diff --git a/.github/workflows/sync-docs.yml b/.github/workflows/sync-docs.yml index 3fe88f718..9cc119dc0 100644 --- a/.github/workflows/sync-docs.yml +++ b/.github/workflows/sync-docs.yml @@ -5,6 +5,8 @@ name: Sync Docs on: push: branches: [main] + paths: + - 'docs/**' pull_request: paths: - 'docs/**' diff --git a/package.json b/package.json index 1cde277b1..a425063c6 100644 --- a/package.json +++ b/package.json @@ -96,7 +96,6 @@ "@serverless/test": "^11.1.1", "@serverlessinc/standards": "*", "adm-zip": "^0.5.10", - "algoliasearch": "^4.23.3", "aws4": "^1.12.0", "chai": "^4.3.7", "chai-as-promised": "^7.1.1", @@ -104,13 +103,11 @@ "eslint": "^8.57.0", "git-list-updated": "^1.2.1", "github-release-from-cc-changelog": "^2.3.0", - "gray-matter": "^4.0.3", "husky": "^4.3.8", "jszip": "^3.10.1", "lint-staged": "^13.2.2", "log": "^6.3.1", "log-node": "^8.0.3", - "marked": "^13.0.0", "mocha": "^9.2.2", "mock-require": "^3.0.3", "ncjsm": "^4.3.2", @@ -120,7 +117,6 @@ "sinon": "^13.0.2", "sinon-chai": "^3.7.0", "standard-version": "^9.5.0", - "striptags": "^3.2.0", "tsx": "^4.15.6", "xml2js": "^0.4.23" }, diff --git a/scripts/node_modules/.bin/esparse b/scripts/node_modules/.bin/esparse new file mode 120000 index 000000000..7423b18b2 --- /dev/null +++ b/scripts/node_modules/.bin/esparse @@ -0,0 +1 @@ +../esprima/bin/esparse.js \ No newline at end of file diff --git a/scripts/node_modules/.bin/esvalidate b/scripts/node_modules/.bin/esvalidate new file mode 120000 index 000000000..16069effb --- /dev/null +++ b/scripts/node_modules/.bin/esvalidate @@ -0,0 +1 @@ +../esprima/bin/esvalidate.js \ No newline at end of file diff --git a/scripts/node_modules/.bin/js-yaml b/scripts/node_modules/.bin/js-yaml new file mode 120000 index 000000000..9dbd010d4 --- /dev/null +++ b/scripts/node_modules/.bin/js-yaml @@ -0,0 +1 @@ +../js-yaml/bin/js-yaml.js \ No newline at end of file diff --git a/scripts/node_modules/.bin/marked b/scripts/node_modules/.bin/marked new file mode 120000 index 000000000..6827ff333 --- /dev/null +++ b/scripts/node_modules/.bin/marked @@ -0,0 +1 @@ +../marked/bin/marked.js \ No newline at end of file diff --git a/scripts/node_modules/.package-lock.json b/scripts/node_modules/.package-lock.json new file mode 100644 index 000000000..e606d8fe3 --- /dev/null +++ b/scripts/node_modules/.package-lock.json @@ -0,0 +1,305 @@ +{ + "name": "scripts", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@algolia/cache-browser-local-storage": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/cache-browser-local-storage/-/cache-browser-local-storage-4.24.0.tgz", + "integrity": "sha512-t63W9BnoXVrGy9iYHBgObNXqYXM3tYXCjDSHeNwnsc324r4o5UiVKUiAB4THQ5z9U5hTj6qUvwg/Ez43ZD85ww==", + "dev": true, + "dependencies": { + "@algolia/cache-common": "4.24.0" + } + }, + "node_modules/@algolia/cache-common": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/cache-common/-/cache-common-4.24.0.tgz", + "integrity": "sha512-emi+v+DmVLpMGhp0V9q9h5CdkURsNmFC+cOS6uK9ndeJm9J4TiqSvPYVu+THUP8P/S08rxf5x2P+p3CfID0Y4g==", + "dev": true + }, + "node_modules/@algolia/cache-in-memory": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/cache-in-memory/-/cache-in-memory-4.24.0.tgz", + "integrity": "sha512-gDrt2so19jW26jY3/MkFg5mEypFIPbPoXsQGQWAi6TrCPsNOSEYepBMPlucqWigsmEy/prp5ug2jy/N3PVG/8w==", + "dev": true, + "dependencies": { + "@algolia/cache-common": "4.24.0" + } + }, + "node_modules/@algolia/client-account": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/client-account/-/client-account-4.24.0.tgz", + "integrity": "sha512-adcvyJ3KjPZFDybxlqnf+5KgxJtBjwTPTeyG2aOyoJvx0Y8dUQAEOEVOJ/GBxX0WWNbmaSrhDURMhc+QeevDsA==", + "dev": true, + "dependencies": { + "@algolia/client-common": "4.24.0", + "@algolia/client-search": "4.24.0", + "@algolia/transporter": "4.24.0" + } + }, + "node_modules/@algolia/client-analytics": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/client-analytics/-/client-analytics-4.24.0.tgz", + "integrity": "sha512-y8jOZt1OjwWU4N2qr8G4AxXAzaa8DBvyHTWlHzX/7Me1LX8OayfgHexqrsL4vSBcoMmVw2XnVW9MhL+Y2ZDJXg==", + "dev": true, + "dependencies": { + "@algolia/client-common": "4.24.0", + "@algolia/client-search": "4.24.0", + "@algolia/requester-common": "4.24.0", + "@algolia/transporter": "4.24.0" + } + }, + "node_modules/@algolia/client-common": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/client-common/-/client-common-4.24.0.tgz", + "integrity": "sha512-bc2ROsNL6w6rqpl5jj/UywlIYC21TwSSoFHKl01lYirGMW+9Eek6r02Tocg4gZ8HAw3iBvu6XQiM3BEbmEMoiA==", + "dev": true, + "dependencies": { + "@algolia/requester-common": "4.24.0", + "@algolia/transporter": "4.24.0" + } + }, + "node_modules/@algolia/client-personalization": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/client-personalization/-/client-personalization-4.24.0.tgz", + "integrity": "sha512-l5FRFm/yngztweU0HdUzz1rC4yoWCFo3IF+dVIVTfEPg906eZg5BOd1k0K6rZx5JzyyoP4LdmOikfkfGsKVE9w==", + "dev": true, + "dependencies": { + "@algolia/client-common": "4.24.0", + "@algolia/requester-common": "4.24.0", + "@algolia/transporter": "4.24.0" + } + }, + "node_modules/@algolia/client-search": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/client-search/-/client-search-4.24.0.tgz", + "integrity": "sha512-uRW6EpNapmLAD0mW47OXqTP8eiIx5F6qN9/x/7HHO6owL3N1IXqydGwW5nhDFBrV+ldouro2W1VX3XlcUXEFCA==", + "dev": true, + "dependencies": { + "@algolia/client-common": "4.24.0", + "@algolia/requester-common": "4.24.0", + "@algolia/transporter": "4.24.0" + } + }, + "node_modules/@algolia/logger-common": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/logger-common/-/logger-common-4.24.0.tgz", + "integrity": "sha512-LLUNjkahj9KtKYrQhFKCzMx0BY3RnNP4FEtO+sBybCjJ73E8jNdaKJ/Dd8A/VA4imVHP5tADZ8pn5B8Ga/wTMA==", + "dev": true + }, + "node_modules/@algolia/logger-console": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/logger-console/-/logger-console-4.24.0.tgz", + "integrity": "sha512-X4C8IoHgHfiUROfoRCV+lzSy+LHMgkoEEU1BbKcsfnV0i0S20zyy0NLww9dwVHUWNfPPxdMU+/wKmLGYf96yTg==", + "dev": true, + "dependencies": { + "@algolia/logger-common": "4.24.0" + } + }, + "node_modules/@algolia/recommend": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/recommend/-/recommend-4.24.0.tgz", + "integrity": "sha512-P9kcgerfVBpfYHDfVZDvvdJv0lEoCvzNlOy2nykyt5bK8TyieYyiD0lguIJdRZZYGre03WIAFf14pgE+V+IBlw==", + "dev": true, + "dependencies": { + "@algolia/cache-browser-local-storage": "4.24.0", + "@algolia/cache-common": "4.24.0", + "@algolia/cache-in-memory": "4.24.0", + "@algolia/client-common": "4.24.0", + "@algolia/client-search": "4.24.0", + "@algolia/logger-common": "4.24.0", + "@algolia/logger-console": "4.24.0", + "@algolia/requester-browser-xhr": "4.24.0", + "@algolia/requester-common": "4.24.0", + "@algolia/requester-node-http": "4.24.0", + "@algolia/transporter": "4.24.0" + } + }, + "node_modules/@algolia/requester-browser-xhr": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/requester-browser-xhr/-/requester-browser-xhr-4.24.0.tgz", + "integrity": "sha512-Z2NxZMb6+nVXSjF13YpjYTdvV3032YTBSGm2vnYvYPA6mMxzM3v5rsCiSspndn9rzIW4Qp1lPHBvuoKJV6jnAA==", + "dev": true, + "dependencies": { + "@algolia/requester-common": "4.24.0" + } + }, + "node_modules/@algolia/requester-common": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/requester-common/-/requester-common-4.24.0.tgz", + "integrity": "sha512-k3CXJ2OVnvgE3HMwcojpvY6d9kgKMPRxs/kVohrwF5WMr2fnqojnycZkxPoEg+bXm8fi5BBfFmOqgYztRtHsQA==", + "dev": true + }, + "node_modules/@algolia/requester-node-http": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/requester-node-http/-/requester-node-http-4.24.0.tgz", + "integrity": "sha512-JF18yTjNOVYvU/L3UosRcvbPMGT9B+/GQWNWnenIImglzNVGpyzChkXLnrSf6uxwVNO6ESGu6oN8MqcGQcjQJw==", + "dev": true, + "dependencies": { + "@algolia/requester-common": "4.24.0" + } + }, + "node_modules/@algolia/transporter": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/transporter/-/transporter-4.24.0.tgz", + "integrity": "sha512-86nI7w6NzWxd1Zp9q3413dRshDqAzSbsQjhcDhPIatEFiZrL1/TjnHL8S7jVKFePlIMzDsZWXAXwXzcok9c5oA==", + "dev": true, + "dependencies": { + "@algolia/cache-common": "4.24.0", + "@algolia/logger-common": "4.24.0", + "@algolia/requester-common": "4.24.0" + } + }, + "node_modules/algoliasearch": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/algoliasearch/-/algoliasearch-4.24.0.tgz", + "integrity": "sha512-bf0QV/9jVejssFBmz2HQLxUadxk574t4iwjCKp5E7NBzwKkrDEhKPISIIjAU/p6K5qDx3qoeh4+26zWN1jmw3g==", + "dev": true, + "dependencies": { + "@algolia/cache-browser-local-storage": "4.24.0", + "@algolia/cache-common": "4.24.0", + "@algolia/cache-in-memory": "4.24.0", + "@algolia/client-account": "4.24.0", + "@algolia/client-analytics": "4.24.0", + "@algolia/client-common": "4.24.0", + "@algolia/client-personalization": "4.24.0", + "@algolia/client-search": "4.24.0", + "@algolia/logger-common": "4.24.0", + "@algolia/logger-console": "4.24.0", + "@algolia/recommend": "4.24.0", + "@algolia/requester-browser-xhr": "4.24.0", + "@algolia/requester-common": "4.24.0", + "@algolia/requester-node-http": "4.24.0", + "@algolia/transporter": "4.24.0" + } + }, + "node_modules/argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "dev": true, + "dependencies": { + "sprintf-js": "~1.0.2" + } + }, + "node_modules/esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "dev": true, + "bin": { + "esparse": "bin/esparse.js", + "esvalidate": "bin/esvalidate.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha512-zCnTtlxNoAiDc3gqY2aYAWFx7XWWiasuF2K8Me5WbN8otHKTUKBwjPtNpRs/rbUZm7KxWAaNj7P1a/p52GbVug==", + "dev": true, + "dependencies": { + "is-extendable": "^0.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/gray-matter": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/gray-matter/-/gray-matter-4.0.3.tgz", + "integrity": "sha512-5v6yZd4JK3eMI3FqqCouswVqwugaA9r4dNZB1wwcmrD02QkV5H0y7XBQW8QwQqEaZY1pM9aqORSORhJRdNK44Q==", + "dev": true, + "dependencies": { + "js-yaml": "^3.13.1", + "kind-of": "^6.0.2", + "section-matter": "^1.0.0", + "strip-bom-string": "^1.0.0" + }, + "engines": { + "node": ">=6.0" + } + }, + "node_modules/is-extendable": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-0.1.1.tgz", + "integrity": "sha512-5BMULNob1vgFX6EjQw5izWDxrecWK9AM72rugNr0TFldMOi0fj6Jk+zeKIt0xGj4cEfQIJth4w3OKWOJ4f+AFw==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/js-yaml": { + "version": "3.14.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", + "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", + "dev": true, + "dependencies": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/kind-of": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz", + "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/marked": { + "version": "13.0.1", + "resolved": "https://registry.npmjs.org/marked/-/marked-13.0.1.tgz", + "integrity": "sha512-7kBohS6GrZKvCsNXZyVVXSW7/hGBHe49ng99YPkDCckSUrrG7MSFLCexsRxptzOmyW2eT5dySh4Md1V6my52fA==", + "dev": true, + "bin": { + "marked": "bin/marked.js" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/section-matter": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/section-matter/-/section-matter-1.0.0.tgz", + "integrity": "sha512-vfD3pmTzGpufjScBh50YHKzEu2lxBWhVEHsNGoEXmCmn2hKGfeNLYMzCJpe8cD7gqX7TJluOVpBkAequ6dgMmA==", + "dev": true, + "dependencies": { + "extend-shallow": "^2.0.1", + "kind-of": "^6.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/sprintf-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==", + "dev": true + }, + "node_modules/strip-bom-string": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/strip-bom-string/-/strip-bom-string-1.0.0.tgz", + "integrity": "sha512-uCC2VHvQRYu+lMh4My/sFNmF2klFymLX1wHJeXnbEJERpV/ZsVuonzerjfrGpIGF7LBVa1O7i9kjiWvJiFck8g==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/striptags": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/striptags/-/striptags-3.2.0.tgz", + "integrity": "sha512-g45ZOGzHDMe2bdYMdIvdAfCQkCTDMGBazSw1ypMowwGIee7ZQ5dU0rBJ8Jqgl+jAKIv4dbeE1jscZq9wid1Tkw==", + "dev": true + } + } +} diff --git a/scripts/node_modules/@algolia/cache-browser-local-storage/dist/cache-browser-local-storage.cjs.js b/scripts/node_modules/@algolia/cache-browser-local-storage/dist/cache-browser-local-storage.cjs.js new file mode 100644 index 000000000..053e947ca --- /dev/null +++ b/scripts/node_modules/@algolia/cache-browser-local-storage/dist/cache-browser-local-storage.cjs.js @@ -0,0 +1,83 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +function createBrowserLocalStorageCache(options) { + const namespaceKey = `algoliasearch-client-js-${options.key}`; + // eslint-disable-next-line functional/no-let + let storage; + const getStorage = () => { + if (storage === undefined) { + storage = options.localStorage || window.localStorage; + } + return storage; + }; + const getNamespace = () => { + return JSON.parse(getStorage().getItem(namespaceKey) || '{}'); + }; + const setNamespace = (namespace) => { + getStorage().setItem(namespaceKey, JSON.stringify(namespace)); + }; + const removeOutdatedCacheItems = () => { + const timeToLive = options.timeToLive ? options.timeToLive * 1000 : null; + const namespace = getNamespace(); + const filteredNamespaceWithoutOldFormattedCacheItems = Object.fromEntries(Object.entries(namespace).filter(([, cacheItem]) => { + return cacheItem.timestamp !== undefined; + })); + setNamespace(filteredNamespaceWithoutOldFormattedCacheItems); + if (!timeToLive) + return; + const filteredNamespaceWithoutExpiredItems = Object.fromEntries(Object.entries(filteredNamespaceWithoutOldFormattedCacheItems).filter(([, cacheItem]) => { + const currentTimestamp = new Date().getTime(); + const isExpired = cacheItem.timestamp + timeToLive < currentTimestamp; + return !isExpired; + })); + setNamespace(filteredNamespaceWithoutExpiredItems); + }; + return { + get(key, defaultValue, events = { + miss: () => Promise.resolve(), + }) { + return Promise.resolve() + .then(() => { + removeOutdatedCacheItems(); + const keyAsString = JSON.stringify(key); + return getNamespace()[keyAsString]; + }) + .then(value => { + return Promise.all([value ? value.value : defaultValue(), value !== undefined]); + }) + .then(([value, exists]) => { + return Promise.all([value, exists || events.miss(value)]); + }) + .then(([value]) => value); + }, + set(key, value) { + return Promise.resolve().then(() => { + const namespace = getNamespace(); + // eslint-disable-next-line functional/immutable-data + namespace[JSON.stringify(key)] = { + timestamp: new Date().getTime(), + value, + }; + getStorage().setItem(namespaceKey, JSON.stringify(namespace)); + return value; + }); + }, + delete(key) { + return Promise.resolve().then(() => { + const namespace = getNamespace(); + // eslint-disable-next-line functional/immutable-data + delete namespace[JSON.stringify(key)]; + getStorage().setItem(namespaceKey, JSON.stringify(namespace)); + }); + }, + clear() { + return Promise.resolve().then(() => { + getStorage().removeItem(namespaceKey); + }); + }, + }; +} + +exports.createBrowserLocalStorageCache = createBrowserLocalStorageCache; diff --git a/scripts/node_modules/@algolia/cache-browser-local-storage/dist/cache-browser-local-storage.d.ts b/scripts/node_modules/@algolia/cache-browser-local-storage/dist/cache-browser-local-storage.d.ts new file mode 100644 index 000000000..dd10a374c --- /dev/null +++ b/scripts/node_modules/@algolia/cache-browser-local-storage/dist/cache-browser-local-storage.d.ts @@ -0,0 +1,31 @@ +import { Cache as Cache_2 } from '@algolia/cache-common'; + +export declare type BrowserLocalStorageCacheItem = { + /** + * The cache item creation timestamp. + */ + readonly timestamp: number; + /** + * The cache item value + */ + readonly value: any; +}; + +export declare type BrowserLocalStorageOptions = { + /** + * The cache key. + */ + readonly key: string; + /** + * The time to live for each cached item in seconds. + */ + readonly timeToLive?: number; + /** + * The native local storage implementation. + */ + readonly localStorage?: Storage; +}; + +export declare function createBrowserLocalStorageCache(options: BrowserLocalStorageOptions): Cache_2; + +export { } diff --git a/scripts/node_modules/@algolia/cache-browser-local-storage/dist/cache-browser-local-storage.esm.js b/scripts/node_modules/@algolia/cache-browser-local-storage/dist/cache-browser-local-storage.esm.js new file mode 100644 index 000000000..24ad97473 --- /dev/null +++ b/scripts/node_modules/@algolia/cache-browser-local-storage/dist/cache-browser-local-storage.esm.js @@ -0,0 +1,79 @@ +function createBrowserLocalStorageCache(options) { + const namespaceKey = `algoliasearch-client-js-${options.key}`; + // eslint-disable-next-line functional/no-let + let storage; + const getStorage = () => { + if (storage === undefined) { + storage = options.localStorage || window.localStorage; + } + return storage; + }; + const getNamespace = () => { + return JSON.parse(getStorage().getItem(namespaceKey) || '{}'); + }; + const setNamespace = (namespace) => { + getStorage().setItem(namespaceKey, JSON.stringify(namespace)); + }; + const removeOutdatedCacheItems = () => { + const timeToLive = options.timeToLive ? options.timeToLive * 1000 : null; + const namespace = getNamespace(); + const filteredNamespaceWithoutOldFormattedCacheItems = Object.fromEntries(Object.entries(namespace).filter(([, cacheItem]) => { + return cacheItem.timestamp !== undefined; + })); + setNamespace(filteredNamespaceWithoutOldFormattedCacheItems); + if (!timeToLive) + return; + const filteredNamespaceWithoutExpiredItems = Object.fromEntries(Object.entries(filteredNamespaceWithoutOldFormattedCacheItems).filter(([, cacheItem]) => { + const currentTimestamp = new Date().getTime(); + const isExpired = cacheItem.timestamp + timeToLive < currentTimestamp; + return !isExpired; + })); + setNamespace(filteredNamespaceWithoutExpiredItems); + }; + return { + get(key, defaultValue, events = { + miss: () => Promise.resolve(), + }) { + return Promise.resolve() + .then(() => { + removeOutdatedCacheItems(); + const keyAsString = JSON.stringify(key); + return getNamespace()[keyAsString]; + }) + .then(value => { + return Promise.all([value ? value.value : defaultValue(), value !== undefined]); + }) + .then(([value, exists]) => { + return Promise.all([value, exists || events.miss(value)]); + }) + .then(([value]) => value); + }, + set(key, value) { + return Promise.resolve().then(() => { + const namespace = getNamespace(); + // eslint-disable-next-line functional/immutable-data + namespace[JSON.stringify(key)] = { + timestamp: new Date().getTime(), + value, + }; + getStorage().setItem(namespaceKey, JSON.stringify(namespace)); + return value; + }); + }, + delete(key) { + return Promise.resolve().then(() => { + const namespace = getNamespace(); + // eslint-disable-next-line functional/immutable-data + delete namespace[JSON.stringify(key)]; + getStorage().setItem(namespaceKey, JSON.stringify(namespace)); + }); + }, + clear() { + return Promise.resolve().then(() => { + getStorage().removeItem(namespaceKey); + }); + }, + }; +} + +export { createBrowserLocalStorageCache }; diff --git a/scripts/node_modules/@algolia/cache-browser-local-storage/index.js b/scripts/node_modules/@algolia/cache-browser-local-storage/index.js new file mode 100644 index 000000000..618c06181 --- /dev/null +++ b/scripts/node_modules/@algolia/cache-browser-local-storage/index.js @@ -0,0 +1,2 @@ +// eslint-disable-next-line functional/immutable-data, import/no-commonjs +module.exports = require('./dist/cache-browser-local-storage.cjs.js'); diff --git a/scripts/node_modules/@algolia/cache-browser-local-storage/package.json b/scripts/node_modules/@algolia/cache-browser-local-storage/package.json new file mode 100644 index 000000000..1ebc84327 --- /dev/null +++ b/scripts/node_modules/@algolia/cache-browser-local-storage/package.json @@ -0,0 +1,22 @@ +{ + "name": "@algolia/cache-browser-local-storage", + "version": "4.24.0", + "private": false, + "description": "Promise-based cache library for browser using local storage.", + "repository": { + "type": "git", + "url": "git://github.com/algolia/algoliasearch-client-javascript.git" + }, + "license": "MIT", + "sideEffects": false, + "main": "index.js", + "module": "dist/cache-browser-local-storage.esm.js", + "types": "dist/cache-browser-local-storage.d.ts", + "files": [ + "index.js", + "dist" + ], + "dependencies": { + "@algolia/cache-common": "4.24.0" + } +} diff --git a/scripts/node_modules/@algolia/cache-common/dist/cache-common.cjs.js b/scripts/node_modules/@algolia/cache-common/dist/cache-common.cjs.js new file mode 100644 index 000000000..906157395 --- /dev/null +++ b/scripts/node_modules/@algolia/cache-common/dist/cache-common.cjs.js @@ -0,0 +1,61 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +// @todo Add logger on options to debug when caches go wrong. +function createFallbackableCache(options) { + const caches = [...options.caches]; + const current = caches.shift(); // eslint-disable-line functional/immutable-data + if (current === undefined) { + return createNullCache(); + } + return { + get(key, defaultValue, events = { + miss: () => Promise.resolve(), + }) { + return current.get(key, defaultValue, events).catch(() => { + return createFallbackableCache({ caches }).get(key, defaultValue, events); + }); + }, + set(key, value) { + return current.set(key, value).catch(() => { + return createFallbackableCache({ caches }).set(key, value); + }); + }, + delete(key) { + return current.delete(key).catch(() => { + return createFallbackableCache({ caches }).delete(key); + }); + }, + clear() { + return current.clear().catch(() => { + return createFallbackableCache({ caches }).clear(); + }); + }, + }; +} + +function createNullCache() { + return { + get(_key, defaultValue, events = { + miss: () => Promise.resolve(), + }) { + const value = defaultValue(); + return value + .then(result => Promise.all([result, events.miss(result)])) + .then(([result]) => result); + }, + set(_key, value) { + return Promise.resolve(value); + }, + delete(_key) { + return Promise.resolve(); + }, + clear() { + return Promise.resolve(); + }, + }; +} + +exports.createFallbackableCache = createFallbackableCache; +exports.createNullCache = createNullCache; diff --git a/scripts/node_modules/@algolia/cache-common/dist/cache-common.d.ts b/scripts/node_modules/@algolia/cache-common/dist/cache-common.d.ts new file mode 100644 index 000000000..685e71efc --- /dev/null +++ b/scripts/node_modules/@algolia/cache-common/dist/cache-common.d.ts @@ -0,0 +1,41 @@ +import { Cache as Cache_3 } from '@algolia/cache-common'; + +declare type Cache_2 = { + /** + * Gets the value of the given `key`. + */ + readonly get: (key: object | string, defaultValue: () => Readonly>, events?: CacheEvents) => Readonly>; + /** + * Sets the given value with the given `key`. + */ + readonly set: (key: object | string, value: TValue) => Readonly>; + /** + * Deletes the given `key`. + */ + readonly delete: (key: object | string) => Readonly>; + /** + * Clears the cache. + */ + readonly clear: () => Readonly>; +}; +export { Cache_2 as Cache } + +export declare type CacheEvents = { + /** + * The callback when the given `key` is missing from the cache. + */ + readonly miss: (value: TValue) => Readonly>; +}; + +export declare function createFallbackableCache(options: FallbackableCacheOptions): Cache_2; + +export declare function createNullCache(): Cache_2; + +export declare type FallbackableCacheOptions = { + /** + * List of caches order by priority. + */ + readonly caches: readonly Cache_3[]; +}; + +export { } diff --git a/scripts/node_modules/@algolia/cache-common/dist/cache-common.esm.js b/scripts/node_modules/@algolia/cache-common/dist/cache-common.esm.js new file mode 100644 index 000000000..b42b26306 --- /dev/null +++ b/scripts/node_modules/@algolia/cache-common/dist/cache-common.esm.js @@ -0,0 +1,56 @@ +// @todo Add logger on options to debug when caches go wrong. +function createFallbackableCache(options) { + const caches = [...options.caches]; + const current = caches.shift(); // eslint-disable-line functional/immutable-data + if (current === undefined) { + return createNullCache(); + } + return { + get(key, defaultValue, events = { + miss: () => Promise.resolve(), + }) { + return current.get(key, defaultValue, events).catch(() => { + return createFallbackableCache({ caches }).get(key, defaultValue, events); + }); + }, + set(key, value) { + return current.set(key, value).catch(() => { + return createFallbackableCache({ caches }).set(key, value); + }); + }, + delete(key) { + return current.delete(key).catch(() => { + return createFallbackableCache({ caches }).delete(key); + }); + }, + clear() { + return current.clear().catch(() => { + return createFallbackableCache({ caches }).clear(); + }); + }, + }; +} + +function createNullCache() { + return { + get(_key, defaultValue, events = { + miss: () => Promise.resolve(), + }) { + const value = defaultValue(); + return value + .then(result => Promise.all([result, events.miss(result)])) + .then(([result]) => result); + }, + set(_key, value) { + return Promise.resolve(value); + }, + delete(_key) { + return Promise.resolve(); + }, + clear() { + return Promise.resolve(); + }, + }; +} + +export { createFallbackableCache, createNullCache }; diff --git a/scripts/node_modules/@algolia/cache-common/index.js b/scripts/node_modules/@algolia/cache-common/index.js new file mode 100644 index 000000000..b121ae501 --- /dev/null +++ b/scripts/node_modules/@algolia/cache-common/index.js @@ -0,0 +1,2 @@ +// eslint-disable-next-line functional/immutable-data, import/no-commonjs +module.exports = require('./dist/cache-common.cjs.js'); diff --git a/scripts/node_modules/@algolia/cache-common/package.json b/scripts/node_modules/@algolia/cache-common/package.json new file mode 100644 index 000000000..960738e61 --- /dev/null +++ b/scripts/node_modules/@algolia/cache-common/package.json @@ -0,0 +1,19 @@ +{ + "name": "@algolia/cache-common", + "version": "4.24.0", + "private": false, + "description": "Common interfaces for promise-based caching libraries", + "repository": { + "type": "git", + "url": "git://github.com/algolia/algoliasearch-client-js.git" + }, + "license": "MIT", + "sideEffects": false, + "main": "index.js", + "module": "dist/cache-common.esm.js", + "types": "dist/cache-common.d.ts", + "files": [ + "index.js", + "dist" + ] +} diff --git a/scripts/node_modules/@algolia/cache-in-memory/dist/cache-in-memory.cjs.js b/scripts/node_modules/@algolia/cache-in-memory/dist/cache-in-memory.cjs.js new file mode 100644 index 000000000..cd2603ddf --- /dev/null +++ b/scripts/node_modules/@algolia/cache-in-memory/dist/cache-in-memory.cjs.js @@ -0,0 +1,37 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +function createInMemoryCache(options = { serializable: true }) { + // eslint-disable-next-line functional/no-let + let cache = {}; + return { + get(key, defaultValue, events = { + miss: () => Promise.resolve(), + }) { + const keyAsString = JSON.stringify(key); + if (keyAsString in cache) { + return Promise.resolve(options.serializable ? JSON.parse(cache[keyAsString]) : cache[keyAsString]); + } + const promise = defaultValue(); + const miss = (events && events.miss) || (() => Promise.resolve()); + return promise.then((value) => miss(value)).then(() => promise); + }, + set(key, value) { + // eslint-disable-next-line functional/immutable-data + cache[JSON.stringify(key)] = options.serializable ? JSON.stringify(value) : value; + return Promise.resolve(value); + }, + delete(key) { + // eslint-disable-next-line functional/immutable-data + delete cache[JSON.stringify(key)]; + return Promise.resolve(); + }, + clear() { + cache = {}; + return Promise.resolve(); + }, + }; +} + +exports.createInMemoryCache = createInMemoryCache; diff --git a/scripts/node_modules/@algolia/cache-in-memory/dist/cache-in-memory.d.ts b/scripts/node_modules/@algolia/cache-in-memory/dist/cache-in-memory.d.ts new file mode 100644 index 000000000..018c1de99 --- /dev/null +++ b/scripts/node_modules/@algolia/cache-in-memory/dist/cache-in-memory.d.ts @@ -0,0 +1,12 @@ +import { Cache as Cache_2 } from '@algolia/cache-common'; + +export declare function createInMemoryCache(options?: InMemoryCacheOptions): Cache_2; + +export declare type InMemoryCacheOptions = { + /** + * If keys and values should be serialized using `JSON.stringify`. + */ + readonly serializable?: boolean; +}; + +export { } diff --git a/scripts/node_modules/@algolia/cache-in-memory/dist/cache-in-memory.esm.js b/scripts/node_modules/@algolia/cache-in-memory/dist/cache-in-memory.esm.js new file mode 100644 index 000000000..3f5555ff9 --- /dev/null +++ b/scripts/node_modules/@algolia/cache-in-memory/dist/cache-in-memory.esm.js @@ -0,0 +1,33 @@ +function createInMemoryCache(options = { serializable: true }) { + // eslint-disable-next-line functional/no-let + let cache = {}; + return { + get(key, defaultValue, events = { + miss: () => Promise.resolve(), + }) { + const keyAsString = JSON.stringify(key); + if (keyAsString in cache) { + return Promise.resolve(options.serializable ? JSON.parse(cache[keyAsString]) : cache[keyAsString]); + } + const promise = defaultValue(); + const miss = (events && events.miss) || (() => Promise.resolve()); + return promise.then((value) => miss(value)).then(() => promise); + }, + set(key, value) { + // eslint-disable-next-line functional/immutable-data + cache[JSON.stringify(key)] = options.serializable ? JSON.stringify(value) : value; + return Promise.resolve(value); + }, + delete(key) { + // eslint-disable-next-line functional/immutable-data + delete cache[JSON.stringify(key)]; + return Promise.resolve(); + }, + clear() { + cache = {}; + return Promise.resolve(); + }, + }; +} + +export { createInMemoryCache }; diff --git a/scripts/node_modules/@algolia/cache-in-memory/index.js b/scripts/node_modules/@algolia/cache-in-memory/index.js new file mode 100644 index 000000000..14ac87838 --- /dev/null +++ b/scripts/node_modules/@algolia/cache-in-memory/index.js @@ -0,0 +1,2 @@ +// eslint-disable-next-line functional/immutable-data, import/no-commonjs +module.exports = require('./dist/cache-in-memory.cjs.js'); diff --git a/scripts/node_modules/@algolia/cache-in-memory/package.json b/scripts/node_modules/@algolia/cache-in-memory/package.json new file mode 100644 index 000000000..305279eb4 --- /dev/null +++ b/scripts/node_modules/@algolia/cache-in-memory/package.json @@ -0,0 +1,22 @@ +{ + "name": "@algolia/cache-in-memory", + "version": "4.24.0", + "private": false, + "description": "Promise-based cache library using memory.", + "repository": { + "type": "git", + "url": "git://github.com/algolia/algoliasearch-client-javascript.git" + }, + "license": "MIT", + "sideEffects": false, + "main": "index.js", + "module": "dist/cache-in-memory.esm.js", + "types": "dist/cache-in-memory.d.ts", + "files": [ + "index.js", + "dist" + ], + "dependencies": { + "@algolia/cache-common": "4.24.0" + } +} diff --git a/scripts/node_modules/@algolia/client-account/dist/client-account.cjs.js b/scripts/node_modules/@algolia/client-account/dist/client-account.cjs.js new file mode 100644 index 000000000..bae1f22dc --- /dev/null +++ b/scripts/node_modules/@algolia/client-account/dist/client-account.cjs.js @@ -0,0 +1,69 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var clientCommon = require('@algolia/client-common'); +var clientSearch = require('@algolia/client-search'); + +function createDestinationIndiceExistsError() { + return { + name: 'DestinationIndiceAlreadyExistsError', + message: 'Destination indice already exists.', + }; +} + +function createIndicesInSameAppError(appId) { + return { + name: 'IndicesInTheSameAppError', + message: 'Indices are in the same application. Use SearchClient.copyIndex instead.', + appId, + }; +} + +const accountCopyIndex = (source, destination, requestOptions) => { + // eslint-disable-next-line functional/prefer-readonly-type + const responses = []; + const promise = clientSearch.exists(destination)() + .then(res => { + if (source.appId === destination.appId) { + throw createIndicesInSameAppError(source.appId); + } + if (res) { + throw createDestinationIndiceExistsError(); + } + }) + .then(() => clientSearch.getSettings(source)()) + .then(settings => + // eslint-disable-next-line functional/immutable-data + responses.push(clientSearch.setSettings(destination)(settings, requestOptions))) + .then(() => clientSearch.browseRules(source)({ + // eslint-disable-next-line functional/immutable-data + batch: rules => responses.push(clientSearch.saveRules(destination)(rules, requestOptions)), + })) + .then(() => clientSearch.browseSynonyms(source)({ + // eslint-disable-next-line functional/immutable-data + batch: synonyms => responses.push(clientSearch.saveSynonyms(destination)(synonyms, requestOptions)), + })) + .then(() => clientSearch.browseObjects(source)({ + // eslint-disable-next-line functional/immutable-data + batch: objects => responses.push(clientSearch.saveObjects(destination)(objects, requestOptions)), + })); + return clientCommon.createWaitablePromise( + /** + * The original promise will return an array of async responses, now + * we need to resolve that array of async responses using a + * `Promise.all`, and then resolve `void` for the end-user. + */ + promise.then(() => Promise.all(responses)).then(() => undefined), + /** + * Next, if the end-user calls the `wait` method, we need to also call + * the `wait` method on each element of of async responses. + */ + (_response, waitRequestOptions) => { + return Promise.all(responses.map(response => response.wait(waitRequestOptions))); + }); +}; + +exports.accountCopyIndex = accountCopyIndex; +exports.createDestinationIndiceExistsError = createDestinationIndiceExistsError; +exports.createIndicesInSameAppError = createIndicesInSameAppError; diff --git a/scripts/node_modules/@algolia/client-account/dist/client-account.d.ts b/scripts/node_modules/@algolia/client-account/dist/client-account.d.ts new file mode 100644 index 000000000..2e5115e52 --- /dev/null +++ b/scripts/node_modules/@algolia/client-account/dist/client-account.d.ts @@ -0,0 +1,18 @@ +import { RequestOptions } from '@algolia/transporter'; +import { SearchIndex } from '@algolia/client-search'; +import { WaitablePromise } from '@algolia/client-common'; + +export declare const accountCopyIndex: (source: SearchIndex, destination: SearchIndex, requestOptions?: RequestOptions | undefined) => WaitablePromise; + +export declare function createDestinationIndiceExistsError(): Error; + +export declare function createIndicesInSameAppError(appId: string): IndicesInSameAppError; + +export declare type IndicesInSameAppError = Error & { + /** + * The app id. + */ + readonly appId: string; +}; + +export { } diff --git a/scripts/node_modules/@algolia/client-account/dist/client-account.esm.js b/scripts/node_modules/@algolia/client-account/dist/client-account.esm.js new file mode 100644 index 000000000..dd2299e66 --- /dev/null +++ b/scripts/node_modules/@algolia/client-account/dist/client-account.esm.js @@ -0,0 +1,63 @@ +import { createWaitablePromise } from '@algolia/client-common'; +import { exists, getSettings, setSettings, browseRules, saveRules, browseSynonyms, saveSynonyms, browseObjects, saveObjects } from '@algolia/client-search'; + +function createDestinationIndiceExistsError() { + return { + name: 'DestinationIndiceAlreadyExistsError', + message: 'Destination indice already exists.', + }; +} + +function createIndicesInSameAppError(appId) { + return { + name: 'IndicesInTheSameAppError', + message: 'Indices are in the same application. Use SearchClient.copyIndex instead.', + appId, + }; +} + +const accountCopyIndex = (source, destination, requestOptions) => { + // eslint-disable-next-line functional/prefer-readonly-type + const responses = []; + const promise = exists(destination)() + .then(res => { + if (source.appId === destination.appId) { + throw createIndicesInSameAppError(source.appId); + } + if (res) { + throw createDestinationIndiceExistsError(); + } + }) + .then(() => getSettings(source)()) + .then(settings => + // eslint-disable-next-line functional/immutable-data + responses.push(setSettings(destination)(settings, requestOptions))) + .then(() => browseRules(source)({ + // eslint-disable-next-line functional/immutable-data + batch: rules => responses.push(saveRules(destination)(rules, requestOptions)), + })) + .then(() => browseSynonyms(source)({ + // eslint-disable-next-line functional/immutable-data + batch: synonyms => responses.push(saveSynonyms(destination)(synonyms, requestOptions)), + })) + .then(() => browseObjects(source)({ + // eslint-disable-next-line functional/immutable-data + batch: objects => responses.push(saveObjects(destination)(objects, requestOptions)), + })); + return createWaitablePromise( + /** + * The original promise will return an array of async responses, now + * we need to resolve that array of async responses using a + * `Promise.all`, and then resolve `void` for the end-user. + */ + promise.then(() => Promise.all(responses)).then(() => undefined), + /** + * Next, if the end-user calls the `wait` method, we need to also call + * the `wait` method on each element of of async responses. + */ + (_response, waitRequestOptions) => { + return Promise.all(responses.map(response => response.wait(waitRequestOptions))); + }); +}; + +export { accountCopyIndex, createDestinationIndiceExistsError, createIndicesInSameAppError }; diff --git a/scripts/node_modules/@algolia/client-account/index.js b/scripts/node_modules/@algolia/client-account/index.js new file mode 100644 index 000000000..ea5e5605a --- /dev/null +++ b/scripts/node_modules/@algolia/client-account/index.js @@ -0,0 +1,2 @@ +// eslint-disable-next-line functional/immutable-data, import/no-commonjs +module.exports = require('./dist/client-account.cjs.js'); diff --git a/scripts/node_modules/@algolia/client-account/package.json b/scripts/node_modules/@algolia/client-account/package.json new file mode 100644 index 000000000..2ab7fb4f8 --- /dev/null +++ b/scripts/node_modules/@algolia/client-account/package.json @@ -0,0 +1,23 @@ +{ + "name": "@algolia/client-account", + "version": "4.24.0", + "private": false, + "repository": { + "type": "git", + "url": "git://github.com/algolia/algoliasearch-client-javascript.git" + }, + "license": "MIT", + "sideEffects": false, + "main": "index.js", + "module": "dist/client-account.esm.js", + "types": "dist/client-account.d.ts", + "files": [ + "index.js", + "dist" + ], + "dependencies": { + "@algolia/client-common": "4.24.0", + "@algolia/client-search": "4.24.0", + "@algolia/transporter": "4.24.0" + } +} diff --git a/scripts/node_modules/@algolia/client-analytics/dist/client-analytics.cjs.js b/scripts/node_modules/@algolia/client-analytics/dist/client-analytics.cjs.js new file mode 100644 index 000000000..ad8292e81 --- /dev/null +++ b/scripts/node_modules/@algolia/client-analytics/dist/client-analytics.cjs.js @@ -0,0 +1,80 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var clientCommon = require('@algolia/client-common'); +var transporter = require('@algolia/transporter'); +var requesterCommon = require('@algolia/requester-common'); + +const createAnalyticsClient = options => { + const region = options.region || 'us'; + const auth = clientCommon.createAuth(clientCommon.AuthMode.WithinHeaders, options.appId, options.apiKey); + const transporter$1 = transporter.createTransporter({ + hosts: [{ url: `analytics.${region}.algolia.com` }], + ...options, + headers: { + ...auth.headers(), + ...{ 'content-type': 'application/json' }, + ...options.headers, + }, + queryParameters: { + ...auth.queryParameters(), + ...options.queryParameters, + }, + }); + const appId = options.appId; + return clientCommon.addMethods({ appId, transporter: transporter$1 }, options.methods); +}; + +const addABTest = (base) => { + return (abTest, requestOptions) => { + return base.transporter.write({ + method: requesterCommon.MethodEnum.Post, + path: '2/abtests', + data: abTest, + }, requestOptions); + }; +}; + +const deleteABTest = (base) => { + return (abTestID, requestOptions) => { + return base.transporter.write({ + method: requesterCommon.MethodEnum.Delete, + path: clientCommon.encode('2/abtests/%s', abTestID), + }, requestOptions); + }; +}; + +const getABTest = (base) => { + return (abTestID, requestOptions) => { + return base.transporter.read({ + method: requesterCommon.MethodEnum.Get, + path: clientCommon.encode('2/abtests/%s', abTestID), + }, requestOptions); + }; +}; + +const getABTests = (base) => { + return (requestOptions) => { + return base.transporter.read({ + method: requesterCommon.MethodEnum.Get, + path: '2/abtests', + }, requestOptions); + }; +}; + +const stopABTest = (base) => { + return (abTestID, requestOptions) => { + return base.transporter.write({ + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode('2/abtests/%s/stop', abTestID), + }, requestOptions); + }; +}; + +exports.addABTest = addABTest; +exports.createAnalyticsClient = createAnalyticsClient; +exports.deleteABTest = deleteABTest; +exports.getABTest = getABTest; +exports.getABTests = getABTests; +exports.stopABTest = stopABTest; diff --git a/scripts/node_modules/@algolia/client-analytics/dist/client-analytics.d.ts b/scripts/node_modules/@algolia/client-analytics/dist/client-analytics.d.ts new file mode 100644 index 000000000..04d9cc88e --- /dev/null +++ b/scripts/node_modules/@algolia/client-analytics/dist/client-analytics.d.ts @@ -0,0 +1,251 @@ +import { ClientTransporterOptions } from '@algolia/client-common'; +import { CreateClient } from '@algolia/client-common'; +import { RequestOptions } from '@algolia/transporter'; +import { SearchOptions } from '@algolia/client-search'; +import { Transporter } from '@algolia/transporter'; + +export declare type ABTest = { + /** + * The ab test name. + */ + readonly name: string; + /** + * The ab test list of variants. + */ + readonly variants: readonly Variant[]; + /** + * The ab test end date, if any. + */ + readonly endAt: string; +}; + +export declare const addABTest: (base: AnalyticsClient) => (abTest: ABTest, requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare type AddABTestResponse = { + /** + * The ab test unique identifier. + */ + abTestID: number; + /** + * The operation task id. May be used to perform a wait task. + */ + taskID: number; + /** + * The index name where the ab test is attached to. + */ + index: string; +}; + +export declare type AnalyticsClient = { + /** + * The application id. + */ + readonly appId: string; + /** + * The underlying transporter. + */ + readonly transporter: Transporter; +}; + +export declare type AnalyticsClientOptions = { + /** + * The application id. + */ + readonly appId: string; + /** + * The api key. + */ + readonly apiKey: string; + /** + * The prefered region. + */ + readonly region?: 'de' | 'us'; +}; + +export declare const createAnalyticsClient: CreateClient; + +export declare const deleteABTest: (base: AnalyticsClient) => (abTestID: number, requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare type DeleteABTestResponse = { + /** + * The ab test unique identifier. + */ + abTestID: number; + /** + * The operation task id. May be used to perform a wait task. + */ + taskID: number; + /** + * The index name where the ab test was attached to. + */ + index: string; +}; + +export declare const getABTest: (base: AnalyticsClient) => (abTestID: number, requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare type GetABTestResponse = { + /** + * The ab test name. + */ + name: string; + /** + * The ab test status. + */ + status: string; + /** + * The ab test list of variants. + */ + variants: VariantResponse[]; + /** + * The ab test end date, if any. + */ + endAt: string; + /** + * The ab test created date, if any. + */ + createdAt: string; + /** + * The ab test updated date. + */ + updatedAt: string; + /** + * The ab test unique identifier. + */ + abTestID: number; + /** + * The ab test significance based on click data. Should be higher than 0.95 to be considered significant - no matter which variant is winning. + */ + clickSignificance: number; + /** + * + * The ab test significance based on conversion data. Should be higher than 0.95 to be considered significant - no matter which variant is winning. + */ + conversionSignificance: number; +}; + +export declare const getABTests: (base: AnalyticsClient) => (requestOptions?: (RequestOptions & GetABTestsOptions) | undefined) => Readonly>; + +export declare type GetABTestsOptions = { + /** + * The number of ab tests to skip from the biginning of the list. + */ + readonly offset?: number; + /** + * The limit of the number of ab tests returned. + */ + readonly limit?: number; + /** + * Filters the returned ab tests by any indices starting with the + * provided prefix that are assigned to either variant of an ab test. + */ + readonly indexPrefix?: string; + /** + * Filters the returned ab tests by any indices ending with the + * provided suffix that are assigned to either variant of an ab test. + */ + readonly indexSuffix?: string; +}; + +export declare type GetABTestsResponse = { + /** + * The number of ab tests within this response. + */ + count: number; + /** + * The total of ab tests. + */ + total: number; + /** + * The list of ab tests. + */ + abtests: GetABTestResponse[] | null; +}; + +export declare const stopABTest: (base: AnalyticsClient) => (abTestID: number, requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare type StopABTestResponse = { + /** + * The ab test unique identifier. + */ + abTestID: number; + /** + * The operation task id. May be used to perform a wait task. + */ + taskID: number; + /** + * The index name where the ab test is attached to. + */ + index: string; +}; + +export declare type Variant = { + /** + * The index name. + */ + readonly index: string; + /** + * Description of the variant. Useful when seing the results in the dashboard or via the API. + */ + readonly description?: string; + /** + * Percentage of the traffic that should be going to the variant. The sum of the percentage should be equal to 100. + */ + readonly trafficPercentage: number; + /** + * The search parameters. + */ + readonly customSearchParameters?: SearchOptions; +}; + +export declare type VariantResponse = Variant & { + /** + * Average click position for the variant. + */ + averageClickPosition?: number; + /** + * Distinct click count for the variant. + */ + clickCount?: number; + /** + * Click through rate for the variant. + */ + clickThroughRate?: number; + /** + * Click through rate for the variant. + */ + conversionCount?: number; + /** + * Distinct conversion count for the variant. + */ + conversionRate?: number; + /** + * No result count. + */ + noResultCount?: number; + /** + * Tracked search count. + */ + trackedSearchCount?: number; + /** + * Search count. + */ + searchCount?: number; + /** + * User count. + */ + userCount?: number; + /** + * Count of the tracked searches attributed to outlier traffic that were removed from the A/B test. + */ + outlierTrackedSearchesCount?: number; + /** + * Count of users attributed to outlier traffic that were removed from the A/B test. + */ + outlierUsersCount?: number; + /** + * The search parameters. + */ + customSearchParameters?: SearchOptions; +}; + +export { } diff --git a/scripts/node_modules/@algolia/client-analytics/dist/client-analytics.esm.js b/scripts/node_modules/@algolia/client-analytics/dist/client-analytics.esm.js new file mode 100644 index 000000000..0c907f580 --- /dev/null +++ b/scripts/node_modules/@algolia/client-analytics/dist/client-analytics.esm.js @@ -0,0 +1,71 @@ +import { createAuth, AuthMode, addMethods, encode } from '@algolia/client-common'; +import { createTransporter } from '@algolia/transporter'; +import { MethodEnum } from '@algolia/requester-common'; + +const createAnalyticsClient = options => { + const region = options.region || 'us'; + const auth = createAuth(AuthMode.WithinHeaders, options.appId, options.apiKey); + const transporter = createTransporter({ + hosts: [{ url: `analytics.${region}.algolia.com` }], + ...options, + headers: { + ...auth.headers(), + ...{ 'content-type': 'application/json' }, + ...options.headers, + }, + queryParameters: { + ...auth.queryParameters(), + ...options.queryParameters, + }, + }); + const appId = options.appId; + return addMethods({ appId, transporter }, options.methods); +}; + +const addABTest = (base) => { + return (abTest, requestOptions) => { + return base.transporter.write({ + method: MethodEnum.Post, + path: '2/abtests', + data: abTest, + }, requestOptions); + }; +}; + +const deleteABTest = (base) => { + return (abTestID, requestOptions) => { + return base.transporter.write({ + method: MethodEnum.Delete, + path: encode('2/abtests/%s', abTestID), + }, requestOptions); + }; +}; + +const getABTest = (base) => { + return (abTestID, requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Get, + path: encode('2/abtests/%s', abTestID), + }, requestOptions); + }; +}; + +const getABTests = (base) => { + return (requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Get, + path: '2/abtests', + }, requestOptions); + }; +}; + +const stopABTest = (base) => { + return (abTestID, requestOptions) => { + return base.transporter.write({ + method: MethodEnum.Post, + path: encode('2/abtests/%s/stop', abTestID), + }, requestOptions); + }; +}; + +export { addABTest, createAnalyticsClient, deleteABTest, getABTest, getABTests, stopABTest }; diff --git a/scripts/node_modules/@algolia/client-analytics/index.js b/scripts/node_modules/@algolia/client-analytics/index.js new file mode 100644 index 000000000..3588503aa --- /dev/null +++ b/scripts/node_modules/@algolia/client-analytics/index.js @@ -0,0 +1,2 @@ +// eslint-disable-next-line functional/immutable-data, import/no-commonjs +module.exports = require('./dist/client-analytics.cjs.js'); diff --git a/scripts/node_modules/@algolia/client-analytics/package.json b/scripts/node_modules/@algolia/client-analytics/package.json new file mode 100644 index 000000000..7ecfea994 --- /dev/null +++ b/scripts/node_modules/@algolia/client-analytics/package.json @@ -0,0 +1,24 @@ +{ + "name": "@algolia/client-analytics", + "version": "4.24.0", + "private": false, + "repository": { + "type": "git", + "url": "git://github.com/algolia/algoliasearch-client-javascript.git" + }, + "license": "MIT", + "sideEffects": false, + "main": "index.js", + "module": "dist/client-analytics.esm.js", + "types": "dist/client-analytics.d.ts", + "files": [ + "index.js", + "dist" + ], + "dependencies": { + "@algolia/client-common": "4.24.0", + "@algolia/client-search": "4.24.0", + "@algolia/requester-common": "4.24.0", + "@algolia/transporter": "4.24.0" + } +} diff --git a/scripts/node_modules/@algolia/client-common/dist/client-common.cjs.js b/scripts/node_modules/@algolia/client-common/dist/client-common.cjs.js new file mode 100644 index 000000000..b5df588e9 --- /dev/null +++ b/scripts/node_modules/@algolia/client-common/dist/client-common.cjs.js @@ -0,0 +1,101 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +function createAuth(authMode, appId, apiKey) { + const credentials = { + 'x-algolia-api-key': apiKey, + 'x-algolia-application-id': appId, + }; + return { + headers() { + return authMode === AuthMode.WithinHeaders ? credentials : {}; + }, + queryParameters() { + return authMode === AuthMode.WithinQueryParameters ? credentials : {}; + }, + }; +} + +function createRetryablePromise(callback) { + let retriesCount = 0; // eslint-disable-line functional/no-let + const retry = () => { + retriesCount++; + return new Promise((resolve) => { + setTimeout(() => { + resolve(callback(retry)); + }, Math.min(100 * retriesCount, 1000)); + }); + }; + return callback(retry); +} + +function createWaitablePromise(promise, wait = (_response, _requestOptions) => { + return Promise.resolve(); +}) { + // eslint-disable-next-line functional/immutable-data + return Object.assign(promise, { + wait(requestOptions) { + return createWaitablePromise(promise + .then(response => Promise.all([wait(response, requestOptions), response])) + .then(promiseResults => promiseResults[1])); + }, + }); +} + +// eslint-disable-next-line functional/prefer-readonly-type +function shuffle(array) { + let c = array.length - 1; // eslint-disable-line functional/no-let + // eslint-disable-next-line functional/no-loop-statement + for (c; c > 0; c--) { + const b = Math.floor(Math.random() * (c + 1)); + const a = array[c]; + array[c] = array[b]; // eslint-disable-line functional/immutable-data, no-param-reassign + array[b] = a; // eslint-disable-line functional/immutable-data, no-param-reassign + } + return array; +} +function addMethods(base, methods) { + if (!methods) { + return base; + } + Object.keys(methods).forEach(key => { + // eslint-disable-next-line functional/immutable-data, no-param-reassign + base[key] = methods[key](base); + }); + return base; +} +function encode(format, ...args) { + // eslint-disable-next-line functional/no-let + let i = 0; + return format.replace(/%s/g, () => encodeURIComponent(args[i++])); +} + +const version = '4.24.0'; + +const destroy = (base) => { + return () => { + return base.transporter.requester.destroy(); + }; +}; + +const AuthMode = { + /** + * If auth credentials should be in query parameters. + */ + WithinQueryParameters: 0, + /** + * If auth credentials should be in headers. + */ + WithinHeaders: 1, +}; + +exports.AuthMode = AuthMode; +exports.addMethods = addMethods; +exports.createAuth = createAuth; +exports.createRetryablePromise = createRetryablePromise; +exports.createWaitablePromise = createWaitablePromise; +exports.destroy = destroy; +exports.encode = encode; +exports.shuffle = shuffle; +exports.version = version; diff --git a/scripts/node_modules/@algolia/client-common/dist/client-common.d.ts b/scripts/node_modules/@algolia/client-common/dist/client-common.d.ts new file mode 100644 index 000000000..52f32eac7 --- /dev/null +++ b/scripts/node_modules/@algolia/client-common/dist/client-common.d.ts @@ -0,0 +1,102 @@ +import { Headers as Headers_2 } from '@algolia/transporter'; +import { HostOptions } from '@algolia/transporter'; +import { QueryParameters } from '@algolia/transporter'; +import { RequestOptions } from '@algolia/transporter'; +import { Transporter } from '@algolia/transporter'; +import { TransporterOptions } from '@algolia/transporter'; + +declare type AddedMethods> = TBase & { + [TKey in keyof TMethods extends string ? keyof TMethods : never]: ReturnType; +}; + +export declare function addMethods>(base: TBase, methods?: TMethods): AddedMethods; + +export declare type Auth = { + /** + * Returns the headers related to auth. Should be + * merged to the transporter headers. + */ + readonly headers: () => Readonly>; + /** + * Returns the query parameters related to auth. Should be + * merged to the query parameters headers. + */ + readonly queryParameters: () => Readonly>; +}; + +export declare const AuthMode: Readonly>; + +export declare type AuthModeType = 0 | 1; + +export declare type ClientTransporterOptions = Pick & Exclude & Exclude> & { + /** + * The hosts used by the requester. + */ + readonly hosts?: readonly HostOptions[]; + /** + * The headers used by the requester. The transporter + * layer may add some extra headers during the request + * for the user agent, and others. + */ + readonly headers?: Headers_2; + /** + * The query parameters used by the requester. The transporter + * layer may add some extra headers during the request + * for the user agent, and others. + */ + readonly queryParameters?: QueryParameters; +}; + +export declare function createAuth(authMode: AuthModeType, appId: string, apiKey: string): Auth; + +export declare type CreateClient = (...args: any) => any; +}>(options: TOptions & { + readonly methods?: TMethods; +}) => TClient & { + [key in keyof TMethods extends string ? keyof TMethods : never]: ReturnType; +}; + +export declare function createRetryablePromise(callback: (retry: () => Promise) => Promise): Promise; + +export declare function createWaitablePromise(promise: Readonly>, wait?: Wait): Readonly>; + +export declare const destroy: (base: { + readonly transporter: Transporter; +}) => () => Readonly>; + +export declare function encode(format: string, ...args: readonly any[]): string; + +declare type Methods = { + readonly [key: string]: (base: TBase) => (...args: any[]) => any; +}; + +export declare function shuffle(array: TData[]): TData[]; + +export declare const version = "4.24.0"; + +export declare type Wait = ( +/** + * The original response. + */ +response: TResponse, +/** + * The custom request options. + */ +requestOptions?: RequestOptions) => Readonly>; + +export declare type WaitablePromise = Readonly> & { + /** + * Wait for a task to complete before executing the next line of code, to synchronize index updates. + * + * All write operations in Algolia are asynchronous by design. It means that when you add or + * update an object to your index, our servers will reply to your request with a taskID as + * soon as they understood the write operation. The actual insert and indexing will be + * done after replying to your code. + * + * You can wait for a task to complete by using this method. + */ + readonly wait: (requestOptions?: RequestOptions) => Readonly>; +}; + +export { } diff --git a/scripts/node_modules/@algolia/client-common/dist/client-common.esm.js b/scripts/node_modules/@algolia/client-common/dist/client-common.esm.js new file mode 100644 index 000000000..7fd5a172e --- /dev/null +++ b/scripts/node_modules/@algolia/client-common/dist/client-common.esm.js @@ -0,0 +1,89 @@ +function createAuth(authMode, appId, apiKey) { + const credentials = { + 'x-algolia-api-key': apiKey, + 'x-algolia-application-id': appId, + }; + return { + headers() { + return authMode === AuthMode.WithinHeaders ? credentials : {}; + }, + queryParameters() { + return authMode === AuthMode.WithinQueryParameters ? credentials : {}; + }, + }; +} + +function createRetryablePromise(callback) { + let retriesCount = 0; // eslint-disable-line functional/no-let + const retry = () => { + retriesCount++; + return new Promise((resolve) => { + setTimeout(() => { + resolve(callback(retry)); + }, Math.min(100 * retriesCount, 1000)); + }); + }; + return callback(retry); +} + +function createWaitablePromise(promise, wait = (_response, _requestOptions) => { + return Promise.resolve(); +}) { + // eslint-disable-next-line functional/immutable-data + return Object.assign(promise, { + wait(requestOptions) { + return createWaitablePromise(promise + .then(response => Promise.all([wait(response, requestOptions), response])) + .then(promiseResults => promiseResults[1])); + }, + }); +} + +// eslint-disable-next-line functional/prefer-readonly-type +function shuffle(array) { + let c = array.length - 1; // eslint-disable-line functional/no-let + // eslint-disable-next-line functional/no-loop-statement + for (c; c > 0; c--) { + const b = Math.floor(Math.random() * (c + 1)); + const a = array[c]; + array[c] = array[b]; // eslint-disable-line functional/immutable-data, no-param-reassign + array[b] = a; // eslint-disable-line functional/immutable-data, no-param-reassign + } + return array; +} +function addMethods(base, methods) { + if (!methods) { + return base; + } + Object.keys(methods).forEach(key => { + // eslint-disable-next-line functional/immutable-data, no-param-reassign + base[key] = methods[key](base); + }); + return base; +} +function encode(format, ...args) { + // eslint-disable-next-line functional/no-let + let i = 0; + return format.replace(/%s/g, () => encodeURIComponent(args[i++])); +} + +const version = '4.24.0'; + +const destroy = (base) => { + return () => { + return base.transporter.requester.destroy(); + }; +}; + +const AuthMode = { + /** + * If auth credentials should be in query parameters. + */ + WithinQueryParameters: 0, + /** + * If auth credentials should be in headers. + */ + WithinHeaders: 1, +}; + +export { AuthMode, addMethods, createAuth, createRetryablePromise, createWaitablePromise, destroy, encode, shuffle, version }; diff --git a/scripts/node_modules/@algolia/client-common/index.js b/scripts/node_modules/@algolia/client-common/index.js new file mode 100644 index 000000000..ddbe0e4dc --- /dev/null +++ b/scripts/node_modules/@algolia/client-common/index.js @@ -0,0 +1,2 @@ +// eslint-disable-next-line functional/immutable-data, import/no-commonjs +module.exports = require('./dist/client-common.cjs.js'); diff --git a/scripts/node_modules/@algolia/client-common/package.json b/scripts/node_modules/@algolia/client-common/package.json new file mode 100644 index 000000000..06e047431 --- /dev/null +++ b/scripts/node_modules/@algolia/client-common/package.json @@ -0,0 +1,22 @@ +{ + "name": "@algolia/client-common", + "version": "4.24.0", + "private": false, + "repository": { + "type": "git", + "url": "git://github.com/algolia/algoliasearch-client-javascript.git" + }, + "license": "MIT", + "sideEffects": false, + "main": "index.js", + "module": "dist/client-common.esm.js", + "types": "dist/client-common.d.ts", + "files": [ + "index.js", + "dist" + ], + "dependencies": { + "@algolia/requester-common": "4.24.0", + "@algolia/transporter": "4.24.0" + } +} diff --git a/scripts/node_modules/@algolia/client-personalization/dist/client-personalization.cjs.js b/scripts/node_modules/@algolia/client-personalization/dist/client-personalization.cjs.js new file mode 100644 index 000000000..a497e15d7 --- /dev/null +++ b/scripts/node_modules/@algolia/client-personalization/dist/client-personalization.cjs.js @@ -0,0 +1,49 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var clientCommon = require('@algolia/client-common'); +var transporter = require('@algolia/transporter'); +var requesterCommon = require('@algolia/requester-common'); + +const createPersonalizationClient = options => { + const region = options.region || 'us'; + const auth = clientCommon.createAuth(clientCommon.AuthMode.WithinHeaders, options.appId, options.apiKey); + const transporter$1 = transporter.createTransporter({ + hosts: [{ url: `personalization.${region}.algolia.com` }], + ...options, + headers: { + ...auth.headers(), + ...{ 'content-type': 'application/json' }, + ...options.headers, + }, + queryParameters: { + ...auth.queryParameters(), + ...options.queryParameters, + }, + }); + return clientCommon.addMethods({ appId: options.appId, transporter: transporter$1 }, options.methods); +}; + +const getPersonalizationStrategy = (base) => { + return (requestOptions) => { + return base.transporter.read({ + method: requesterCommon.MethodEnum.Get, + path: '1/strategies/personalization', + }, requestOptions); + }; +}; + +const setPersonalizationStrategy = (base) => { + return (personalizationStrategy, requestOptions) => { + return base.transporter.write({ + method: requesterCommon.MethodEnum.Post, + path: '1/strategies/personalization', + data: personalizationStrategy, + }, requestOptions); + }; +}; + +exports.createPersonalizationClient = createPersonalizationClient; +exports.getPersonalizationStrategy = getPersonalizationStrategy; +exports.setPersonalizationStrategy = setPersonalizationStrategy; diff --git a/scripts/node_modules/@algolia/client-personalization/dist/client-personalization.d.ts b/scripts/node_modules/@algolia/client-personalization/dist/client-personalization.d.ts new file mode 100644 index 000000000..e9d3cfdc3 --- /dev/null +++ b/scripts/node_modules/@algolia/client-personalization/dist/client-personalization.d.ts @@ -0,0 +1,93 @@ +import { ClientTransporterOptions } from '@algolia/client-common'; +import { CreateClient } from '@algolia/client-common'; +import { RequestOptions } from '@algolia/transporter'; +import { Transporter } from '@algolia/transporter'; + +export declare const createPersonalizationClient: CreateClient; + +export declare const getPersonalizationStrategy: (base: PersonalizationClient) => (requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare type GetPersonalizationStrategyResponse = { + /** + * Events scoring + */ + eventsScoring: Array<{ + eventName: string; + eventType: string; + score: number; + }>; + /** + * Facets scoring + */ + facetsScoring: Array<{ + facetName: string; + score: number; + }>; + /** + * Personalization impact + */ + personalizationImpact: number; +}; + +export declare type PersonalizationClient = { + /** + * The application id. + */ + readonly appId: string; + /** + * The underlying transporter. + */ + readonly transporter: Transporter; +}; + +export declare type PersonalizationClientOptions = { + /** + * The application id. + */ + readonly appId: string; + /** + * The api key. + */ + readonly apiKey: string; + /** + * The prefered region. + */ + readonly region?: string; +}; + +export declare type PersonalizationStrategy = { + /** + * Events scoring + */ + readonly eventsScoring: ReadonlyArray<{ + readonly eventName: string; + readonly eventType: string; + readonly score: number; + }>; + /** + * Facets scoring + */ + readonly facetsScoring: ReadonlyArray<{ + readonly facetName: string; + readonly score: number; + }>; + /** + * Personalization impact + */ + readonly personalizationImpact: number; +}; + +export declare const setPersonalizationStrategy: (base: PersonalizationClient) => (personalizationStrategy: PersonalizationStrategy, requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare type SetPersonalizationStrategyResponse = { + /** + * The status code. + */ + status?: number; + /** + * The message. + */ + message: string; +}; + +export { } diff --git a/scripts/node_modules/@algolia/client-personalization/dist/client-personalization.esm.js b/scripts/node_modules/@algolia/client-personalization/dist/client-personalization.esm.js new file mode 100644 index 000000000..71d3167a9 --- /dev/null +++ b/scripts/node_modules/@algolia/client-personalization/dist/client-personalization.esm.js @@ -0,0 +1,43 @@ +import { createAuth, AuthMode, addMethods } from '@algolia/client-common'; +import { createTransporter } from '@algolia/transporter'; +import { MethodEnum } from '@algolia/requester-common'; + +const createPersonalizationClient = options => { + const region = options.region || 'us'; + const auth = createAuth(AuthMode.WithinHeaders, options.appId, options.apiKey); + const transporter = createTransporter({ + hosts: [{ url: `personalization.${region}.algolia.com` }], + ...options, + headers: { + ...auth.headers(), + ...{ 'content-type': 'application/json' }, + ...options.headers, + }, + queryParameters: { + ...auth.queryParameters(), + ...options.queryParameters, + }, + }); + return addMethods({ appId: options.appId, transporter }, options.methods); +}; + +const getPersonalizationStrategy = (base) => { + return (requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Get, + path: '1/strategies/personalization', + }, requestOptions); + }; +}; + +const setPersonalizationStrategy = (base) => { + return (personalizationStrategy, requestOptions) => { + return base.transporter.write({ + method: MethodEnum.Post, + path: '1/strategies/personalization', + data: personalizationStrategy, + }, requestOptions); + }; +}; + +export { createPersonalizationClient, getPersonalizationStrategy, setPersonalizationStrategy }; diff --git a/scripts/node_modules/@algolia/client-personalization/index.js b/scripts/node_modules/@algolia/client-personalization/index.js new file mode 100644 index 000000000..df07d60ae --- /dev/null +++ b/scripts/node_modules/@algolia/client-personalization/index.js @@ -0,0 +1,2 @@ +// eslint-disable-next-line functional/immutable-data, import/no-commonjs +module.exports = require('./dist/client-personalization.cjs.js'); diff --git a/scripts/node_modules/@algolia/client-personalization/package.json b/scripts/node_modules/@algolia/client-personalization/package.json new file mode 100644 index 000000000..f97a2ae22 --- /dev/null +++ b/scripts/node_modules/@algolia/client-personalization/package.json @@ -0,0 +1,23 @@ +{ + "name": "@algolia/client-personalization", + "version": "4.24.0", + "private": false, + "repository": { + "type": "git", + "url": "git://github.com/algolia/algoliasearch-client-javascript.git" + }, + "license": "MIT", + "sideEffects": false, + "main": "index.js", + "module": "dist/client-personalization.esm.js", + "types": "dist/client-personalization.d.ts", + "files": [ + "index.js", + "dist" + ], + "dependencies": { + "@algolia/client-common": "4.24.0", + "@algolia/requester-common": "4.24.0", + "@algolia/transporter": "4.24.0" + } +} diff --git a/scripts/node_modules/@algolia/client-search/dist/client-search.cjs.js b/scripts/node_modules/@algolia/client-search/dist/client-search.cjs.js new file mode 100644 index 000000000..c7fe50629 --- /dev/null +++ b/scripts/node_modules/@algolia/client-search/dist/client-search.cjs.js @@ -0,0 +1,1380 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var clientCommon = require('@algolia/client-common'); +var transporter = require('@algolia/transporter'); +var requesterCommon = require('@algolia/requester-common'); +var crypto = require('crypto'); + +function createBrowsablePromise(options) { + const browse = (data) => { + return options.request(data).then(response => { + /** + * First we send to the developer the + * batch retrieved from the API. + */ + if (options.batch !== undefined) { + options.batch(response.hits); + } + /** + * Then, we ask to the browse concrete implementation + * if we should stop browsing. As example, the `browseObjects` + * method will stop if the cursor is not present on the response. + */ + if (options.shouldStop(response)) { + return undefined; + } + /** + * Finally, if the response contains a cursor, we browse to the next + * batch using that same cursor. Otherwise, we just use the traditional + * browsing using the page element. + */ + if (response.cursor) { + return browse({ + cursor: response.cursor, + }); + } + return browse({ + page: (data.page || 0) + 1, + }); + }); + }; + return browse({}); +} + +const createSearchClient = options => { + const appId = options.appId; + const auth = clientCommon.createAuth(options.authMode !== undefined ? options.authMode : clientCommon.AuthMode.WithinHeaders, appId, options.apiKey); + const transporter$1 = transporter.createTransporter({ + hosts: [ + { url: `${appId}-dsn.algolia.net`, accept: transporter.CallEnum.Read }, + { url: `${appId}.algolia.net`, accept: transporter.CallEnum.Write }, + ].concat(clientCommon.shuffle([ + { url: `${appId}-1.algolianet.com` }, + { url: `${appId}-2.algolianet.com` }, + { url: `${appId}-3.algolianet.com` }, + ])), + ...options, + headers: { + ...auth.headers(), + ...{ 'content-type': 'application/x-www-form-urlencoded' }, + ...options.headers, + }, + queryParameters: { + ...auth.queryParameters(), + ...options.queryParameters, + }, + }); + const base = { + transporter: transporter$1, + appId, + addAlgoliaAgent(segment, version) { + transporter$1.userAgent.add({ segment, version }); + }, + clearCache() { + return Promise.all([ + transporter$1.requestsCache.clear(), + transporter$1.responsesCache.clear(), + ]).then(() => undefined); + }, + }; + return clientCommon.addMethods(base, options.methods); +}; + +function createMissingObjectIDError() { + return { + name: 'MissingObjectIDError', + message: 'All objects must have an unique objectID ' + + '(like a primary key) to be valid. ' + + 'Algolia is also able to generate objectIDs ' + + "automatically but *it's not recommended*. " + + "To do it, use the `{'autoGenerateObjectIDIfNotExist': true}` option.", + }; +} + +function createObjectNotFoundError() { + return { + name: 'ObjectNotFoundError', + message: 'Object not found.', + }; +} + +function createValidUntilNotFoundError() { + return { + name: 'ValidUntilNotFoundError', + message: 'ValidUntil not found in given secured api key.', + }; +} + +const addApiKey = (base) => { + return (acl, requestOptions) => { + const { queryParameters, ...options } = requestOptions || {}; + const data = { + acl, + ...(queryParameters !== undefined ? { queryParameters } : {}), + }; + const wait = (response, waitRequestOptions) => { + return clientCommon.createRetryablePromise(retry => { + return getApiKey(base)(response.key, waitRequestOptions).catch((apiError) => { + if (apiError.status !== 404) { + throw apiError; + } + return retry(); + }); + }); + }; + return clientCommon.createWaitablePromise(base.transporter.write({ + method: requesterCommon.MethodEnum.Post, + path: '1/keys', + data, + }, options), wait); + }; +}; + +const assignUserID = (base) => { + return (userID, clusterName, requestOptions) => { + const mappedRequestOptions = transporter.createMappedRequestOptions(requestOptions); + // eslint-disable-next-line functional/immutable-data + mappedRequestOptions.queryParameters['X-Algolia-User-ID'] = userID; + return base.transporter.write({ + method: requesterCommon.MethodEnum.Post, + path: '1/clusters/mapping', + data: { cluster: clusterName }, + }, mappedRequestOptions); + }; +}; + +const assignUserIDs = (base) => { + return (userIDs, clusterName, requestOptions) => { + return base.transporter.write({ + method: requesterCommon.MethodEnum.Post, + path: '1/clusters/mapping/batch', + data: { + users: userIDs, + cluster: clusterName, + }, + }, requestOptions); + }; +}; + +const clearDictionaryEntries = (base) => { + return (dictionary, requestOptions) => { + return clientCommon.createWaitablePromise(base.transporter.write({ + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode('/1/dictionaries/%s/batch', dictionary), + data: { + clearExistingDictionaryEntries: true, + requests: { action: 'addEntry', body: [] }, + }, + }, requestOptions), (response, waitRequestOptions) => waitAppTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const copyIndex = (base) => { + return (from, to, requestOptions) => { + const wait = (response, waitRequestOptions) => { + return initIndex(base)(from, { + methods: { waitTask }, + }).waitTask(response.taskID, waitRequestOptions); + }; + return clientCommon.createWaitablePromise(base.transporter.write({ + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode('1/indexes/%s/operation', from), + data: { + operation: 'copy', + destination: to, + }, + }, requestOptions), wait); + }; +}; + +const copyRules = (base) => { + return (from, to, requestOptions) => { + return copyIndex(base)(from, to, { + ...requestOptions, + scope: [ScopeEnum.Rules], + }); + }; +}; + +const copySettings = (base) => { + return (from, to, requestOptions) => { + return copyIndex(base)(from, to, { + ...requestOptions, + scope: [ScopeEnum.Settings], + }); + }; +}; + +const copySynonyms = (base) => { + return (from, to, requestOptions) => { + return copyIndex(base)(from, to, { + ...requestOptions, + scope: [ScopeEnum.Synonyms], + }); + }; +}; + +const customRequest = (base) => { + return (request, requestOptions) => { + if (request.method === requesterCommon.MethodEnum.Get) { + return base.transporter.read(request, requestOptions); + } + return base.transporter.write(request, requestOptions); + }; +}; + +const deleteApiKey = (base) => { + return (apiKey, requestOptions) => { + const wait = (_, waitRequestOptions) => { + return clientCommon.createRetryablePromise(retry => { + return getApiKey(base)(apiKey, waitRequestOptions) + .then(retry) + .catch((apiError) => { + if (apiError.status !== 404) { + throw apiError; + } + }); + }); + }; + return clientCommon.createWaitablePromise(base.transporter.write({ + method: requesterCommon.MethodEnum.Delete, + path: clientCommon.encode('1/keys/%s', apiKey), + }, requestOptions), wait); + }; +}; + +const deleteDictionaryEntries = (base) => { + return (dictionary, objectIDs, requestOptions) => { + const requests = objectIDs.map(objectID => ({ + action: 'deleteEntry', + body: { objectID }, + })); + return clientCommon.createWaitablePromise(base.transporter.write({ + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode('/1/dictionaries/%s/batch', dictionary), + data: { clearExistingDictionaryEntries: false, requests }, + }, requestOptions), (response, waitRequestOptions) => waitAppTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const generateSecuredApiKey = () => { + return (parentApiKey, restrictions) => { + const queryParameters = transporter.serializeQueryParameters(restrictions); + const securedKey = crypto.createHmac('sha256', parentApiKey) + .update(queryParameters) + .digest('hex'); + return Buffer.from(securedKey + queryParameters).toString('base64'); + }; +}; + +const getApiKey = (base) => { + return (apiKey, requestOptions) => { + return base.transporter.read({ + method: requesterCommon.MethodEnum.Get, + path: clientCommon.encode('1/keys/%s', apiKey), + }, requestOptions); + }; +}; + +const getAppTask = (base) => { + return (taskID, requestOptions) => { + return base.transporter.read({ + method: requesterCommon.MethodEnum.Get, + path: clientCommon.encode('1/task/%s', taskID.toString()), + }, requestOptions); + }; +}; + +const getDictionarySettings = (base) => { + return (requestOptions) => { + return base.transporter.read({ + method: requesterCommon.MethodEnum.Get, + path: '/1/dictionaries/*/settings', + }, requestOptions); + }; +}; + +const getLogs = (base) => { + return (requestOptions) => { + return base.transporter.read({ + method: requesterCommon.MethodEnum.Get, + path: '1/logs', + }, requestOptions); + }; +}; + +const getSecuredApiKeyRemainingValidity = () => { + return (securedApiKey) => { + const decodedString = Buffer.from(securedApiKey, 'base64').toString('ascii'); + const regex = /validUntil=(\d+)/; + const match = decodedString.match(regex); + if (match === null) { + throw createValidUntilNotFoundError(); + } + return parseInt(match[1], 10) - Math.round(new Date().getTime() / 1000); + }; +}; + +const getTopUserIDs = (base) => { + return (requestOptions) => { + return base.transporter.read({ + method: requesterCommon.MethodEnum.Get, + path: '1/clusters/mapping/top', + }, requestOptions); + }; +}; + +const getUserID = (base) => { + return (userID, requestOptions) => { + return base.transporter.read({ + method: requesterCommon.MethodEnum.Get, + path: clientCommon.encode('1/clusters/mapping/%s', userID), + }, requestOptions); + }; +}; + +const hasPendingMappings = (base) => { + return (requestOptions) => { + const { retrieveMappings, ...options } = requestOptions || {}; + if (retrieveMappings === true) { + // eslint-disable-next-line functional/immutable-data + options.getClusters = true; + } + return base.transporter.read({ + method: requesterCommon.MethodEnum.Get, + path: '1/clusters/mapping/pending', + }, options); + }; +}; + +const initIndex = (base) => { + return (indexName, options = {}) => { + const searchIndex = { + transporter: base.transporter, + appId: base.appId, + indexName, + }; + return clientCommon.addMethods(searchIndex, options.methods); + }; +}; + +const listApiKeys = (base) => { + return (requestOptions) => { + return base.transporter.read({ + method: requesterCommon.MethodEnum.Get, + path: '1/keys', + }, requestOptions); + }; +}; + +const listClusters = (base) => { + return (requestOptions) => { + return base.transporter.read({ + method: requesterCommon.MethodEnum.Get, + path: '1/clusters', + }, requestOptions); + }; +}; + +const listIndices = (base) => { + return (requestOptions) => { + return base.transporter.read({ + method: requesterCommon.MethodEnum.Get, + path: '1/indexes', + }, requestOptions); + }; +}; + +const listUserIDs = (base) => { + return (requestOptions) => { + return base.transporter.read({ + method: requesterCommon.MethodEnum.Get, + path: '1/clusters/mapping', + }, requestOptions); + }; +}; + +const moveIndex = (base) => { + return (from, to, requestOptions) => { + const wait = (response, waitRequestOptions) => { + return initIndex(base)(from, { + methods: { waitTask }, + }).waitTask(response.taskID, waitRequestOptions); + }; + return clientCommon.createWaitablePromise(base.transporter.write({ + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode('1/indexes/%s/operation', from), + data: { + operation: 'move', + destination: to, + }, + }, requestOptions), wait); + }; +}; + +const multipleBatch = (base) => { + return (requests, requestOptions) => { + const wait = (response, waitRequestOptions) => { + return Promise.all(Object.keys(response.taskID).map(indexName => { + return initIndex(base)(indexName, { + methods: { waitTask }, + }).waitTask(response.taskID[indexName], waitRequestOptions); + })); + }; + return clientCommon.createWaitablePromise(base.transporter.write({ + method: requesterCommon.MethodEnum.Post, + path: '1/indexes/*/batch', + data: { + requests, + }, + }, requestOptions), wait); + }; +}; + +const multipleGetObjects = (base) => { + return (requests, requestOptions) => { + return base.transporter.read({ + method: requesterCommon.MethodEnum.Post, + path: '1/indexes/*/objects', + data: { + requests, + }, + }, requestOptions); + }; +}; + +const multipleQueries = (base) => { + return (queries, requestOptions) => { + const requests = queries.map(query => { + return { + ...query, + params: transporter.serializeQueryParameters(query.params || {}), + }; + }); + return base.transporter.read({ + method: requesterCommon.MethodEnum.Post, + path: '1/indexes/*/queries', + data: { + requests, + }, + cacheable: true, + }, requestOptions); + }; +}; + +const multipleSearchForFacetValues = (base) => { + return (queries, requestOptions) => { + return Promise.all(queries.map(query => { + const { facetName, facetQuery, ...params } = query.params; + return initIndex(base)(query.indexName, { + methods: { searchForFacetValues }, + }).searchForFacetValues(facetName, facetQuery, { + ...requestOptions, + ...params, + }); + })); + }; +}; + +const removeUserID = (base) => { + return (userID, requestOptions) => { + const mappedRequestOptions = transporter.createMappedRequestOptions(requestOptions); + // eslint-disable-next-line functional/immutable-data + mappedRequestOptions.queryParameters['X-Algolia-User-ID'] = userID; + return base.transporter.write({ + method: requesterCommon.MethodEnum.Delete, + path: '1/clusters/mapping', + }, mappedRequestOptions); + }; +}; + +const replaceDictionaryEntries = (base) => { + return (dictionary, entries, requestOptions) => { + const requests = entries.map(entry => ({ + action: 'addEntry', + body: entry, + })); + return clientCommon.createWaitablePromise(base.transporter.write({ + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode('/1/dictionaries/%s/batch', dictionary), + data: { clearExistingDictionaryEntries: true, requests }, + }, requestOptions), (response, waitRequestOptions) => waitAppTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const restoreApiKey = (base) => { + return (apiKey, requestOptions) => { + const wait = (_, waitRequestOptions) => { + return clientCommon.createRetryablePromise(retry => { + return getApiKey(base)(apiKey, waitRequestOptions).catch((apiError) => { + if (apiError.status !== 404) { + throw apiError; + } + return retry(); + }); + }); + }; + return clientCommon.createWaitablePromise(base.transporter.write({ + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode('1/keys/%s/restore', apiKey), + }, requestOptions), wait); + }; +}; + +const saveDictionaryEntries = (base) => { + return (dictionary, entries, requestOptions) => { + const requests = entries.map(entry => ({ + action: 'addEntry', + body: entry, + })); + return clientCommon.createWaitablePromise(base.transporter.write({ + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode('/1/dictionaries/%s/batch', dictionary), + data: { clearExistingDictionaryEntries: false, requests }, + }, requestOptions), (response, waitRequestOptions) => waitAppTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const searchDictionaryEntries = (base) => { + return (dictionary, query, requestOptions) => { + return base.transporter.read({ + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode('/1/dictionaries/%s/search', dictionary), + data: { + query, + }, + cacheable: true, + }, requestOptions); + }; +}; + +const searchUserIDs = (base) => { + return (query, requestOptions) => { + return base.transporter.read({ + method: requesterCommon.MethodEnum.Post, + path: '1/clusters/mapping/search', + data: { + query, + }, + }, requestOptions); + }; +}; + +const setDictionarySettings = (base) => { + return (settings, requestOptions) => { + return clientCommon.createWaitablePromise(base.transporter.write({ + method: requesterCommon.MethodEnum.Put, + path: '/1/dictionaries/*/settings', + data: settings, + }, requestOptions), (response, waitRequestOptions) => waitAppTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const updateApiKey = (base) => { + return (apiKey, requestOptions) => { + const updatedFields = Object.assign({}, requestOptions); + const { queryParameters, ...options } = requestOptions || {}; + const data = queryParameters ? { queryParameters } : {}; + const apiKeyFields = [ + 'acl', + 'indexes', + 'referers', + 'restrictSources', + 'queryParameters', + 'description', + 'maxQueriesPerIPPerHour', + 'maxHitsPerQuery', + ]; + // Check that all the fields retrieved through getApiKey are the same as the ones we wanted to update + const hasChanged = (getApiKeyResponse) => { + return Object.keys(updatedFields) + .filter((updatedField) => apiKeyFields.indexOf(updatedField) !== -1) + .every(updatedField => { + // If the field is an array, we need to check that they are the same length and that all the values are the same + if (Array.isArray(getApiKeyResponse[updatedField]) && + Array.isArray(updatedFields[updatedField])) { + const getApiKeyResponseArray = getApiKeyResponse[updatedField]; + return (getApiKeyResponseArray.length === updatedFields[updatedField].length && + getApiKeyResponseArray.every((value, index) => value === updatedFields[updatedField][index])); + } + else { + return getApiKeyResponse[updatedField] === updatedFields[updatedField]; + } + }); + }; + const wait = (_, waitRequestOptions) => clientCommon.createRetryablePromise(retry => { + return getApiKey(base)(apiKey, waitRequestOptions).then(getApiKeyResponse => { + return hasChanged(getApiKeyResponse) ? Promise.resolve() : retry(); + }); + }); + return clientCommon.createWaitablePromise(base.transporter.write({ + method: requesterCommon.MethodEnum.Put, + path: clientCommon.encode('1/keys/%s', apiKey), + data, + }, options), wait); + }; +}; + +const waitAppTask = (base) => { + return (taskID, requestOptions) => { + return clientCommon.createRetryablePromise(retry => { + return getAppTask(base)(taskID, requestOptions).then(response => { + return response.status !== 'published' ? retry() : undefined; + }); + }); + }; +}; + +const batch = (base) => { + return (requests, requestOptions) => { + const wait = (response, waitRequestOptions) => { + return waitTask(base)(response.taskID, waitRequestOptions); + }; + return clientCommon.createWaitablePromise(base.transporter.write({ + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode('1/indexes/%s/batch', base.indexName), + data: { + requests, + }, + }, requestOptions), wait); + }; +}; + +const browseObjects = (base) => { + return (requestOptions) => { + return createBrowsablePromise({ + shouldStop: response => response.cursor === undefined, + ...requestOptions, + request: (data) => base.transporter.read({ + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode('1/indexes/%s/browse', base.indexName), + data, + }, requestOptions), + }); + }; +}; + +const browseRules = (base) => { + return (requestOptions) => { + const options = { + hitsPerPage: 1000, + ...requestOptions, + }; + return createBrowsablePromise({ + shouldStop: response => response.hits.length < options.hitsPerPage, + ...options, + request(data) { + return searchRules(base)('', { ...options, ...data }).then((response) => { + return { + ...response, + hits: response.hits.map(rule => { + // eslint-disable-next-line functional/immutable-data,no-param-reassign + delete rule._highlightResult; + return rule; + }), + }; + }); + }, + }); + }; +}; + +const browseSynonyms = (base) => { + return (requestOptions) => { + const options = { + hitsPerPage: 1000, + ...requestOptions, + }; + return createBrowsablePromise({ + shouldStop: response => response.hits.length < options.hitsPerPage, + ...options, + request(data) { + return searchSynonyms(base)('', { ...options, ...data }).then((response) => { + return { + ...response, + hits: response.hits.map(synonym => { + // eslint-disable-next-line functional/immutable-data,no-param-reassign + delete synonym._highlightResult; + return synonym; + }), + }; + }); + }, + }); + }; +}; + +const chunkedBatch = (base) => { + return (bodies, action, requestOptions) => { + const { batchSize, ...options } = requestOptions || {}; + const response = { + taskIDs: [], + objectIDs: [], + }; + const forEachBatch = (lastIndex = 0) => { + // eslint-disable-next-line functional/prefer-readonly-type + const bodiesChunk = []; + // eslint-disable-next-line functional/no-let + let index; + /* eslint-disable-next-line functional/no-loop-statement */ + for (index = lastIndex; index < bodies.length; index++) { + // eslint-disable-next-line functional/immutable-data + bodiesChunk.push(bodies[index]); + if (bodiesChunk.length === (batchSize || 1000)) { + break; + } + } + if (bodiesChunk.length === 0) { + return Promise.resolve(response); + } + return batch(base)(bodiesChunk.map(body => { + return { + action, + body, + }; + }), options).then(res => { + response.objectIDs = response.objectIDs.concat(res.objectIDs); // eslint-disable-line functional/immutable-data + response.taskIDs.push(res.taskID); // eslint-disable-line functional/immutable-data + index++; + return forEachBatch(index); + }); + }; + return clientCommon.createWaitablePromise(forEachBatch(), (chunkedBatchResponse, waitRequestOptions) => { + return Promise.all(chunkedBatchResponse.taskIDs.map(taskID => { + return waitTask(base)(taskID, waitRequestOptions); + })); + }); + }; +}; + +const clearObjects = (base) => { + return (requestOptions) => { + return clientCommon.createWaitablePromise(base.transporter.write({ + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode('1/indexes/%s/clear', base.indexName), + }, requestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const clearRules = (base) => { + return (requestOptions) => { + const { forwardToReplicas, ...options } = requestOptions || {}; + const mappedRequestOptions = transporter.createMappedRequestOptions(options); + if (forwardToReplicas) { + mappedRequestOptions.queryParameters.forwardToReplicas = 1; // eslint-disable-line functional/immutable-data + } + return clientCommon.createWaitablePromise(base.transporter.write({ + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode('1/indexes/%s/rules/clear', base.indexName), + }, mappedRequestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const clearSynonyms = (base) => { + return (requestOptions) => { + const { forwardToReplicas, ...options } = requestOptions || {}; + const mappedRequestOptions = transporter.createMappedRequestOptions(options); + if (forwardToReplicas) { + mappedRequestOptions.queryParameters.forwardToReplicas = 1; // eslint-disable-line functional/immutable-data + } + return clientCommon.createWaitablePromise(base.transporter.write({ + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode('1/indexes/%s/synonyms/clear', base.indexName), + }, mappedRequestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const deleteBy = (base) => { + return (filters, requestOptions) => { + return clientCommon.createWaitablePromise(base.transporter.write({ + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode('1/indexes/%s/deleteByQuery', base.indexName), + data: filters, + }, requestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const deleteIndex = (base) => { + return (requestOptions) => { + return clientCommon.createWaitablePromise(base.transporter.write({ + method: requesterCommon.MethodEnum.Delete, + path: clientCommon.encode('1/indexes/%s', base.indexName), + }, requestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const deleteObject = (base) => { + return (objectID, requestOptions) => { + return clientCommon.createWaitablePromise(deleteObjects(base)([objectID], requestOptions).then(response => { + return { taskID: response.taskIDs[0] }; + }), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const deleteObjects = (base) => { + return (objectIDs, requestOptions) => { + const objects = objectIDs.map(objectID => { + return { objectID }; + }); + return chunkedBatch(base)(objects, BatchActionEnum.DeleteObject, requestOptions); + }; +}; + +const deleteRule = (base) => { + return (objectID, requestOptions) => { + const { forwardToReplicas, ...options } = requestOptions || {}; + const mappedRequestOptions = transporter.createMappedRequestOptions(options); + if (forwardToReplicas) { + mappedRequestOptions.queryParameters.forwardToReplicas = 1; // eslint-disable-line functional/immutable-data + } + return clientCommon.createWaitablePromise(base.transporter.write({ + method: requesterCommon.MethodEnum.Delete, + path: clientCommon.encode('1/indexes/%s/rules/%s', base.indexName, objectID), + }, mappedRequestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const deleteSynonym = (base) => { + return (objectID, requestOptions) => { + const { forwardToReplicas, ...options } = requestOptions || {}; + const mappedRequestOptions = transporter.createMappedRequestOptions(options); + if (forwardToReplicas) { + mappedRequestOptions.queryParameters.forwardToReplicas = 1; // eslint-disable-line functional/immutable-data + } + return clientCommon.createWaitablePromise(base.transporter.write({ + method: requesterCommon.MethodEnum.Delete, + path: clientCommon.encode('1/indexes/%s/synonyms/%s', base.indexName, objectID), + }, mappedRequestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const exists = (base) => { + return (requestOptions) => { + return getSettings(base)(requestOptions) + .then(() => true) + .catch(error => { + if (error.status !== 404) { + throw error; + } + return false; + }); + }; +}; + +const findAnswers = (base) => { + return (query, queryLanguages, requestOptions) => { + return base.transporter.read({ + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode('1/answers/%s/prediction', base.indexName), + data: { + query, + queryLanguages, + }, + cacheable: true, + }, requestOptions); + }; +}; + +const findObject = (base) => { + return (callback, requestOptions) => { + const { query, paginate, ...options } = requestOptions || {}; + // eslint-disable-next-line functional/no-let + let page = 0; + const forEachPage = () => { + return search(base)(query || '', { ...options, page }).then(result => { + // eslint-disable-next-line functional/no-loop-statement + for (const [position, hit] of Object.entries(result.hits)) { + // eslint-disable-next-line promise/no-callback-in-promise + if (callback(hit)) { + return { + object: hit, + position: parseInt(position, 10), + page, + }; + } + } + page++; + // paginate if option was set and has next page + if (paginate === false || page >= result.nbPages) { + throw createObjectNotFoundError(); + } + return forEachPage(); + }); + }; + return forEachPage(); + }; +}; + +const getObject = (base) => { + return (objectID, requestOptions) => { + return base.transporter.read({ + method: requesterCommon.MethodEnum.Get, + path: clientCommon.encode('1/indexes/%s/%s', base.indexName, objectID), + }, requestOptions); + }; +}; + +const getObjectPosition = () => { + return (searchResponse, objectID) => { + // eslint-disable-next-line functional/no-loop-statement + for (const [position, hit] of Object.entries(searchResponse.hits)) { + if (hit.objectID === objectID) { + return parseInt(position, 10); + } + } + return -1; + }; +}; + +const getObjects = (base) => { + return (objectIDs, requestOptions) => { + const { attributesToRetrieve, ...options } = requestOptions || {}; + const requests = objectIDs.map(objectID => { + return { + indexName: base.indexName, + objectID, + ...(attributesToRetrieve ? { attributesToRetrieve } : {}), + }; + }); + return base.transporter.read({ + method: requesterCommon.MethodEnum.Post, + path: '1/indexes/*/objects', + data: { + requests, + }, + }, options); + }; +}; + +const getRule = (base) => { + return (objectID, requestOptions) => { + return base.transporter.read({ + method: requesterCommon.MethodEnum.Get, + path: clientCommon.encode('1/indexes/%s/rules/%s', base.indexName, objectID), + }, requestOptions); + }; +}; + +const getSettings = (base) => { + return (requestOptions) => { + return base.transporter.read({ + method: requesterCommon.MethodEnum.Get, + path: clientCommon.encode('1/indexes/%s/settings', base.indexName), + data: { + getVersion: 2, + }, + }, requestOptions); + }; +}; + +const getSynonym = (base) => { + return (objectID, requestOptions) => { + return base.transporter.read({ + method: requesterCommon.MethodEnum.Get, + path: clientCommon.encode(`1/indexes/%s/synonyms/%s`, base.indexName, objectID), + }, requestOptions); + }; +}; + +const getTask = (base) => { + return (taskID, requestOptions) => { + return base.transporter.read({ + method: requesterCommon.MethodEnum.Get, + path: clientCommon.encode('1/indexes/%s/task/%s', base.indexName, taskID.toString()), + }, requestOptions); + }; +}; + +const partialUpdateObject = (base) => { + return (object, requestOptions) => { + return clientCommon.createWaitablePromise(partialUpdateObjects(base)([object], requestOptions).then(response => { + return { + objectID: response.objectIDs[0], + taskID: response.taskIDs[0], + }; + }), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const partialUpdateObjects = (base) => { + return (objects, requestOptions) => { + const { createIfNotExists, ...options } = requestOptions || {}; + const action = createIfNotExists + ? BatchActionEnum.PartialUpdateObject + : BatchActionEnum.PartialUpdateObjectNoCreate; + return chunkedBatch(base)(objects, action, options); + }; +}; + +const replaceAllObjects = (base) => { + return (objects, requestOptions) => { + const { safe, autoGenerateObjectIDIfNotExist, batchSize, ...options } = requestOptions || {}; + const operation = (from, to, type, operationRequestOptions) => { + return clientCommon.createWaitablePromise(base.transporter.write({ + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode('1/indexes/%s/operation', from), + data: { + operation: type, + destination: to, + }, + }, operationRequestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; + const randomSuffix = Math.random() + .toString(36) + .substring(7); + const temporaryIndexName = `${base.indexName}_tmp_${randomSuffix}`; + const saveObjectsInTemporary = saveObjects({ + appId: base.appId, + transporter: base.transporter, + indexName: temporaryIndexName, + }); + // @ts-ignore + // eslint-disable-next-line prefer-const, functional/no-let, functional/prefer-readonly-type + let responses = []; + const copyWaitablePromise = operation(base.indexName, temporaryIndexName, 'copy', { + ...options, + scope: ['settings', 'synonyms', 'rules'], + }); + // eslint-disable-next-line functional/immutable-data + responses.push(copyWaitablePromise); + const result = (safe + ? copyWaitablePromise.wait(options) + : copyWaitablePromise) + .then(() => { + const saveObjectsWaitablePromise = saveObjectsInTemporary(objects, { + ...options, + autoGenerateObjectIDIfNotExist, + batchSize, + }); + // eslint-disable-next-line functional/immutable-data + responses.push(saveObjectsWaitablePromise); + return safe ? saveObjectsWaitablePromise.wait(options) : saveObjectsWaitablePromise; + }) + .then(() => { + const moveWaitablePromise = operation(temporaryIndexName, base.indexName, 'move', options); + // eslint-disable-next-line functional/immutable-data + responses.push(moveWaitablePromise); + return safe ? moveWaitablePromise.wait(options) : moveWaitablePromise; + }) + .then(() => Promise.all(responses)) + .then(([copyResponse, saveObjectsResponse, moveResponse]) => { + return { + objectIDs: saveObjectsResponse.objectIDs, + taskIDs: [copyResponse.taskID, ...saveObjectsResponse.taskIDs, moveResponse.taskID], + }; + }); + return clientCommon.createWaitablePromise(result, (_, waitRequestOptions) => { + return Promise.all(responses.map(response => response.wait(waitRequestOptions))); + }); + }; +}; + +const replaceAllRules = (base) => { + return (rules, requestOptions) => { + return saveRules(base)(rules, { + ...requestOptions, + clearExistingRules: true, + }); + }; +}; + +const replaceAllSynonyms = (base) => { + return (synonyms, requestOptions) => { + return saveSynonyms(base)(synonyms, { + ...requestOptions, + clearExistingSynonyms: true, + }); + }; +}; + +const saveObject = (base) => { + return (object, requestOptions) => { + return clientCommon.createWaitablePromise(saveObjects(base)([object], requestOptions).then(response => { + return { + objectID: response.objectIDs[0], + taskID: response.taskIDs[0], + }; + }), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const saveObjects = (base) => { + return (objects, requestOptions) => { + const { autoGenerateObjectIDIfNotExist, ...options } = requestOptions || {}; + const action = autoGenerateObjectIDIfNotExist + ? BatchActionEnum.AddObject + : BatchActionEnum.UpdateObject; + if (action === BatchActionEnum.UpdateObject) { + // eslint-disable-next-line functional/no-loop-statement + for (const object of objects) { + if (object.objectID === undefined) { + return clientCommon.createWaitablePromise(Promise.reject(createMissingObjectIDError())); + } + } + } + return chunkedBatch(base)(objects, action, options); + }; +}; + +const saveRule = (base) => { + return (rule, requestOptions) => { + return saveRules(base)([rule], requestOptions); + }; +}; + +const saveRules = (base) => { + return (rules, requestOptions) => { + const { forwardToReplicas, clearExistingRules, ...options } = requestOptions || {}; + const mappedRequestOptions = transporter.createMappedRequestOptions(options); + if (forwardToReplicas) { + mappedRequestOptions.queryParameters.forwardToReplicas = 1; // eslint-disable-line functional/immutable-data + } + if (clearExistingRules) { + mappedRequestOptions.queryParameters.clearExistingRules = 1; // eslint-disable-line functional/immutable-data + } + return clientCommon.createWaitablePromise(base.transporter.write({ + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode('1/indexes/%s/rules/batch', base.indexName), + data: rules, + }, mappedRequestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const saveSynonym = (base) => { + return (synonym, requestOptions) => { + return saveSynonyms(base)([synonym], requestOptions); + }; +}; + +const saveSynonyms = (base) => { + return (synonyms, requestOptions) => { + const { forwardToReplicas, clearExistingSynonyms, replaceExistingSynonyms, ...options } = requestOptions || {}; + const mappedRequestOptions = transporter.createMappedRequestOptions(options); + if (forwardToReplicas) { + mappedRequestOptions.queryParameters.forwardToReplicas = 1; // eslint-disable-line functional/immutable-data + } + if (replaceExistingSynonyms || clearExistingSynonyms) { + mappedRequestOptions.queryParameters.replaceExistingSynonyms = 1; // eslint-disable-line functional/immutable-data + } + return clientCommon.createWaitablePromise(base.transporter.write({ + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode('1/indexes/%s/synonyms/batch', base.indexName), + data: synonyms, + }, mappedRequestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const search = (base) => { + return (query, requestOptions) => { + return base.transporter.read({ + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode('1/indexes/%s/query', base.indexName), + data: { + query, + }, + cacheable: true, + }, requestOptions); + }; +}; + +const searchForFacetValues = (base) => { + return (facetName, facetQuery, requestOptions) => { + return base.transporter.read({ + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode('1/indexes/%s/facets/%s/query', base.indexName, facetName), + data: { + facetQuery, + }, + cacheable: true, + }, requestOptions); + }; +}; + +const searchRules = (base) => { + return (query, requestOptions) => { + return base.transporter.read({ + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode('1/indexes/%s/rules/search', base.indexName), + data: { + query, + }, + }, requestOptions); + }; +}; + +const searchSynonyms = (base) => { + return (query, requestOptions) => { + return base.transporter.read({ + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode('1/indexes/%s/synonyms/search', base.indexName), + data: { + query, + }, + }, requestOptions); + }; +}; + +const setSettings = (base) => { + return (settings, requestOptions) => { + const { forwardToReplicas, ...options } = requestOptions || {}; + const mappedRequestOptions = transporter.createMappedRequestOptions(options); + if (forwardToReplicas) { + mappedRequestOptions.queryParameters.forwardToReplicas = 1; // eslint-disable-line functional/immutable-data + } + return clientCommon.createWaitablePromise(base.transporter.write({ + method: requesterCommon.MethodEnum.Put, + path: clientCommon.encode('1/indexes/%s/settings', base.indexName), + data: settings, + }, mappedRequestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const waitTask = (base) => { + return (taskID, requestOptions) => { + return clientCommon.createRetryablePromise(retry => { + return getTask(base)(taskID, requestOptions).then(response => { + return response.status !== 'published' ? retry() : undefined; + }); + }); + }; +}; + +const ApiKeyACLEnum = { + AddObject: 'addObject', + Analytics: 'analytics', + Browser: 'browse', + DeleteIndex: 'deleteIndex', + DeleteObject: 'deleteObject', + EditSettings: 'editSettings', + Inference: 'inference', + ListIndexes: 'listIndexes', + Logs: 'logs', + Personalization: 'personalization', + Recommendation: 'recommendation', + Search: 'search', + SeeUnretrievableAttributes: 'seeUnretrievableAttributes', + Settings: 'settings', + Usage: 'usage', +}; + +const BatchActionEnum = { + AddObject: 'addObject', + UpdateObject: 'updateObject', + PartialUpdateObject: 'partialUpdateObject', + PartialUpdateObjectNoCreate: 'partialUpdateObjectNoCreate', + DeleteObject: 'deleteObject', + DeleteIndex: 'delete', + ClearIndex: 'clear', +}; + +const ScopeEnum = { + Settings: 'settings', + Synonyms: 'synonyms', + Rules: 'rules', +}; + +const StrategyEnum = { + None: 'none', + StopIfEnoughMatches: 'stopIfEnoughMatches', +}; + +const SynonymEnum = { + Synonym: 'synonym', + OneWaySynonym: 'oneWaySynonym', + AltCorrection1: 'altCorrection1', + AltCorrection2: 'altCorrection2', + Placeholder: 'placeholder', +}; + +exports.ApiKeyACLEnum = ApiKeyACLEnum; +exports.BatchActionEnum = BatchActionEnum; +exports.ScopeEnum = ScopeEnum; +exports.StrategyEnum = StrategyEnum; +exports.SynonymEnum = SynonymEnum; +exports.addApiKey = addApiKey; +exports.assignUserID = assignUserID; +exports.assignUserIDs = assignUserIDs; +exports.batch = batch; +exports.browseObjects = browseObjects; +exports.browseRules = browseRules; +exports.browseSynonyms = browseSynonyms; +exports.chunkedBatch = chunkedBatch; +exports.clearDictionaryEntries = clearDictionaryEntries; +exports.clearObjects = clearObjects; +exports.clearRules = clearRules; +exports.clearSynonyms = clearSynonyms; +exports.copyIndex = copyIndex; +exports.copyRules = copyRules; +exports.copySettings = copySettings; +exports.copySynonyms = copySynonyms; +exports.createBrowsablePromise = createBrowsablePromise; +exports.createMissingObjectIDError = createMissingObjectIDError; +exports.createObjectNotFoundError = createObjectNotFoundError; +exports.createSearchClient = createSearchClient; +exports.createValidUntilNotFoundError = createValidUntilNotFoundError; +exports.customRequest = customRequest; +exports.deleteApiKey = deleteApiKey; +exports.deleteBy = deleteBy; +exports.deleteDictionaryEntries = deleteDictionaryEntries; +exports.deleteIndex = deleteIndex; +exports.deleteObject = deleteObject; +exports.deleteObjects = deleteObjects; +exports.deleteRule = deleteRule; +exports.deleteSynonym = deleteSynonym; +exports.exists = exists; +exports.findAnswers = findAnswers; +exports.findObject = findObject; +exports.generateSecuredApiKey = generateSecuredApiKey; +exports.getApiKey = getApiKey; +exports.getAppTask = getAppTask; +exports.getDictionarySettings = getDictionarySettings; +exports.getLogs = getLogs; +exports.getObject = getObject; +exports.getObjectPosition = getObjectPosition; +exports.getObjects = getObjects; +exports.getRule = getRule; +exports.getSecuredApiKeyRemainingValidity = getSecuredApiKeyRemainingValidity; +exports.getSettings = getSettings; +exports.getSynonym = getSynonym; +exports.getTask = getTask; +exports.getTopUserIDs = getTopUserIDs; +exports.getUserID = getUserID; +exports.hasPendingMappings = hasPendingMappings; +exports.initIndex = initIndex; +exports.listApiKeys = listApiKeys; +exports.listClusters = listClusters; +exports.listIndices = listIndices; +exports.listUserIDs = listUserIDs; +exports.moveIndex = moveIndex; +exports.multipleBatch = multipleBatch; +exports.multipleGetObjects = multipleGetObjects; +exports.multipleQueries = multipleQueries; +exports.multipleSearchForFacetValues = multipleSearchForFacetValues; +exports.partialUpdateObject = partialUpdateObject; +exports.partialUpdateObjects = partialUpdateObjects; +exports.removeUserID = removeUserID; +exports.replaceAllObjects = replaceAllObjects; +exports.replaceAllRules = replaceAllRules; +exports.replaceAllSynonyms = replaceAllSynonyms; +exports.replaceDictionaryEntries = replaceDictionaryEntries; +exports.restoreApiKey = restoreApiKey; +exports.saveDictionaryEntries = saveDictionaryEntries; +exports.saveObject = saveObject; +exports.saveObjects = saveObjects; +exports.saveRule = saveRule; +exports.saveRules = saveRules; +exports.saveSynonym = saveSynonym; +exports.saveSynonyms = saveSynonyms; +exports.search = search; +exports.searchDictionaryEntries = searchDictionaryEntries; +exports.searchForFacetValues = searchForFacetValues; +exports.searchRules = searchRules; +exports.searchSynonyms = searchSynonyms; +exports.searchUserIDs = searchUserIDs; +exports.setDictionarySettings = setDictionarySettings; +exports.setSettings = setSettings; +exports.updateApiKey = updateApiKey; +exports.waitAppTask = waitAppTask; +exports.waitTask = waitTask; diff --git a/scripts/node_modules/@algolia/client-search/dist/client-search.d.ts b/scripts/node_modules/@algolia/client-search/dist/client-search.d.ts new file mode 100644 index 000000000..0d3b7cb05 --- /dev/null +++ b/scripts/node_modules/@algolia/client-search/dist/client-search.d.ts @@ -0,0 +1,2597 @@ +import { AuthModeType } from '@algolia/client-common'; +import { ClientTransporterOptions } from '@algolia/client-common'; +import { CreateClient } from '@algolia/client-common'; +import { Request as Request_2 } from '@algolia/transporter'; +import { RequestOptions } from '@algolia/transporter'; +import { Transporter } from '@algolia/transporter'; +import { WaitablePromise } from '@algolia/client-common'; + +export declare const addApiKey: (base: SearchClient) => (acl: readonly ApiKeyACLType[], requestOptions?: (AddApiKeyOptions & Pick) | undefined) => Readonly>; + +export declare type AddApiKeyOptions = { + /** + * A Unix timestamp used to define the expiration date of the API key. + */ + readonly validity?: number; + /** + * Specify the maximum number of hits this API key can retrieve in one call. + * This parameter can be used to protect you from attempts at retrieving your entire index contents by massively querying the index. + */ + readonly maxHitsPerQuery?: number; + /** + * Specify the maximum number of API calls allowed from an IP address per hour. Each time an API call is performed with this key, a check is performed. + */ + readonly maxQueriesPerIPPerHour?: number; + /** + * Specify the list of targeted indices. You can target all indices starting with a prefix or ending with a suffix using the ‘*’ character. + */ + readonly indexes?: readonly string[]; + /** + * Specify the list of referers. You can target all referers starting with a prefix, ending with a suffix using the ‘*’ character. + */ + readonly referers?: readonly string[]; + /** + * Specify the list of query parameters. You can force the query parameters for a query using the url string format. + */ + readonly queryParameters?: string; + /** + * Specify a description of the API key. Used for informative purposes only. It has impact on the functionality of the API key. + */ + readonly description?: string; +}; + +export declare type AddApiKeyResponse = { + /** + * The returned api key. + */ + key: string; + /** + * Date of creation of the api key. + */ + createdAt: string; +}; + +export declare const ApiKeyACLEnum: Readonly>; + +export declare type ApiKeyACLType = 'addObject' | 'analytics' | 'browse' | 'deleteIndex' | 'deleteObject' | 'editSettings' | 'inference' | 'listIndexes' | 'logs' | 'personalization' | 'recommendation' | 'search' | 'seeUnretrievableAttributes' | 'settings' | 'usage'; + +export declare const assignUserID: (base: SearchClient) => (userID: string, clusterName: string, requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare type AssignUserIDResponse = { + /** + * Date of creation of the userId. + */ + createdAt: string; +}; + +export declare const assignUserIDs: (base: SearchClient) => (userIDs: readonly string[], clusterName: string, requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare type AssignUserIDsResponse = { + /** + * Date of creation of the userId + */ + createdAt: string; +}; + +export declare type AutomaticFacetFilter = { + /** + * Attribute to filter on. This must match a facet placeholder in the rule’s pattern. + */ + readonly facet: string; + /** + * Whether the filter is disjunctive (true) or conjunctive (false). + */ + readonly disjunctive?: boolean; + /** + * Score for the filter. Typically used for optional or disjunctive filters. + */ + readonly score?: number; +}; + +export declare const batch: (base: SearchIndex) => (requests: readonly BatchRequest[], requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare const BatchActionEnum: Readonly>; + +export declare type BatchActionType = 'addObject' | 'updateObject' | 'partialUpdateObject' | 'partialUpdateObjectNoCreate' | 'deleteObject' | 'delete' | 'clear'; + +export declare type BatchRequest = { + /** + * The batch action. + */ + readonly action: BatchActionType; + /** + * The body of the given `action`. Note that, bodies difer + * depending of the action. + */ + readonly body: Record; +}; + +export declare type BatchResponse = { + /** + * The operation task id. May be used to perform a wait task. + */ + taskID: number; + /** + * The object ids created/updated by the batch request. + */ + objectIDs: string[]; +}; + +export declare const browseObjects: (base: SearchIndex) => (requestOptions?: (SearchOptions & BrowseOptions & RequestOptions) | undefined) => Readonly>; + +export declare type BrowseOptions = { + /** + * The callback called for each batch of objects. + */ + readonly batch?: (batch: ReadonlyArray) => any; + /** + * The callback called to determine if the browse should stop. By + * default this checks whether there's any more content to get. + */ + readonly shouldStop?: (response: BrowseResponse) => boolean; +}; + +export declare type BrowseRequestData = { + /** + * If available, should be used for browsing to the next page. + */ + readonly cursor?: string; + /** + * If cursor is not available, should be used for browsing to the next page. + */ + readonly page?: number; +}; + +export declare type BrowseResponse = { + /** + * The hits per page. + */ + hits: Array; + /** + * The cursor used for iterate on the next page. + */ + cursor?: string; +}; + +export declare const browseRules: (base: SearchIndex) => (requestOptions?: (SearchRulesOptions & BrowseOptions & RequestOptions) | undefined) => Readonly>; + +export declare const browseSynonyms: (base: SearchIndex) => (requestOptions?: (SearchSynonymsOptions & BrowseOptions & RequestOptions) | undefined) => Readonly>; + +export declare const chunkedBatch: (base: SearchIndex) => (bodies: readonly object[], action: BatchActionType, requestOptions?: (RequestOptions & ChunkOptions) | undefined) => Readonly>; + +export declare type ChunkedBatchResponse = { + /** + * The operations task ids. May be used to perform a wait task. + */ + taskIDs: number[]; + /** + * The object ids created/updated/deleted by the multiple requests. + */ + objectIDs: string[]; +}; + +export declare type ChunkOptions = { + /** + * The number of objects per batch. + */ + readonly batchSize?: number; +}; + +export declare const clearDictionaryEntries: (base: SearchClient) => (dictionary: DictionaryName, requestOptions?: (RequestOptions & DictionaryEntriesOptions) | undefined) => Readonly>; + +export declare const clearObjects: (base: SearchIndex) => (requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare const clearRules: (base: SearchIndex) => (requestOptions?: (RequestOptions & ClearRulesOptions) | undefined) => Readonly>; + +export declare type ClearRulesOptions = { + /** + * If the clear rules request should be forward to replicas. + */ + readonly forwardToReplicas?: boolean; +}; + +export declare const clearSynonyms: (base: SearchIndex) => (requestOptions?: (ClearSynonymsOptions & RequestOptions) | undefined) => Readonly>; + +export declare type ClearSynonymsOptions = { + /** + * If the clear synonyms request should be forward to replicas. + */ + readonly forwardToReplicas?: boolean; +}; + +export declare type Cluster = { + /** + * The cluster name + */ + readonly clusterName: string; + /** + * Number of records in the cluster. + */ + readonly nbRecords: number; + /** + * Number of users assign to the cluster. + */ + readonly nbUserIDs: number; + /** + * Data size taken by all the users assigned to the cluster. + */ + readonly dataSize: number; +}; + +export declare type Condition = { + /** + * Query patterns are expressed as a string with a specific syntax. A pattern is a sequence of tokens. + */ + readonly pattern?: string; + /** + * Apply this rule only when the filter matches. + */ + readonly filters?: string; + /** + * is | startsWith | endsWith | contains: Whether the pattern must match the beginning or the end of the query string, or both, or none. + */ + readonly anchoring?: 'is' | 'startsWith' | 'endsWith' | 'contains'; + /** + * Rule context (format: [A-Za-z0-9_-]+). When specified, the rule is contextual and applies only when the same context is specified at query time (using the ruleContexts parameter). + * When absent, the rule is generic and always applies (provided that its other conditions are met, of course). + */ + readonly context?: string; + /** + * If set to true, alternatives make the rule to trigger on synonyms, typos and plurals. + * Note that setting ignorePlurals to false overrides this parameter. + */ + readonly alternatives?: boolean; +}; + +export declare type Consequence = { + /** + * Additional search parameters. Any valid search parameter is allowed. + */ + readonly params?: ConsequenceParams & Pick>; + /** + * Objects to promote as hits. + */ + readonly promote?: readonly ConsequencePromote[]; + /** + * Objects to hide from hits. + */ + readonly hide?: ReadonlyArray<{ + readonly objectID: string; + }>; + /** + * Whether the Query Rule should promote or not promoted items. + */ + readonly filterPromotes?: boolean; + /** + * Custom JSON object that will be appended to the userData array in the response. + * This object is not interpreted by the API. It is limited to 1kB of minified JSON. + */ + readonly userData?: any; +}; + +export declare type ConsequenceParams = { + /** + * When providing a string, it replaces the entire query string. + * When providing an object, it describes incremental edits to be made to the query string (but you can’t do both). + */ + readonly query?: ConsequenceQuery | string; + /** + * Names of facets to which automatic filtering must be applied; they must match the facet name of a facet value placeholder in the query pattern. + */ + readonly automaticFacetFilters?: readonly AutomaticFacetFilter[] | readonly string[]; + /** + * Same syntax as automaticFacetFilters, but the engine treats the filters as optional. + * Behaves like optionalFilters. + */ + readonly automaticOptionalFacetFilters?: readonly AutomaticFacetFilter[] | readonly string[]; + /** + * Content defining how the search interface should be rendered. + * A default value for this can be set via settings + */ + readonly renderingContent?: Settings['renderingContent']; +}; + +export declare type ConsequencePromote = { + /** + * Unique identifier of the object to promote. + */ + readonly objectID: string; + /** + * Promoted rank for the object (zero-based). + */ + readonly position: number; +} | { + /** + * List of unique identifiers for the objects to promote. + */ + readonly objectIDs: readonly string[]; + /** + * Promoted start rank for the objects (zero-based). + */ + readonly position: number; +}; + +export declare type ConsequenceQuery = { + /** + * List of removes. + */ + readonly remove?: readonly string[]; + /** + * List of edits. + */ + readonly edits?: ReadonlyArray<{ + /** + * Type of edit. + */ + readonly type?: 'remove' | 'replace'; + /** + * Text or patterns to remove from the query string. + */ + readonly delete?: string; + /** + * Text that should be inserted in place of the removed text inside the query string. + */ + readonly insert?: string; + }>; +}; + +export declare const copyIndex: (base: SearchClient) => (from: string, to: string, requestOptions?: (CopyIndexOptions & RequestOptions) | undefined) => Readonly>; + +export declare type CopyIndexOptions = { + readonly scope?: readonly ScopeType[]; +}; + +export declare const copyRules: (base: SearchClient) => (from: string, to: string, requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare const copySettings: (base: SearchClient) => (from: string, to: string, requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare const copySynonyms: (base: SearchClient) => (from: string, to: string, requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare function createBrowsablePromise(options: { + readonly shouldStop: (response: BrowseResponse) => boolean; + readonly request: (data: BrowseRequestData) => Readonly>>; +} & BrowseOptions): Readonly>; + +export declare type CreateIndex = (...args: any) => any; +}>(indexName: string, options?: { + readonly methods?: TMethods; +}) => SearchIndex & { + [key in keyof TMethods extends string ? keyof TMethods : never]: ReturnType; +}; + +export declare function createMissingObjectIDError(): Error; + +export declare function createObjectNotFoundError(): Error; + +export declare const createSearchClient: CreateClient; + +export declare function createValidUntilNotFoundError(): Error; + +export declare const customRequest: (base: SearchClient) => (request: Request_2, requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare const deleteApiKey: (base: SearchClient) => (apiKey: string, requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare type DeleteApiKeyResponse = { + /** + * The date when the api key was deleted. + */ + deletedAt: string; +}; + +export declare const deleteBy: (base: SearchIndex) => (filters: DeleteByFiltersOptions, requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare type DeleteByFiltersOptions = { + /** + * Filter the query with numeric, facet and/or tag filters. + */ + readonly filters?: string; + /** + * Filter hits by facet value. + */ + readonly facetFilters?: string | readonly string[] | ReadonlyArray; + /** + * Filter on numeric attributes. + */ + readonly numericFilters?: string | readonly string[] | ReadonlyArray; + /** + * Filter hits by tags. tagFilters is a different way of filtering, which relies on the _tags + * attribute. It uses a simpler syntax than filters. You can use it when you want to do + * simple filtering based on tags. + */ + readonly tagFilters?: string | readonly string[] | ReadonlyArray; + /** + * Search for entries around a central geolocation, enabling a geo search within a circular area. + */ + readonly aroundLatLng?: string; + /** + * Search for entries around a given location automatically computed from the requester’s IP address. + */ + readonly aroundLatLngViaIP?: boolean; + /** + * Search inside a rectangular area (in geo coordinates). + */ + readonly insideBoundingBox?: ReadonlyArray | string; + /** + * Search inside a polygon (in geo coordinates). + */ + readonly insidePolygon?: ReadonlyArray; +}; + +export declare const deleteDictionaryEntries: (base: SearchClient) => (dictionary: DictionaryName, objectIDs: readonly string[], requestOptions?: (RequestOptions & DictionaryEntriesOptions) | undefined) => Readonly>; + +export declare const deleteIndex: (base: SearchIndex) => (requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare const deleteObject: (base: SearchIndex) => (objectID: string, requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare const deleteObjects: (base: SearchIndex) => (objectIDs: readonly string[], requestOptions?: (RequestOptions & ChunkOptions) | undefined) => Readonly>; + +export declare type DeleteResponse = { + /** + * The operation task id. May be used to perform a wait task. + */ + taskID: number; +}; + +export declare const deleteRule: (base: SearchIndex) => (objectID: string, requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare const deleteSynonym: (base: SearchIndex) => (objectID: string, requestOptions?: (RequestOptions & DeleteSynonymOptions) | undefined) => Readonly>; + +export declare type DeleteSynonymOptions = { + /** + * If the delete synonym request should be forward to replicas. + */ + readonly forwardToReplicas?: boolean; +}; + +export declare type DictionaryEntriesOptions = { + /** + * Array of dictionary entries + */ + readonly dictionaryEntries: readonly DictionaryEntry[]; +}; + +export declare type DictionaryEntriesResponse = { + /** + * When the given rules got saved. + */ + updatedAt: number; + /** + * The operation task id. May be used to perform a wait task. + */ + taskID: number; +}; + +export declare type DictionaryEntry = { + /** + * Unique identifier for the rule (format: [A-Za-z0-9_-]+). + */ + readonly objectID: string; + readonly language: string; + readonly word?: string; + readonly words?: readonly string[]; + readonly decomposition?: readonly string[]; + readonly state?: 'enabled' | 'disabled'; +}; + +export declare type DictionaryName = 'plurals' | 'stopwords' | 'compounds'; + +export declare type DictionarySettings = { + /** + * Disable the builtin Algolia entries for a type of dictionary per language. + */ + readonly disableStandardEntries: RequireAtLeastOne>>; +}; + +export declare const exists: (base: SearchIndex) => (requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare type FacetHit = { + /** + * The value of the facet. + */ + readonly value: string; + /** + * The highlighted value. + */ + readonly highlighted: string; + /** + * The count. + */ + readonly count: number; +}; + +export declare const findAnswers: (base: SearchIndex) => (query: string, queryLanguages: readonly string[], requestOptions?: (RequestOptions & FindAnswersOptions) | undefined) => Readonly>>; + +export declare type FindAnswersOptions = { + /** + * Attributes to use for predictions. + * If using the default (["*"]), all attributes are used to find answers. + */ + readonly attributesForPrediction?: readonly string[]; + /** + * Maximum number of answers to retrieve from the Answers Engine. + * Cannot be greater than 1000. + */ + readonly nbHits?: number; + /** + * Threshold for the answers’ confidence score: + * only answers with extracts that score above this threshold are returned. + */ + readonly threshold?: number; + /** + * Whether the attribute name in which the answer was found should be returned. + * This option is expensive in processing time. + */ + readonly returnExtractAttribute?: boolean; + /** + * Algolia search parameters to use to fetch the hits. + * Can be any search parameter, except: + * - attributesToSnippet + * - hitsPerPage + * - queryType + * - naturalLanguages and associated parameters + * (removeStopWords, ignorePlurals, and removeWordsIfNoResults) + */ + readonly searchParameters?: Omit; +}; + +export declare type FindAnswersResponse = Omit, 'hits'> & { + /** + * The hits returned by the search. + * + * Hits are ordered according to the ranking or sorting of the index being queried. + */ + hits: Array>; +}; + +export declare const findObject: (base: SearchIndex) => (callback: (object: TObject & ObjectWithObjectID) => boolean, requestOptions?: (FindObjectOptions & RequestOptions) | undefined) => Readonly>>; + +export declare type FindObjectOptions = { + /** + * If the underlying find object options should paginate + * over a search method. + */ + readonly paginate?: boolean; + /** + * The query used by the underlying find object to + * find the object. + */ + readonly query?: string; +}; + +export declare type FindObjectResponse = { + /** + * The found object. + */ + object: TObject & ObjectWithObjectID; + /** + * The position where the object was found. + */ + position: number; + /** + * The page where the object was found. + */ + page: number; +}; + +export declare const generateSecuredApiKey: () => (parentApiKey: string, restrictions: SecuredApiKeyRestrictions) => string; + +export declare const getApiKey: (base: SearchClient) => (apiKey: string, requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare type GetApiKeyResponse = { + /** + * The api key value + */ + value: string; + /** + * Date of creation (Unix timestamp). + */ + createdAt: number; + /** + * List of permissions the key contains. + */ + acl: ApiKeyACLType[]; + /** + * A Unix timestamp used to define the expiration date of the API key. + */ + validity: number; + /** + * Specify the maximum number of hits this API key can retrieve in one call. + * This parameter can be used to protect you from attempts at retrieving your entire index contents by massively querying the index. + */ + maxHitsPerQuery?: number; + /** + * Specify the maximum number of API calls allowed from an IP address per hour. Each time an API call is performed with this key, a check is performed. + */ + maxQueriesPerIPPerHour?: number; + /** + * Specify the list of targeted indices. You can target all indices starting with a prefix or ending with a suffix using the ‘*’ character. + */ + indexes?: string[]; + /** + * Specify the list of referers. You can target all referers starting with a prefix, ending with a suffix using the ‘*’ character. + */ + referers?: string[]; + /** + * IPv4 network allowed to use the generated key. + * This is used for more protection against API key leaking and reuse. + * Note that you can only provide a single source, but you can specify a range of IPs (e.g., 192.168.1.0/24). + */ + restrictSources?: string; + /** + * Specify the list of query parameters. You can force the query parameters for a query using the url string format. + */ + queryParameters?: string; + /** + * Specify a description of the API key. Used for informative purposes only. It has impact on the functionality of the API key. + */ + description?: string; +}; + +export declare const getAppTask: (base: SearchClient) => (taskID: number, requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare const getDictionarySettings: (base: SearchClient) => (requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare type GetDictionarySettingsResponse = { + /** + * Disable the builtin Algolia entries for a type of dictionary per language. + */ + readonly disableStandardEntries: RequireAtLeastOne>>; +}; + +export declare const getLogs: (base: SearchClient) => (requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare type GetLogsOptions = { + /** + * The offset. + */ + readonly offset: number; + /** + * The length size. + */ + readonly length: number; +}; + +export declare type GetLogsResponse = { + /** + * The list of logs. + */ + logs: Log[]; +}; + +export declare const getObject: (base: SearchIndex) => (objectID: string, requestOptions?: (RequestOptions & GetObjectOptions) | undefined) => Readonly>; + +export declare type GetObjectOptions = { + /** + * The attributes that should come with witch object. + */ + readonly attributesToRetrieve?: readonly string[]; +}; + +export declare const getObjectPosition: () => (searchResponse: SearchResponse, objectID: string) => number; + +export declare const getObjects: (base: SearchIndex) => (objectIDs: readonly string[], requestOptions?: (RequestOptions & GetObjectsOptions) | undefined) => Readonly>>; + +export declare type GetObjectsOptions = { + /** + * The attributes that should come with witch object. + */ + readonly attributesToRetrieve?: readonly string[]; +}; + +export declare type GetObjectsResponse = { + /** + * The list of results. + */ + results: Array<(TObject & ObjectWithObjectID) | null>; +}; + +export declare const getRule: (base: SearchIndex) => (objectID: string, requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare const getSecuredApiKeyRemainingValidity: () => (securedApiKey: string) => number; + +export declare const getSettings: (base: SearchIndex) => (requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare const getSynonym: (base: SearchIndex) => (objectID: string, requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare const getTask: (base: SearchIndex) => (taskID: number, requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare const getTopUserIDs: (base: SearchClient) => (requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare type GetTopUserIDsResponse = { + /** + * Mapping of cluster names to top users. + */ + topUsers: Record; +}; + +export declare const getUserID: (base: SearchClient) => (userID: string, requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare const hasPendingMappings: (base: SearchClient) => (requestOptions?: (HasPendingMappingsOptions & RequestOptions) | undefined) => Readonly>; + +export declare type HasPendingMappingsOptions = { + /** + * If the clusters pending mapping state should be on the response. + * + * @defaultValue false + */ + readonly retrieveMappings?: boolean; + /** + * If the clusters pending mapping state should be on the response. + * + * @defaultValue false + * + * @internal + */ + readonly getClusters?: boolean; +}; + +export declare type HasPendingMappingsResponse = { + /** + * If there is any clusters with pending mapping state. + */ + pending: boolean; + /** + * Describe cluster pending (migrating, creating, deleting) mapping state. + */ + clusters?: { + [key: string]: string[]; + }; +}; + +declare type HighlightMatch = { + readonly value: string; + readonly matchLevel: 'none' | 'partial' | 'full'; + readonly matchedWords: readonly string[]; + readonly fullyHighlighted?: boolean; +}; + +export declare type HighlightResult = THit extends string | number ? HighlightMatch : { + [KAttribute in keyof THit]?: HighlightResult; +}; + +export declare type Hit = THit & { + readonly objectID: string; + readonly _highlightResult?: HighlightResult; + readonly _snippetResult?: SnippetResult; + readonly _rankingInfo?: RankingInfo; + readonly _distinctSeqID?: number; +}; + +export declare type Index = { + /** + * Index name. + */ + readonly name: string; + /** + * Index creation date. (ISO-8601 format) + */ + readonly createdAt: string; + /** + * Date of last update. (ISO-8601 format) + */ + readonly updatedAt: string; + /** + * Number of records contained in the index + */ + readonly entries: number; + /** + * Number of bytes of the index in minified format. + */ + readonly dataSize: number; + /** + * Number of bytes of the index binary file. + */ + readonly fileSize: number; + /** + * Last build time in seconds. + */ + readonly lastBuildTimeS: number; + /** + * Number of pending indexing operations. + */ + readonly numberOfPendingTasks: number; + /** + * A boolean which says whether the index has pending tasks. + */ + readonly pendingTask: boolean; + /** + * Only present if the index is a replica. + * Contains the name of the related primary index. + */ + readonly primary?: string; + /** + * Only present if the index is a primary index with replicas. + * Contains the names of all linked replicas. + */ + readonly replicas?: readonly string[]; + /** + * Only present if the index is a virtual replica. + */ + readonly virtual?: boolean; +}; + +export declare type IndexOperationResponse = { + /** + * The operation task id. May be used to perform a wait task. + */ + taskID: number; +}; + +/** + * @deprecated please use `Index` instead of `Indice` + */ +export declare type Indice = Index; + +export declare const initIndex: (base: SearchClient) => CreateIndex; + +export declare const listApiKeys: (base: SearchClient) => (requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare type ListApiKeysResponse = { + /** + * List of keys + */ + keys: GetApiKeyResponse[]; +}; + +export declare const listClusters: (base: SearchClient) => (requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare type ListClustersResponse = { + /** + * List of clusters. + */ + clusters: Cluster[]; +}; + +export declare const listIndices: (base: SearchClient) => (requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare type ListIndicesResponse = { + /** + * Number of pages + */ + nbPages: number; + /** + * List of index response + */ + items: Index[]; +}; + +export declare const listUserIDs: (base: SearchClient) => (requestOptions?: (ListUserIDsOptions & RequestOptions) | undefined) => Readonly>; + +export declare type ListUserIDsOptions = { + /** + * Page to fetch. + */ + readonly page?: number; + /** + * Number of users to retrieve per page. + */ + readonly hitsPerPage?: number; +}; + +export declare type ListUserIDsResponse = { + /** + * List of users id. + */ + userIDs: UserIDResponse[]; +}; + +export declare type Log = { + /** + * Timestamp in ISO-8601 format. + */ + readonly timestamp: string; + /** + * Rest type of the method. + */ + readonly method: string; + /** + * Http response code. + */ + readonly answer_code: string; + /** + * Request body. It’s truncated after 1000 characters. + */ + readonly query_body: string; + /** + * Answer body. It’s truncated after 1000 characters. + */ + readonly answer: string; + /** + * Request URL. + */ + readonly url: string; + /** + * Client ip of the call. + */ + readonly ip: string; + /** + * SHA1 ID of entry. + */ + readonly sha1: string; + /** + * Request Headers (API Key is obfuscated). + */ + readonly query_headers: string; + /** + * Number Of Api Calls + */ + readonly nb_api_calls?: string; + /** + * Processing time for the query. This does not include network time. + */ + readonly processing_time_ms: string; + /** + * Number of hits returned for the query. + */ + readonly query_nb_hits?: string; + /** + * Exhaustive flags used during the query. + */ + readonly exhaustive?: boolean; + /** + * Index name of the log + */ + readonly index?: string; + /** + * Internal queries performed for this query. + */ + readonly inner_queries: ReadonlyArray<{ + /** + * Index name of the query. + */ + readonly index_name: string; + /** + * Query ID of the query. + */ + readonly query_id?: string; + /** + * The offset of the query. + */ + readonly offset?: number; + /** + * The user token of the query. + */ + readonly user_token?: string; + }>; +}; + +export declare const moveIndex: (base: SearchClient) => (from: string, to: string, requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare const multipleBatch: (base: SearchClient) => (requests: readonly MultipleBatchRequest[], requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare type MultipleBatchRequest = { + /** + * The index name where the multiple batch are going to be applied. + */ + readonly indexName: string; + /** + * The action used. + */ + readonly action: BatchActionType; + /** + * The body associated with the request. + */ + readonly body: Record; +}; + +export declare type MultipleBatchResponse = { + /** + * The list of object ids. + */ + objectIDs: string[]; + /** + * The operation task id. May be used to perform a wait task. + */ + taskID: Record; +}; + +export declare type MultipleGetObject = { + /** + * The index name. + */ + readonly indexName: string; + /** + * The object id. + */ + readonly objectID: string; + /** + * The attributes that should be returned with the object. + */ + readonly attributesToRetrieve?: readonly string[]; +}; + +export declare const multipleGetObjects: (base: SearchClient) => (requests: readonly MultipleGetObject[], requestOptions?: RequestOptions | undefined) => Readonly>>; + +export declare type MultipleGetObjectsResponse = { + /** + * The list of objects. + */ + results: Array; +}; + +export declare const multipleQueries: (base: SearchClient) => (queries: readonly MultipleQueriesQuery[], requestOptions?: (RequestOptions & MultipleQueriesOptions) | undefined) => Readonly>>; + +export declare type MultipleQueriesOptions = { + readonly strategy?: StrategyType; +}; + +export declare type MultipleQueriesQuery = SharedMultipleQueriesQuery & ({ + readonly type?: 'default'; +} | { + readonly type: 'facet'; + /** + * The facet name. + */ + readonly facet: string; + /** + * The search options. + */ + readonly params?: SharedMultipleQueriesQuery['params'] & { + /** + * The search query used to search the facet attribute. Follows the same rules for an index query: a single character, a partial word, a word, or a phrase. + */ + readonly facetQuery?: string; + }; +}); + +export declare type MultipleQueriesResponse = { + /** + * The list of results. + */ + results: Array | SearchForFacetValuesResponse>; +}; + +export declare const multipleSearchForFacetValues: (base: SearchClient) => (queries: readonly { + readonly indexName: string; + readonly params: SearchForFacetValuesQueryParams & SearchOptions; +}[], requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare type ObjectWithObjectID = { + /** + * The object id of the object. + */ + readonly objectID: string; +}; + +export declare const partialUpdateObject: (base: SearchIndex) => (object: Record, requestOptions?: (RequestOptions & ChunkOptions & PartialUpdateObjectsOptions) | undefined) => Readonly>; + +export declare type PartialUpdateObjectResponse = { + /** + * The operation task id. May be used to perform a wait task. + */ + taskID: number; + /** + * The object id updated. + */ + objectID: string; +}; + +export declare const partialUpdateObjects: (base: SearchIndex) => (objects: readonly Record[], requestOptions?: (RequestOptions & ChunkOptions & PartialUpdateObjectsOptions) | undefined) => Readonly>; + +export declare type PartialUpdateObjectsOptions = { + /** + * If the object should be created when does not exist. + */ + readonly createIfNotExists?: boolean; +}; + +export declare type RankingInfo = { + readonly promoted: boolean; + readonly nbTypos: number; + readonly firstMatchedWord: number; + readonly proximityDistance?: number; + readonly geoDistance: number; + readonly geoPrecision?: number; + readonly nbExactWords: number; + readonly words: number; + readonly filters: number; + readonly userScore: number; + readonly matchedGeoLocation?: { + readonly lat: number; + readonly lng: number; + readonly distance: number; + }; + readonly personalization?: { + readonly filtersScore: number; + readonly rankingScore: number; + readonly score: number; + }; + readonly promotedByReRanking?: boolean; +}; + +export declare type RedirectRuleIndexMetadata = { + /** + * Source index for the redirect rule + */ + readonly source: string; + /** + * Destination index for the redirect rule + */ + readonly dest: string; + /** + * Reason for the redirect rule + */ + readonly reason: string; + /** + * Status for the redirect rule + */ + readonly succeed: boolean; + /** + * Data for the redirect rule + */ + readonly data: { + /** + * Rule objectId + */ + readonly ruleObjectID: string; + }; +}; + +export declare const removeUserID: (base: SearchClient) => (userID: string, requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare type RemoveUserIDResponse = { + /** + * When the given `userID` got removed. + */ + deletedAt: string; +}; + +export declare const replaceAllObjects: (base: SearchIndex) => (objects: readonly Readonly>[], requestOptions?: (ReplaceAllObjectsOptions & ChunkOptions & SaveObjectsOptions & RequestOptions) | undefined) => Readonly>; + +export declare type ReplaceAllObjectsOptions = { + /** + * If the all objects should be replaced using wait operations. Keep + * in mind that, when the `safe` option is used, the operation may + * take a little more than expected. + */ + readonly safe?: boolean; +}; + +export declare const replaceAllRules: (base: SearchIndex) => (rules: readonly Rule[], requestOptions?: (RequestOptions & SaveRulesOptions) | undefined) => Readonly>; + +export declare const replaceAllSynonyms: (base: SearchIndex) => (synonyms: readonly Synonym[], requestOptions?: (RequestOptions & Pick) | undefined) => Readonly>; + +export declare const replaceDictionaryEntries: (base: SearchClient) => (dictionary: DictionaryName, entries: readonly DictionaryEntry[], requestOptions?: (RequestOptions & DictionaryEntriesOptions) | undefined) => Readonly>; + +export declare type RequireAtLeastOne = { + [TKey in keyof TType]-?: Required> & Partial>>; +}[keyof TType]; + +export declare const restoreApiKey: (base: SearchClient) => (apiKey: string, requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare type RestoreApiKeyResponse = { + /** + * Restoration date of the API key. + */ + createdAt: string; +}; + +export declare type Rule = { + /** + * Unique identifier for the rule (format: [A-Za-z0-9_-]+). + */ + readonly objectID: string; + /** + * Condition of the rule, expressed using the following variables: pattern, anchoring, context. + * + * @deprecated This parameter is deprecated in favor of `conditions`. + */ + readonly condition?: Condition; + /** + * Conditions of the rule, expressed using the following variables: pattern, anchoring, context. + */ + readonly conditions?: readonly Condition[]; + /** + * Consequence of the rule. At least one of the following object must be used: params, promote, hide, userData. + */ + readonly consequence?: Consequence; + /** + * This field is intended for rule management purposes, in particular to ease searching for rules and presenting them to human readers. It is not interpreted by the API. + */ + readonly description?: string; + /** + * Whether the rule is enabled. Disabled rules remain in the index, but are not applied at query time. + */ + readonly enabled?: boolean; + /** + * By default, rules are permanently valid. When validity periods are specified, the rule applies only during those periods; it is ignored the rest of the time. + * The list must not be empty. + */ + readonly validity?: readonly TimeRange[]; +}; + +export declare const saveDictionaryEntries: (base: SearchClient) => (dictionary: DictionaryName, entries: readonly DictionaryEntry[], requestOptions?: (RequestOptions & DictionaryEntriesOptions) | undefined) => Readonly>; + +export declare const saveObject: (base: SearchIndex) => (object: Readonly>, requestOptions?: (RequestOptions & ChunkOptions & SaveObjectsOptions) | undefined) => Readonly>; + +export declare type SaveObjectResponse = { + /** + * The operation task id. May be used to perform a wait task. + */ + taskID: number; + /** + * The object id saved. + */ + objectID: string; +}; + +export declare const saveObjects: (base: SearchIndex) => (objects: readonly Readonly>[], requestOptions?: (RequestOptions & ChunkOptions & SaveObjectsOptions) | undefined) => Readonly>; + +export declare type SaveObjectsOptions = { + /** + * If the object id should be generated when does not exists. + */ + readonly autoGenerateObjectIDIfNotExist?: boolean; +}; + +export declare const saveRule: (base: SearchIndex) => (rule: Rule, requestOptions?: (RequestOptions & SaveRulesOptions) | undefined) => Readonly>; + +export declare type SaveRuleResponse = { + /** + * When the given rules got saved. + */ + updatedAt: number; + /** + * The operation task id. May be used to perform a wait task. + */ + taskID: number; +}; + +export declare const saveRules: (base: SearchIndex) => (rules: readonly Rule[], requestOptions?: (RequestOptions & SaveRulesOptions) | undefined) => Readonly>; + +export declare type SaveRulesOptions = { + /** + * If the saved rules should be forward to replicas. + */ + readonly forwardToReplicas?: boolean; + /** + * If the existing rules should be removed. + */ + readonly clearExistingRules?: boolean; +}; + +export declare type SaveRulesResponse = { + /** + * When the given rules got saved. + */ + updatedAt: number; + /** + * The operation task id. May be used to perform a wait task. + */ + taskID: number; +}; + +export declare const saveSynonym: (base: SearchIndex) => (synonym: Synonym, requestOptions?: (RequestOptions & SaveSynonymsOptions) | undefined) => Readonly>; + +export declare type SaveSynonymResponse = { + /** + * When the given synonyms got saved. + */ + updatedAt: number; + /** + * The operation task id. May be used to perform a wait task. + */ + taskID: number; +}; + +export declare const saveSynonyms: (base: SearchIndex) => (synonyms: readonly Synonym[], requestOptions?: (SaveSynonymsOptions & RequestOptions) | undefined) => Readonly>; + +export declare type SaveSynonymsOptions = { + /** + * If the saved synonyms should be forward to replicas. + */ + readonly forwardToReplicas?: boolean; + /** + * If the existing synonyms should be removed. + * @deprecated use clearExistingSynonyms + */ + readonly replaceExistingSynonyms?: boolean; + /** + * If the existing synonyms should be removed. + */ + readonly clearExistingSynonyms?: boolean; +}; + +export declare type SaveSynonymsResponse = { + /** + * When the given synonyms got saved. + */ + updatedAt: number; + /** + * The operation task id. May be used to perform a wait task. + */ + taskID: number; +}; + +export declare const ScopeEnum: Readonly>; + +export declare type ScopeType = 'settings' | 'synonyms' | 'rules'; + +export declare const search: (base: SearchIndex) => (query: string, requestOptions?: (RequestOptions & SearchOptions) | undefined) => Readonly>>; + +export declare type SearchClient = { + /** + * The application id. + */ + readonly appId: string; + /** + * The underlying transporter. + */ + readonly transporter: Transporter; + /** + * Mutates the transporter, adding the given user agent. + */ + readonly addAlgoliaAgent: (segment: string, version?: string) => void; + /** + * Clears both requests and responses caches. + */ + readonly clearCache: () => Readonly>; +}; + +export declare type SearchClientOptions = { + /** + * The application id. + */ + readonly appId: string; + /** + * The api key. + */ + readonly apiKey: string; + /** + * The auth mode type. In browser environments credentials may + * be passed within the headers. + */ + readonly authMode?: AuthModeType; +}; + +export declare const searchDictionaryEntries: (base: SearchClient) => (dictionary: DictionaryName, query: string, requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare type SearchDictionaryEntriesResponse = { + /** + * The dictionary entries returned by the search. + */ + hits: DictionaryEntry[]; + /** + * Index of the current page (zero-based). + */ + page: number; + /** + * Number of dictionary entries matched by the query. + */ + nbHits: number; + /** + * Number of pages returned. + * + * Calculation is based on the total number of hits (nbHits) divided by the + * number of hits per page (hitsPerPage), rounded up to the nearest integer. + */ + nbPages: number; +}; + +export declare const searchForFacetValues: (base: SearchIndex) => (facetName: string, facetQuery: string, requestOptions?: (RequestOptions & SearchOptions) | undefined) => Readonly>; + +export declare type SearchForFacetValuesQueryParams = { + /** + * The facet name. + */ + readonly facetName: string; + /** + * The facet query. + */ + readonly facetQuery: string; +}; + +export declare type SearchForFacetValuesResponse = { + /** + * The list of facet hits. + */ + facetHits: FacetHit[]; + /** + * The exhaustive facets count. + */ + exhaustiveFacetsCount: boolean; + /** + * The time that the API toke the process the request. + */ + processingTimeMS?: number; +}; + +export declare type SearchIndex = { + /** + * The application id. + */ + readonly appId: string; + /** + * The index name. + */ + readonly indexName: string; + /** + * The underlying transporter. + */ + readonly transporter: Transporter; +}; + +export declare type SearchOptions = { + /** + * Create a new query with an empty search query. + */ + readonly query?: string; + /** + * Allows a search for similar objects, but the query has to be constructed on your end and included alongside an empty query. + * + * The similarQuery should be made from the tags and keywords of the relevant object. + */ + readonly similarQuery?: string; + /** + * Filter hits by facet value. + */ + readonly facetFilters?: string | readonly string[] | ReadonlyArray; + /** + * Create filters for ranking purposes, where records that match the filter are ranked highest. + */ + readonly optionalFilters?: string | readonly string[] | ReadonlyArray; + /** + * Filter on numeric attributes. + */ + readonly numericFilters?: string | readonly string[] | ReadonlyArray; + /** + * Filter hits by tags. tagFilters is a different way of filtering, which relies on the _tags + * attribute. It uses a simpler syntax than filters. You can use it when you want to do + * simple filtering based on tags. + */ + readonly tagFilters?: string | readonly string[] | ReadonlyArray; + /** + * Determines how to calculate the total score for filtering. + */ + readonly sumOrFiltersScores?: boolean; + /** + * Filter the query with numeric, facet and/or tag filters. + */ + readonly filters?: string; + /** + * Specify the page to retrieve. + */ + readonly page?: number; + /** + * Set the number of hits per page. + */ + readonly hitsPerPage?: number; + /** + * Specify the offset of the first hit to return. + */ + readonly offset?: number; + /** + * Set the number of hits to retrieve (used only with offset). + */ + readonly length?: number; + /** + * List of attributes to highlight. + */ + readonly attributesToHighlight?: readonly string[]; + /** + * List of attributes to snippet, with an optional maximum number of words to snippet. + */ + readonly attributesToSnippet?: readonly string[]; + /** + * Gives control over which attributes to retrieve and which not to retrieve. + */ + readonly attributesToRetrieve?: readonly string[]; + /** + * The HTML string to insert before the highlighted parts in all highlight and snippet results. + */ + readonly highlightPreTag?: string; + /** + * The HTML string to insert after the highlighted parts in all highlight and snippet results + */ + readonly highlightPostTag?: string; + /** + * String used as an ellipsis indicator when a snippet is truncated. + */ + readonly snippetEllipsisText?: string; + /** + * Restrict highlighting and snippeting to items that matched the query. + */ + readonly restrictHighlightAndSnippetArrays?: boolean; + /** + * Facets to retrieve. + */ + readonly facets?: readonly string[]; + /** + * Maximum number of facet values to return for each facet during a regular search. + */ + readonly maxValuesPerFacet?: number; + /** + * Force faceting to be applied after de-duplication (via the Distinct setting). + */ + readonly facetingAfterDistinct?: boolean; + /** + * Minimum number of characters a word in the query string must contain to accept matches with 1 typo + */ + readonly minWordSizefor1Typo?: number; + /** + * Minimum number of characters a word in the query string must contain to accept matches with 2 typos. + */ + readonly minWordSizefor2Typos?: number; + /** + * Whether to allow typos on numbers (“numeric tokens”) in the query string. + */ + readonly allowTyposOnNumericTokens?: boolean; + /** + * List of attributes on which you want to disable typo tolerance. + */ + readonly disableTypoToleranceOnAttributes?: readonly string[]; + /** + * Controls if and how query words are interpreted as prefixes. + */ + readonly queryType?: 'prefixLast' | 'prefixAll' | 'prefixNone'; + /** + * Selects a strategy to remove words from the query when it doesn’t match any hits. + */ + readonly removeWordsIfNoResults?: 'none' | 'lastWords' | 'firstWords' | 'allOptional'; + /** + * Enables the advanced query syntax. + */ + readonly advancedSyntax?: boolean; + /** + * AdvancedSyntaxFeatures can be exactPhrase or excludeWords + */ + readonly advancedSyntaxFeatures?: ReadonlyArray<'exactPhrase' | 'excludeWords'>; + /** + * A list of words that should be considered as optional when found in the query. + */ + readonly optionalWords?: string | readonly string[]; + /** + * List of attributes on which you want to disable the exact ranking criterion. + */ + readonly disableExactOnAttributes?: readonly string[]; + /** + * Controls how the exact ranking criterion is computed when the query contains only one word. + */ + readonly exactOnSingleWordQuery?: 'attribute' | 'none' | 'word'; + /** + * List of alternatives that should be considered an exact match by the exact ranking criterion. + */ + readonly alternativesAsExact?: ReadonlyArray<'ignorePlurals' | 'singleWordSynonym' | 'multiWordsSynonym'>; + /** + * Whether rules should be globally enabled. + */ + readonly enableRules?: boolean; + /** + * Enables contextual rules. + */ + readonly ruleContexts?: readonly string[]; + /** + * Enables de-duplication or grouping of results. + */ + readonly distinct?: boolean | number; + /** + * Whether the current query will be taken into account in the Analytics + */ + readonly analytics?: boolean; + /** + * List of tags to apply to the query in the analytics. + */ + readonly analyticsTags?: readonly string[]; + /** + * Whether to take into account an index’s synonyms for a particular search. + */ + readonly synonyms?: boolean; + /** + * Whether to highlight and snippet the original word that matches the synonym or the synonym itself. + */ + readonly replaceSynonymsInHighlight?: boolean; + /** + * Precision of the proximity ranking criterion. + */ + readonly minProximity?: number; + /** + * Choose which fields the response will contain. Applies to search and browse queries. + */ + readonly responseFields?: readonly string[]; + /** + * Maximum number of facet hits to return during a search for facet values. + */ + readonly maxFacetHits?: number; + /** + * Whether to include or exclude a query from the processing-time percentile computation. + */ + readonly percentileComputation?: boolean; + /** + * Enable the Click Analytics feature. + */ + readonly clickAnalytics?: boolean; + /** + * The `personalizationImpact` parameter sets the percentage of the impact that personalization has on ranking records. The + * value must be between 0 and 100 (inclusive). This parameter will not be taken into account if `enablePersonalization` + * is **false**. + */ + readonly personalizationImpact?: number; + /** + * Enable personalization for the query + */ + readonly enablePersonalization?: boolean; + /** + * Restricts a given query to look in only a subset of your searchable attributes. + */ + readonly restrictSearchableAttributes?: readonly string[]; + /** + * Controls how facet values are sorted. + */ + readonly sortFacetValuesBy?: 'count' | 'alpha'; + /** + * Controls whether typo tolerance is enabled and how it is applied. + */ + readonly typoTolerance?: boolean | 'min' | 'strict'; + /** + * Search for entries around a central geolocation, enabling a geo search within a circular area. + */ + readonly aroundLatLng?: string; + /** + * Search for entries around a given location automatically computed from the requester’s IP address. + */ + readonly aroundLatLngViaIP?: boolean; + /** + * Define the maximum radius for a geo search (in meters). + */ + readonly aroundRadius?: number | 'all'; + /** + * Precision of geo search (in meters), to add grouping by geo location to the ranking formula. + */ + readonly aroundPrecision?: number | ReadonlyArray<{ + readonly from: number; + readonly value: number; + }>; + /** + * Minimum radius (in meters) used for a geo search when aroundRadius is not set. + */ + readonly minimumAroundRadius?: number; + /** + * Search inside a rectangular area (in geo coordinates). + */ + readonly insideBoundingBox?: ReadonlyArray | string; + /** + * Search inside a polygon (in geo coordinates). + */ + readonly insidePolygon?: ReadonlyArray; + /** + * Treats singular, plurals, and other forms of declensions as matching terms. + */ + readonly ignorePlurals?: boolean | readonly string[]; + /** + * Removes stop (common) words from the query before executing it. + */ + readonly removeStopWords?: boolean | readonly string[]; + /** + * List of supported languages with their associated language ISO code. + * + * Apply a set of natural language best practices such as ignorePlurals, + * removeStopWords, removeWordsIfNoResults, analyticsTags and ruleContexts. + */ + readonly naturalLanguages?: readonly string[]; + /** + * When true, each hit in the response contains an additional _rankingInfo object. + */ + readonly getRankingInfo?: boolean; + /** + * A user identifier. + * Format: alpha numeric string [a-zA-Z0-9_-] + * Length: between 1 and 64 characters. + */ + readonly userToken?: string; + /** + * Can be to enable or disable A/B tests at query time. + * Engine's default: true + */ + readonly enableABTest?: boolean; + /** + * Enable word segmentation (also called decompounding) at query time for + * compatible languages. For example, this turns the Dutch query + * "spaanplaatbehang" into "spaan plaat behang" to retrieve more relevant + * results. + */ + readonly decompoundQuery?: boolean; + /** + * The relevancy threshold to apply to search in a virtual index [0-100]. A Bigger + * value means fewer, but more relevant results, smaller value means more, but + * less relevant results. + */ + readonly relevancyStrictness?: number; + /** + * Whether this search should use Dynamic Re-Ranking. + * @link https://www.algolia.com/doc/guides/algolia-ai/re-ranking/ + * + * Note: You need to turn on Dynamic Re-Ranking on your index for it to have an effect on + * your search results. You can do this through the Re-Ranking page on the dashboard. + * This parameter is only used to turn off Dynamic Re-Ranking (with false) at search time. + */ + readonly enableReRanking?: boolean; + /** + * When Dynamic Re-Ranking is enabled, only records that match these filters will be impacted by Dynamic Re-Ranking. + */ + readonly reRankingApplyFilter?: string | readonly string[] | ReadonlyArray | null; + /** + * Sets the languages to be used by language-specific settings and functionalities such as ignorePlurals, removeStopWords, and CJK word-detection. + */ + readonly queryLanguages?: readonly string[]; + /** + * Enriches the API’s response with meta-information as to how the query was processed. + */ + readonly explain?: readonly string[]; +}; + +export declare type SearchResponse = { + /** + * The hits returned by the search. + * + * Hits are ordered according to the ranking or sorting of the index being queried. + */ + hits: Array>; + /** + * Index of the current page (zero-based). + */ + page: number; + /** + * Number of hits returned (used only with offset) + */ + length?: number; + /** + * The offset of the first hit to returned. + */ + offset?: number; + /** + * Number of hits matched by the query. + */ + nbHits: number; + /** + * Subset of hits selected when relevancyStrictness is applied. + */ + nbSortedHits?: number; + /** + * Number of pages returned. + * + * Calculation is based on the total number of hits (nbHits) divided by the + * number of hits per page (hitsPerPage), rounded up to the nearest integer. + */ + nbPages: number; + /** + * Maximum number of hits returned per page. + */ + hitsPerPage: number; + /** + * Time the server took to process the request, in milliseconds. This does not include network time. + */ + processingTimeMS: number; + /** + * Time the server took to process the request, in milliseconds. + */ + serverTimeMS?: number; + /** + * Whether the nbHits is exhaustive (true) or approximate (false). + * + * An approximation is done when the query takes more than 50ms to be + * processed (this can happen when using complex filters on millions on records). + */ + exhaustiveNbHits: boolean; + /** + * Whether the facet count is exhaustive (true) or approximate (false). + */ + exhaustiveFacetsCount?: boolean; + /** + * A mapping of each facet name to the corresponding facet counts. + */ + facets?: Record>; + /** + * Statistics for numerical facets. + */ + facets_stats?: Record; + /** + * The query used to search. Accepts every character, and every character entered will be used in the search. + * + * An empty query can be used to fetch all records. + */ + query: string; + /** + * A markup text indicating which parts of the original query have been removed in order to retrieve a non-empty result set. + */ + queryAfterRemoval?: string; + /** + * A url-encoded string of all search parameters. + */ + params: string; + /** + * Unique identifier of the search query, to be sent in Insights methods. This identifier links events back to the search query it represents. + * + * Returned only if clickAnalytics is true. + */ + queryID?: string; + /** + * Used to return warnings about the query. + */ + message?: string; + /** + * The computed geo location. + * + * Format: "lat,lng", where the latitude and longitude are expressed as decimal floating point number. + */ + aroundLatLng?: string; + /** + * The automatically computed radius. + */ + automaticRadius?: string; + /** + * Actual host name of the server that processed the request. + * + * Our DNS supports automatic failover and load balancing, so this may differ from the host name used in the request. + */ + serverUsed?: string; + /** + * Index name used for the query. + */ + index?: string; + /** + * Index name used for the query. In case of AB test, the index targetted isn’t always the index used by the query. + */ + indexUsed?: string; + /** + * If a search encounters an index that is being A/B tested, abTestID reports the ongoing A/B test ID. + */ + abTestID?: number; + /** + * In case of AB test, reports the variant ID used. The variant ID is the position in the array of variants (starting at 1). + */ + abTestVariantID?: number; + /** + * The query string that will be searched, after normalization. + */ + parsedQuery?: string; + /** + * Custom user data. + */ + userData?: any; + /** + * Rules applied to the query. + */ + appliedRules?: Array>; + /** + * The explanation of the decompounding at query time. + */ + explain?: { + /** + * The explain query match. + */ + match: { + /** + * The explain query match alternatives. + */ + alternatives: Array<{ + /** + * The alternative type. + */ + types: string[]; + /** + * The list of alternative words. + */ + words: string[]; + /** + * The number of typos. + */ + typos: number; + /** + * The offset. + */ + offset: number; + /** + * The length. + */ + length: number; + }>; + }; + /** + * Query parameter reporting. Parameters are reported + * as a JSON object with one field per parameter. + */ + params?: Record; + /** + * This parameter is for internal use only. + */ + redirect?: { + index?: RedirectRuleIndexMetadata[]; + }; + }; + /** + * The relevancy threshold applied to search in a virtual index. + */ + appliedRelevancyStrictness?: number; + renderingContent?: Settings['renderingContent']; +}; + +export declare const searchRules: (base: SearchIndex) => (query: string, requestOptions?: (RequestOptions & SearchRulesOptions) | undefined) => Readonly>>; + +export declare type SearchRulesOptions = { + /** + * Full text query. + */ + readonly query?: string; + /** + * When specified, restricts matches to rules with a specific anchoring type. When omitted, all anchoring types may match. + */ + readonly anchoring?: string; + /** + * Restricts matches to contextual rules with a specific context (exact match). + */ + readonly context?: string; + /** + * Requested page (zero-based). + */ + readonly page?: number; + /** + * Maximum number of hits in a page. Minimum is 1, maximum is 1000. + */ + readonly hitsPerPage?: number; + /** + * When specified, restricts matches to rules with a specific enabled status. + * When absent (default), all rules are retrieved, regardless of their enabled status. + */ + readonly enabled?: boolean; +}; + +export declare const searchSynonyms: (base: SearchIndex) => (query: string, requestOptions?: (SearchSynonymsOptions & RequestOptions) | undefined) => Readonly>; + +export declare type SearchSynonymsOptions = { + /** + * The synonym type. + */ + readonly type?: string; + /** + * Page to retrieve. + */ + readonly page?: number; + /** + * Number of hits per page. + */ + readonly hitsPerPage?: number; +}; + +export declare type SearchSynonymsResponse = { + /** + * The list of synonyms. + */ + hits: Synonym[]; + /** + * The number of synonyms on the list. + */ + nbHits: number; +}; + +export declare const searchUserIDs: (base: SearchClient) => (query: string, requestOptions?: (SearchUserIDsOptions & RequestOptions) | undefined) => Readonly>; + +export declare type SearchUserIDsOptions = { + /** + * If specified, only clusters assigned to this cluster can be returned. + * */ + readonly cluster?: string; + /** + * Page to fetch. + */ + readonly page?: number; + /** + * Number of users to return by page. + */ + readonly hitsPerPage?: number; +}; + +export declare type SearchUserIDsResponse = { + /** + * List of userID matching the query. + */ + hits: UserIDResponse[]; + /** + * Current page. + */ + page: number; + /** + * Number of userIDs matching the query. + */ + nbHits: number; + /** + * Number of hits retrieved per page. + */ + hitsPerPage: number; + /** + * Timestamp of the last update of the index. + */ + updatedAt: number; +}; + +export declare type SecuredApiKeyRestrictions = SearchOptions & { + /** + * A Unix timestamp used to define the expiration date of the API key. + */ + readonly validUntil?: number; + /** + * List of index names that can be queried. + */ + readonly restrictIndices?: readonly string[] | string; + /** + * IPv4 network allowed to use the generated key. This is used for more protection against API key leaking and reuse. + */ + readonly restrictSources?: string; + /** + * Specify a user identifier. This is often used with rate limits. + */ + readonly userToken?: string; +}; + +export declare const setDictionarySettings: (base: SearchClient) => (settings: DictionarySettings, requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare const setSettings: (base: SearchIndex) => (settings: Settings, requestOptions?: (RequestOptions & SetSettingsOptions) | undefined) => Readonly>; + +export declare type SetSettingsOptions = { + /** + * If the saved settings should be forward to replicas. + */ + readonly forwardToReplicas?: boolean; +}; + +export declare type SetSettingsResponse = { + /** + * The operation task id. May be used to perform a wait task. + */ + taskID: number; + /** + * When the settings got updated. + */ + updatedAt: number; +}; + +export declare type Settings = { + /** + * The complete list of attributes that will be used for searching. + */ + readonly searchableAttributes?: readonly string[]; + /** + * @deprecated Use `searchableAttributes` instead. + */ + readonly attributesToIndex?: readonly string[]; + /** + * The complete list of attributes that will be used for faceting. + */ + readonly attributesForFaceting?: readonly string[]; + /** + * List of attributes that cannot be retrieved at query time. + */ + readonly unretrievableAttributes?: readonly string[]; + /** + * Gives control over which attributes to retrieve and which not to retrieve. + */ + readonly attributesToRetrieve?: readonly string[]; + /** + * Controls the way results are sorted. + */ + readonly ranking?: readonly string[]; + /** + * Specifies the custom ranking criterion. + */ + readonly customRanking?: readonly string[]; + /** + * Creates replicas, exact copies of an index. + */ + readonly replicas?: readonly string[]; + /** + * @deprecated Use `replicas` instead. + */ + readonly slaves?: readonly string[]; + /** + * The primary parameter is automatically added to a replica's settings when the replica is created and cannot be modified. + * + * Can not be setted. + */ + readonly primary?: string; + /** + * Maximum number of facet values to return for each facet during a regular search. + */ + readonly maxValuesPerFacet?: number; + /** + * Controls how facet values are sorted. + */ + readonly sortFacetValuesBy?: 'count' | 'alpha'; + /** + * List of attributes to highlight. + */ + readonly attributesToHighlight?: readonly string[]; + /** + * List of attributes to snippet, with an optional maximum number of words to snippet. + */ + readonly attributesToSnippet?: readonly string[]; + /** + * The HTML string to insert before the highlighted parts in all highlight and snippet results. + */ + readonly highlightPreTag?: string; + /** + * The HTML string to insert after the highlighted parts in all highlight and snippet results. + */ + readonly highlightPostTag?: string; + /** + * String used as an ellipsis indicator when a snippet is truncated. + */ + readonly snippetEllipsisText?: string; + /** + * Restrict highlighting and snippeting to items that matched the query. + */ + readonly restrictHighlightAndSnippetArrays?: boolean; + /** + * Set the number of hits per page. + */ + readonly hitsPerPage?: number; + /** + * Set the maximum number of hits accessible via pagination. + */ + readonly paginationLimitedTo?: number; + /** + * Minimum number of characters a word in the query string must contain to accept matches with 1 typo. + */ + readonly minWordSizefor1Typo?: number; + /** + * Minimum number of characters a word in the query string must contain to accept matches with 2 typos. + */ + readonly minWordSizefor2Typos?: number; + /** + * Controls whether typo tolerance is enabled and how it is applied. + */ + readonly typoTolerance?: string | boolean; + /** + * hether to allow typos on numbers (“numeric tokens”) in the query string. + */ + readonly allowTyposOnNumericTokens?: boolean; + /** + * List of attributes on which you want to disable typo tolerance. + */ + readonly disableTypoToleranceOnAttributes?: readonly string[]; + /** + * List of words on which you want to disable typo tolerance. + */ + readonly disableTypoToleranceOnWords?: readonly string[]; + /** + * Control which separators are indexed. + */ + readonly separatorsToIndex?: string; + /** + * Treats singular, plurals, and other forms of declensions as matching terms. + */ + readonly ignorePlurals?: readonly string[] | boolean; + /** + * Sets the languages to be used by language-specific settings and functionalities such as ignorePlurals, removeStopWords, and CJK word-detection. + */ + readonly queryLanguages?: readonly string[]; + /** + * A list of language ISO code. + */ + readonly indexLanguages?: readonly string[]; + /** + * Whether rules should be globally enabled. + */ + readonly enableRules?: boolean; + /** + * Controls if and how query words are interpreted as prefixes. + */ + readonly queryType?: 'prefixLast' | 'prefixAll' | 'prefixNone'; + /** + * Selects a strategy to remove words from the query when it doesn’t match any hits. + */ + readonly removeWordsIfNoResults?: 'none' | 'lastWords' | 'firstWords' | 'allOptional'; + /** + * Enables the advanced query syntax. + */ + readonly advancedSyntax?: boolean; + /** + * AdvancedSyntaxFeatures can be exactPhrase or excludeWords + */ + readonly advancedSyntaxFeatures?: ReadonlyArray<'exactPhrase' | 'excludeWords'>; + /** + * A list of words that should be considered as optional when found in the query. + */ + readonly optionalWords?: readonly string[]; + /** + * List of attributes on which you want to disable prefix matching. + */ + readonly disablePrefixOnAttributes?: readonly string[]; + /** + * List of attributes on which you want to disable the exact ranking criterion. + */ + readonly disableExactOnAttributes?: readonly string[]; + /** + * Controls how the exact ranking criterion is computed when the query contains only one word. + */ + readonly exactOnSingleWordQuery?: 'attribute' | 'none' | 'word'; + /** + * List of alternatives that should be considered an exact match by the exact ranking criterion. + */ + readonly alternativesAsExact?: ReadonlyArray<'ignorePlurals' | 'singleWordSynonym' | 'multiWordsSynonym'>; + /** + * Removes stop (common) words from the query before executing it. + */ + readonly removeStopWords?: boolean | readonly string[]; + /** + * List of numeric attributes that can be used as numerical filters. + */ + readonly numericAttributesForFiltering?: readonly string[]; + /** + * Enables compression of large integer arrays. + */ + readonly allowCompressionOfIntegerArray?: boolean; + /** + * Name of the de-duplication attribute to be used with the distinct feature. + */ + readonly attributeForDistinct?: string; + /** + * Enables de-duplication or grouping of results. + */ + readonly distinct?: boolean | number; + /** + * Whether to highlight and snippet the original word that matches the synonym or the synonym itself. + */ + readonly replaceSynonymsInHighlight?: boolean; + /** + * Allows proximity to impact which searchable attribute is matched in the attribute ranking stage. + */ + readonly attributeCriteriaComputedByMinProximity?: boolean; + /** + * Precision of the proximity ranking criterion. + */ + readonly minProximity?: number; + /** + * Choose which fields the response will contain. Applies to search and browse queries. + */ + readonly responseFields?: readonly string[]; + /** + * Maximum number of facet hits to return during a search for facet values. + */ + readonly maxFacetHits?: number; + /** + * List of attributes on which to do a decomposition of camel case words. + */ + readonly camelCaseAttributes?: readonly string[]; + /** + * Specify on which attributes in your index Algolia should apply word-splitting (“decompounding”) + */ + readonly decompoundedAttributes?: Readonly>; + /** + * Characters that should not be automatically normalized by the search engine. + */ + readonly keepDiacriticsOnCharacters?: string; + /** + * Overrides Algolia's default normalization. + */ + readonly customNormalization?: Readonly>>>; + /** + * Enable personalization for queries by default + */ + readonly enablePersonalization?: boolean; + /** + * Custom userData that could be added to the Settings. + */ + readonly userData?: any; + /** + * Enable word segmentation (also called decompounding) at query time for + * compatible languages. For example, this turns the Dutch query + * "spaanplaatbehang" into "spaan plaat behang" to retrieve more relevant + * results. + */ + readonly decompoundQuery?: boolean; + /** + * Specify on which attributes in your index Algolia should apply Japanese + * transliteration to make words indexed in Katakana or Kanji searchable in Hiragana. + */ + readonly attributesToTransliterate?: readonly string[]; + /** + * The relevancy threshold to apply to search in a virtual index [0-100]. A Bigger + * value means fewer, but more relevant results, smaller value means more, but + * less relevant results. + */ + readonly relevancyStrictness?: number; + /** + * The search mode that the index will use to query for results. + */ + readonly mode?: 'neuralSearch' | 'keywordSearch'; + /** + * The settings relevant for configuration of the semantic search engine. + * These settings are only used when the mode is set to 'neuralSearch'. + */ + readonly semanticSearch?: { + /** + * When null, the current index / replica group will be used as the event source. + */ + readonly eventSources?: readonly string[] | null; + }; + /** + * Content defining how the search interface should be rendered. + * This is set via the settings for a default value and can be overridden via rules + */ + readonly renderingContent?: { + /** + * defining how facets should be ordered + */ + readonly facetOrdering?: { + /** + * the ordering of facets (widgets) + */ + readonly facets?: { + /** + * pinned order of facet lists + */ + readonly order?: readonly string[]; + }; + /** + * the ordering of facet values, within an individual list + */ + readonly values?: { + readonly [facet: string]: { + /** + * Hide facet values + */ + readonly hide?: readonly string[]; + /** + * pinned order of facet values + */ + readonly order?: readonly string[]; + /** + * How to display the remaining items. + * - facet count (descending) + * - alphabetical (ascending) + * - hidden (show only pinned values) + */ + readonly sortRemainingBy?: 'count' | 'alpha' | 'hidden'; + }; + }; + }; + /** + * Defining UI widget configuration + */ + readonly widgets?: { + /** + * Configuration for banners + */ + readonly banners?: ReadonlyArray<{ + /** + * Configuration for the banner image + */ + readonly image: { + /** + * Set of possible URLs of the banner image + */ + readonly urls: ReadonlyArray<{ + /** + * URL of the banner image + */ + readonly url: string; + }>; + /** + * Alt text of the banner image + */ + readonly title?: string; + }; + /** + * Configuration for the banner click navigation + */ + readonly link?: { + /** + * URL to navigate to when the banner is clicked + */ + readonly url?: string; + /** + * Target of the navigation + * - `_blank` opens the URL in a new tab + * - `_self` opens the URL in the same tab + */ + readonly target?: '_blank' | '_self'; + }; + }>; + }; + }; + /** + * Whether this index should use Dynamic Re-Ranking. + * @link https://www.algolia.com/doc/guides/algolia-ai/re-ranking/ + * + * Note: You need to turn on Dynamic Re-Ranking on your index for it to have an effect on + * your search results. You can do this through the Re-Ranking page on the dashboard. + */ + readonly enableReRanking?: boolean; + /** + * When Dynamic Re-Ranking is enabled, only records that match these filters will be impacted by Dynamic Re-Ranking. + */ + readonly reRankingApplyFilter?: string | readonly string[] | ReadonlyArray | null; +}; + +declare type SharedMultipleQueriesQuery = { + /** + * The type of query to perform. + * + * @defaultValue "default" + */ + readonly type?: 'default' | 'facet'; + /** + * The index name. + */ + readonly indexName: string; + /** + * The search options. + */ + readonly params?: SearchOptions; + /** + * The query associated with the request. + */ + readonly query?: string; +}; + +declare type SnippetMatch = { + readonly value: string; + readonly matchLevel: 'none' | 'partial' | 'full'; +}; + +export declare type SnippetResult = THit extends string | number ? SnippetMatch : { + [KAttribute in keyof THit]: SnippetResult; +}; + +export declare const StrategyEnum: Readonly>; + +export declare type StrategyType = 'none' | 'stopIfEnoughMatches'; + +export declare type Synonym = { + /** + * Synonym object ID. + */ + readonly objectID: string; + /** + * There are 4 synonym types. The parameter can be one of the following value. + */ + readonly type: SynonymType; + /** + * A list of synonyms. + */ + readonly synonyms?: readonly string[]; + /** + * Defines the synonym. A word or expression, used as the basis for the array of synonyms. + */ + readonly input?: string; + /** + * A single word, used as the basis for the below array of corrections. + */ + readonly word?: string; + /** + * An list of corrections of the word. + */ + readonly corrections?: readonly string[]; + /** + * A single word, used as the basis for the below list of replacements. + */ + readonly placeholder?: string; + /** + * An list of replacements of the placeholder. + */ + readonly replacements?: readonly string[]; +}; + +export declare const SynonymEnum: Readonly>; + +export declare type SynonymType = 'synonym' | 'oneWaySynonym' | 'altCorrection1' | 'altCorrection2' | 'placeholder'; + +export declare type TaskStatusResponse = { + /** + * The operation status. When the value is `published` the + * operation is completed. + */ + status: string; + /** + * If the operation is pending. + */ + pendingTask: boolean; +}; + +export declare type TimeRange = { + /** + * DateTime with UTC offset for Serialization/Deserialization in unix timespan. + */ + readonly from: number; + /** + * DateTime with UTC offset for Serialization/Deserialization in unix timespan. + */ + readonly until: number; +}; + +export declare const updateApiKey: (base: SearchClient) => (apiKey: string, requestOptions?: (UpdateApiKeyOptions & Pick) | undefined) => Readonly>; + +export declare type UpdateApiKeyOptions = { + /** + * List of permissions the key contains. + */ + readonly acl?: readonly ApiKeyACLType[]; + /** + * A Unix timestamp used to define the expiration date of the API key. + */ + readonly validity?: number; + /** + * Specify the maximum number of hits this API key can retrieve in one call. + * This parameter can be used to protect you from attempts at retrieving your entire index contents by massively querying the index. + */ + readonly maxHitsPerQuery?: number; + /** + * Specify the maximum number of API calls allowed from an IP address per hour. Each time an API call is performed with this key, a check is performed. + */ + readonly maxQueriesPerIPPerHour?: number; + /** + * Specify the list of targeted indices. You can target all indices starting with a prefix or ending with a suffix using the ‘*’ character. + */ + readonly indexes?: readonly string[]; + /** + * Specify the list of referers. You can target all referers starting with a prefix, ending with a suffix using the ‘*’ character. + */ + readonly referers?: readonly string[]; + /** + * Specify the list of query parameters. You can force the query parameters for a query using the url string format. + */ + readonly queryParameters?: string; + /** + * Specify a description of the API key. Used for informative purposes only. It has impact on the functionality of the API key. + */ + readonly description?: string; +}; + +export declare type UpdateApiKeyResponse = { + /** + * The api key. + */ + key: string; + /** + * Date of update + */ + updatedAt: string; +}; + +export declare type UserIDResponse = { + /** + * userID of the user. + */ + userID: string; + /** + * Cluster on which the user is assigned + */ + clusterName: string; + /** + * Number of records belonging to the user. + */ + nbRecords: number; + /** + * Data size used by the user. + */ + dataSize: number; +}; + +export declare const waitAppTask: (base: SearchClient) => (taskID: number, requestOptions?: RequestOptions | undefined) => Readonly>; + +export declare const waitTask: (base: SearchIndex) => (taskID: number, requestOptions?: RequestOptions | undefined) => Readonly>; + +export { } diff --git a/scripts/node_modules/@algolia/client-search/dist/client-search.esm.js b/scripts/node_modules/@algolia/client-search/dist/client-search.esm.js new file mode 100644 index 000000000..a5daf5819 --- /dev/null +++ b/scripts/node_modules/@algolia/client-search/dist/client-search.esm.js @@ -0,0 +1,1287 @@ +import { createAuth, AuthMode, shuffle, addMethods, createWaitablePromise, createRetryablePromise, encode } from '@algolia/client-common'; +import { createTransporter, CallEnum, createMappedRequestOptions, serializeQueryParameters } from '@algolia/transporter'; +import { MethodEnum } from '@algolia/requester-common'; +import { createHmac } from 'crypto'; + +function createBrowsablePromise(options) { + const browse = (data) => { + return options.request(data).then(response => { + /** + * First we send to the developer the + * batch retrieved from the API. + */ + if (options.batch !== undefined) { + options.batch(response.hits); + } + /** + * Then, we ask to the browse concrete implementation + * if we should stop browsing. As example, the `browseObjects` + * method will stop if the cursor is not present on the response. + */ + if (options.shouldStop(response)) { + return undefined; + } + /** + * Finally, if the response contains a cursor, we browse to the next + * batch using that same cursor. Otherwise, we just use the traditional + * browsing using the page element. + */ + if (response.cursor) { + return browse({ + cursor: response.cursor, + }); + } + return browse({ + page: (data.page || 0) + 1, + }); + }); + }; + return browse({}); +} + +const createSearchClient = options => { + const appId = options.appId; + const auth = createAuth(options.authMode !== undefined ? options.authMode : AuthMode.WithinHeaders, appId, options.apiKey); + const transporter = createTransporter({ + hosts: [ + { url: `${appId}-dsn.algolia.net`, accept: CallEnum.Read }, + { url: `${appId}.algolia.net`, accept: CallEnum.Write }, + ].concat(shuffle([ + { url: `${appId}-1.algolianet.com` }, + { url: `${appId}-2.algolianet.com` }, + { url: `${appId}-3.algolianet.com` }, + ])), + ...options, + headers: { + ...auth.headers(), + ...{ 'content-type': 'application/x-www-form-urlencoded' }, + ...options.headers, + }, + queryParameters: { + ...auth.queryParameters(), + ...options.queryParameters, + }, + }); + const base = { + transporter, + appId, + addAlgoliaAgent(segment, version) { + transporter.userAgent.add({ segment, version }); + }, + clearCache() { + return Promise.all([ + transporter.requestsCache.clear(), + transporter.responsesCache.clear(), + ]).then(() => undefined); + }, + }; + return addMethods(base, options.methods); +}; + +function createMissingObjectIDError() { + return { + name: 'MissingObjectIDError', + message: 'All objects must have an unique objectID ' + + '(like a primary key) to be valid. ' + + 'Algolia is also able to generate objectIDs ' + + "automatically but *it's not recommended*. " + + "To do it, use the `{'autoGenerateObjectIDIfNotExist': true}` option.", + }; +} + +function createObjectNotFoundError() { + return { + name: 'ObjectNotFoundError', + message: 'Object not found.', + }; +} + +function createValidUntilNotFoundError() { + return { + name: 'ValidUntilNotFoundError', + message: 'ValidUntil not found in given secured api key.', + }; +} + +const addApiKey = (base) => { + return (acl, requestOptions) => { + const { queryParameters, ...options } = requestOptions || {}; + const data = { + acl, + ...(queryParameters !== undefined ? { queryParameters } : {}), + }; + const wait = (response, waitRequestOptions) => { + return createRetryablePromise(retry => { + return getApiKey(base)(response.key, waitRequestOptions).catch((apiError) => { + if (apiError.status !== 404) { + throw apiError; + } + return retry(); + }); + }); + }; + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Post, + path: '1/keys', + data, + }, options), wait); + }; +}; + +const assignUserID = (base) => { + return (userID, clusterName, requestOptions) => { + const mappedRequestOptions = createMappedRequestOptions(requestOptions); + // eslint-disable-next-line functional/immutable-data + mappedRequestOptions.queryParameters['X-Algolia-User-ID'] = userID; + return base.transporter.write({ + method: MethodEnum.Post, + path: '1/clusters/mapping', + data: { cluster: clusterName }, + }, mappedRequestOptions); + }; +}; + +const assignUserIDs = (base) => { + return (userIDs, clusterName, requestOptions) => { + return base.transporter.write({ + method: MethodEnum.Post, + path: '1/clusters/mapping/batch', + data: { + users: userIDs, + cluster: clusterName, + }, + }, requestOptions); + }; +}; + +const clearDictionaryEntries = (base) => { + return (dictionary, requestOptions) => { + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Post, + path: encode('/1/dictionaries/%s/batch', dictionary), + data: { + clearExistingDictionaryEntries: true, + requests: { action: 'addEntry', body: [] }, + }, + }, requestOptions), (response, waitRequestOptions) => waitAppTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const copyIndex = (base) => { + return (from, to, requestOptions) => { + const wait = (response, waitRequestOptions) => { + return initIndex(base)(from, { + methods: { waitTask }, + }).waitTask(response.taskID, waitRequestOptions); + }; + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Post, + path: encode('1/indexes/%s/operation', from), + data: { + operation: 'copy', + destination: to, + }, + }, requestOptions), wait); + }; +}; + +const copyRules = (base) => { + return (from, to, requestOptions) => { + return copyIndex(base)(from, to, { + ...requestOptions, + scope: [ScopeEnum.Rules], + }); + }; +}; + +const copySettings = (base) => { + return (from, to, requestOptions) => { + return copyIndex(base)(from, to, { + ...requestOptions, + scope: [ScopeEnum.Settings], + }); + }; +}; + +const copySynonyms = (base) => { + return (from, to, requestOptions) => { + return copyIndex(base)(from, to, { + ...requestOptions, + scope: [ScopeEnum.Synonyms], + }); + }; +}; + +const customRequest = (base) => { + return (request, requestOptions) => { + if (request.method === MethodEnum.Get) { + return base.transporter.read(request, requestOptions); + } + return base.transporter.write(request, requestOptions); + }; +}; + +const deleteApiKey = (base) => { + return (apiKey, requestOptions) => { + const wait = (_, waitRequestOptions) => { + return createRetryablePromise(retry => { + return getApiKey(base)(apiKey, waitRequestOptions) + .then(retry) + .catch((apiError) => { + if (apiError.status !== 404) { + throw apiError; + } + }); + }); + }; + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Delete, + path: encode('1/keys/%s', apiKey), + }, requestOptions), wait); + }; +}; + +const deleteDictionaryEntries = (base) => { + return (dictionary, objectIDs, requestOptions) => { + const requests = objectIDs.map(objectID => ({ + action: 'deleteEntry', + body: { objectID }, + })); + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Post, + path: encode('/1/dictionaries/%s/batch', dictionary), + data: { clearExistingDictionaryEntries: false, requests }, + }, requestOptions), (response, waitRequestOptions) => waitAppTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const generateSecuredApiKey = () => { + return (parentApiKey, restrictions) => { + const queryParameters = serializeQueryParameters(restrictions); + const securedKey = createHmac('sha256', parentApiKey) + .update(queryParameters) + .digest('hex'); + return Buffer.from(securedKey + queryParameters).toString('base64'); + }; +}; + +const getApiKey = (base) => { + return (apiKey, requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Get, + path: encode('1/keys/%s', apiKey), + }, requestOptions); + }; +}; + +const getAppTask = (base) => { + return (taskID, requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Get, + path: encode('1/task/%s', taskID.toString()), + }, requestOptions); + }; +}; + +const getDictionarySettings = (base) => { + return (requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Get, + path: '/1/dictionaries/*/settings', + }, requestOptions); + }; +}; + +const getLogs = (base) => { + return (requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Get, + path: '1/logs', + }, requestOptions); + }; +}; + +const getSecuredApiKeyRemainingValidity = () => { + return (securedApiKey) => { + const decodedString = Buffer.from(securedApiKey, 'base64').toString('ascii'); + const regex = /validUntil=(\d+)/; + const match = decodedString.match(regex); + if (match === null) { + throw createValidUntilNotFoundError(); + } + return parseInt(match[1], 10) - Math.round(new Date().getTime() / 1000); + }; +}; + +const getTopUserIDs = (base) => { + return (requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Get, + path: '1/clusters/mapping/top', + }, requestOptions); + }; +}; + +const getUserID = (base) => { + return (userID, requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Get, + path: encode('1/clusters/mapping/%s', userID), + }, requestOptions); + }; +}; + +const hasPendingMappings = (base) => { + return (requestOptions) => { + const { retrieveMappings, ...options } = requestOptions || {}; + if (retrieveMappings === true) { + // eslint-disable-next-line functional/immutable-data + options.getClusters = true; + } + return base.transporter.read({ + method: MethodEnum.Get, + path: '1/clusters/mapping/pending', + }, options); + }; +}; + +const initIndex = (base) => { + return (indexName, options = {}) => { + const searchIndex = { + transporter: base.transporter, + appId: base.appId, + indexName, + }; + return addMethods(searchIndex, options.methods); + }; +}; + +const listApiKeys = (base) => { + return (requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Get, + path: '1/keys', + }, requestOptions); + }; +}; + +const listClusters = (base) => { + return (requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Get, + path: '1/clusters', + }, requestOptions); + }; +}; + +const listIndices = (base) => { + return (requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Get, + path: '1/indexes', + }, requestOptions); + }; +}; + +const listUserIDs = (base) => { + return (requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Get, + path: '1/clusters/mapping', + }, requestOptions); + }; +}; + +const moveIndex = (base) => { + return (from, to, requestOptions) => { + const wait = (response, waitRequestOptions) => { + return initIndex(base)(from, { + methods: { waitTask }, + }).waitTask(response.taskID, waitRequestOptions); + }; + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Post, + path: encode('1/indexes/%s/operation', from), + data: { + operation: 'move', + destination: to, + }, + }, requestOptions), wait); + }; +}; + +const multipleBatch = (base) => { + return (requests, requestOptions) => { + const wait = (response, waitRequestOptions) => { + return Promise.all(Object.keys(response.taskID).map(indexName => { + return initIndex(base)(indexName, { + methods: { waitTask }, + }).waitTask(response.taskID[indexName], waitRequestOptions); + })); + }; + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Post, + path: '1/indexes/*/batch', + data: { + requests, + }, + }, requestOptions), wait); + }; +}; + +const multipleGetObjects = (base) => { + return (requests, requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Post, + path: '1/indexes/*/objects', + data: { + requests, + }, + }, requestOptions); + }; +}; + +const multipleQueries = (base) => { + return (queries, requestOptions) => { + const requests = queries.map(query => { + return { + ...query, + params: serializeQueryParameters(query.params || {}), + }; + }); + return base.transporter.read({ + method: MethodEnum.Post, + path: '1/indexes/*/queries', + data: { + requests, + }, + cacheable: true, + }, requestOptions); + }; +}; + +const multipleSearchForFacetValues = (base) => { + return (queries, requestOptions) => { + return Promise.all(queries.map(query => { + const { facetName, facetQuery, ...params } = query.params; + return initIndex(base)(query.indexName, { + methods: { searchForFacetValues }, + }).searchForFacetValues(facetName, facetQuery, { + ...requestOptions, + ...params, + }); + })); + }; +}; + +const removeUserID = (base) => { + return (userID, requestOptions) => { + const mappedRequestOptions = createMappedRequestOptions(requestOptions); + // eslint-disable-next-line functional/immutable-data + mappedRequestOptions.queryParameters['X-Algolia-User-ID'] = userID; + return base.transporter.write({ + method: MethodEnum.Delete, + path: '1/clusters/mapping', + }, mappedRequestOptions); + }; +}; + +const replaceDictionaryEntries = (base) => { + return (dictionary, entries, requestOptions) => { + const requests = entries.map(entry => ({ + action: 'addEntry', + body: entry, + })); + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Post, + path: encode('/1/dictionaries/%s/batch', dictionary), + data: { clearExistingDictionaryEntries: true, requests }, + }, requestOptions), (response, waitRequestOptions) => waitAppTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const restoreApiKey = (base) => { + return (apiKey, requestOptions) => { + const wait = (_, waitRequestOptions) => { + return createRetryablePromise(retry => { + return getApiKey(base)(apiKey, waitRequestOptions).catch((apiError) => { + if (apiError.status !== 404) { + throw apiError; + } + return retry(); + }); + }); + }; + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Post, + path: encode('1/keys/%s/restore', apiKey), + }, requestOptions), wait); + }; +}; + +const saveDictionaryEntries = (base) => { + return (dictionary, entries, requestOptions) => { + const requests = entries.map(entry => ({ + action: 'addEntry', + body: entry, + })); + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Post, + path: encode('/1/dictionaries/%s/batch', dictionary), + data: { clearExistingDictionaryEntries: false, requests }, + }, requestOptions), (response, waitRequestOptions) => waitAppTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const searchDictionaryEntries = (base) => { + return (dictionary, query, requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Post, + path: encode('/1/dictionaries/%s/search', dictionary), + data: { + query, + }, + cacheable: true, + }, requestOptions); + }; +}; + +const searchUserIDs = (base) => { + return (query, requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Post, + path: '1/clusters/mapping/search', + data: { + query, + }, + }, requestOptions); + }; +}; + +const setDictionarySettings = (base) => { + return (settings, requestOptions) => { + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Put, + path: '/1/dictionaries/*/settings', + data: settings, + }, requestOptions), (response, waitRequestOptions) => waitAppTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const updateApiKey = (base) => { + return (apiKey, requestOptions) => { + const updatedFields = Object.assign({}, requestOptions); + const { queryParameters, ...options } = requestOptions || {}; + const data = queryParameters ? { queryParameters } : {}; + const apiKeyFields = [ + 'acl', + 'indexes', + 'referers', + 'restrictSources', + 'queryParameters', + 'description', + 'maxQueriesPerIPPerHour', + 'maxHitsPerQuery', + ]; + // Check that all the fields retrieved through getApiKey are the same as the ones we wanted to update + const hasChanged = (getApiKeyResponse) => { + return Object.keys(updatedFields) + .filter((updatedField) => apiKeyFields.indexOf(updatedField) !== -1) + .every(updatedField => { + // If the field is an array, we need to check that they are the same length and that all the values are the same + if (Array.isArray(getApiKeyResponse[updatedField]) && + Array.isArray(updatedFields[updatedField])) { + const getApiKeyResponseArray = getApiKeyResponse[updatedField]; + return (getApiKeyResponseArray.length === updatedFields[updatedField].length && + getApiKeyResponseArray.every((value, index) => value === updatedFields[updatedField][index])); + } + else { + return getApiKeyResponse[updatedField] === updatedFields[updatedField]; + } + }); + }; + const wait = (_, waitRequestOptions) => createRetryablePromise(retry => { + return getApiKey(base)(apiKey, waitRequestOptions).then(getApiKeyResponse => { + return hasChanged(getApiKeyResponse) ? Promise.resolve() : retry(); + }); + }); + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Put, + path: encode('1/keys/%s', apiKey), + data, + }, options), wait); + }; +}; + +const waitAppTask = (base) => { + return (taskID, requestOptions) => { + return createRetryablePromise(retry => { + return getAppTask(base)(taskID, requestOptions).then(response => { + return response.status !== 'published' ? retry() : undefined; + }); + }); + }; +}; + +const batch = (base) => { + return (requests, requestOptions) => { + const wait = (response, waitRequestOptions) => { + return waitTask(base)(response.taskID, waitRequestOptions); + }; + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Post, + path: encode('1/indexes/%s/batch', base.indexName), + data: { + requests, + }, + }, requestOptions), wait); + }; +}; + +const browseObjects = (base) => { + return (requestOptions) => { + return createBrowsablePromise({ + shouldStop: response => response.cursor === undefined, + ...requestOptions, + request: (data) => base.transporter.read({ + method: MethodEnum.Post, + path: encode('1/indexes/%s/browse', base.indexName), + data, + }, requestOptions), + }); + }; +}; + +const browseRules = (base) => { + return (requestOptions) => { + const options = { + hitsPerPage: 1000, + ...requestOptions, + }; + return createBrowsablePromise({ + shouldStop: response => response.hits.length < options.hitsPerPage, + ...options, + request(data) { + return searchRules(base)('', { ...options, ...data }).then((response) => { + return { + ...response, + hits: response.hits.map(rule => { + // eslint-disable-next-line functional/immutable-data,no-param-reassign + delete rule._highlightResult; + return rule; + }), + }; + }); + }, + }); + }; +}; + +const browseSynonyms = (base) => { + return (requestOptions) => { + const options = { + hitsPerPage: 1000, + ...requestOptions, + }; + return createBrowsablePromise({ + shouldStop: response => response.hits.length < options.hitsPerPage, + ...options, + request(data) { + return searchSynonyms(base)('', { ...options, ...data }).then((response) => { + return { + ...response, + hits: response.hits.map(synonym => { + // eslint-disable-next-line functional/immutable-data,no-param-reassign + delete synonym._highlightResult; + return synonym; + }), + }; + }); + }, + }); + }; +}; + +const chunkedBatch = (base) => { + return (bodies, action, requestOptions) => { + const { batchSize, ...options } = requestOptions || {}; + const response = { + taskIDs: [], + objectIDs: [], + }; + const forEachBatch = (lastIndex = 0) => { + // eslint-disable-next-line functional/prefer-readonly-type + const bodiesChunk = []; + // eslint-disable-next-line functional/no-let + let index; + /* eslint-disable-next-line functional/no-loop-statement */ + for (index = lastIndex; index < bodies.length; index++) { + // eslint-disable-next-line functional/immutable-data + bodiesChunk.push(bodies[index]); + if (bodiesChunk.length === (batchSize || 1000)) { + break; + } + } + if (bodiesChunk.length === 0) { + return Promise.resolve(response); + } + return batch(base)(bodiesChunk.map(body => { + return { + action, + body, + }; + }), options).then(res => { + response.objectIDs = response.objectIDs.concat(res.objectIDs); // eslint-disable-line functional/immutable-data + response.taskIDs.push(res.taskID); // eslint-disable-line functional/immutable-data + index++; + return forEachBatch(index); + }); + }; + return createWaitablePromise(forEachBatch(), (chunkedBatchResponse, waitRequestOptions) => { + return Promise.all(chunkedBatchResponse.taskIDs.map(taskID => { + return waitTask(base)(taskID, waitRequestOptions); + })); + }); + }; +}; + +const clearObjects = (base) => { + return (requestOptions) => { + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Post, + path: encode('1/indexes/%s/clear', base.indexName), + }, requestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const clearRules = (base) => { + return (requestOptions) => { + const { forwardToReplicas, ...options } = requestOptions || {}; + const mappedRequestOptions = createMappedRequestOptions(options); + if (forwardToReplicas) { + mappedRequestOptions.queryParameters.forwardToReplicas = 1; // eslint-disable-line functional/immutable-data + } + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Post, + path: encode('1/indexes/%s/rules/clear', base.indexName), + }, mappedRequestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const clearSynonyms = (base) => { + return (requestOptions) => { + const { forwardToReplicas, ...options } = requestOptions || {}; + const mappedRequestOptions = createMappedRequestOptions(options); + if (forwardToReplicas) { + mappedRequestOptions.queryParameters.forwardToReplicas = 1; // eslint-disable-line functional/immutable-data + } + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Post, + path: encode('1/indexes/%s/synonyms/clear', base.indexName), + }, mappedRequestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const deleteBy = (base) => { + return (filters, requestOptions) => { + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Post, + path: encode('1/indexes/%s/deleteByQuery', base.indexName), + data: filters, + }, requestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const deleteIndex = (base) => { + return (requestOptions) => { + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Delete, + path: encode('1/indexes/%s', base.indexName), + }, requestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const deleteObject = (base) => { + return (objectID, requestOptions) => { + return createWaitablePromise(deleteObjects(base)([objectID], requestOptions).then(response => { + return { taskID: response.taskIDs[0] }; + }), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const deleteObjects = (base) => { + return (objectIDs, requestOptions) => { + const objects = objectIDs.map(objectID => { + return { objectID }; + }); + return chunkedBatch(base)(objects, BatchActionEnum.DeleteObject, requestOptions); + }; +}; + +const deleteRule = (base) => { + return (objectID, requestOptions) => { + const { forwardToReplicas, ...options } = requestOptions || {}; + const mappedRequestOptions = createMappedRequestOptions(options); + if (forwardToReplicas) { + mappedRequestOptions.queryParameters.forwardToReplicas = 1; // eslint-disable-line functional/immutable-data + } + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Delete, + path: encode('1/indexes/%s/rules/%s', base.indexName, objectID), + }, mappedRequestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const deleteSynonym = (base) => { + return (objectID, requestOptions) => { + const { forwardToReplicas, ...options } = requestOptions || {}; + const mappedRequestOptions = createMappedRequestOptions(options); + if (forwardToReplicas) { + mappedRequestOptions.queryParameters.forwardToReplicas = 1; // eslint-disable-line functional/immutable-data + } + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Delete, + path: encode('1/indexes/%s/synonyms/%s', base.indexName, objectID), + }, mappedRequestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const exists = (base) => { + return (requestOptions) => { + return getSettings(base)(requestOptions) + .then(() => true) + .catch(error => { + if (error.status !== 404) { + throw error; + } + return false; + }); + }; +}; + +const findAnswers = (base) => { + return (query, queryLanguages, requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Post, + path: encode('1/answers/%s/prediction', base.indexName), + data: { + query, + queryLanguages, + }, + cacheable: true, + }, requestOptions); + }; +}; + +const findObject = (base) => { + return (callback, requestOptions) => { + const { query, paginate, ...options } = requestOptions || {}; + // eslint-disable-next-line functional/no-let + let page = 0; + const forEachPage = () => { + return search(base)(query || '', { ...options, page }).then(result => { + // eslint-disable-next-line functional/no-loop-statement + for (const [position, hit] of Object.entries(result.hits)) { + // eslint-disable-next-line promise/no-callback-in-promise + if (callback(hit)) { + return { + object: hit, + position: parseInt(position, 10), + page, + }; + } + } + page++; + // paginate if option was set and has next page + if (paginate === false || page >= result.nbPages) { + throw createObjectNotFoundError(); + } + return forEachPage(); + }); + }; + return forEachPage(); + }; +}; + +const getObject = (base) => { + return (objectID, requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Get, + path: encode('1/indexes/%s/%s', base.indexName, objectID), + }, requestOptions); + }; +}; + +const getObjectPosition = () => { + return (searchResponse, objectID) => { + // eslint-disable-next-line functional/no-loop-statement + for (const [position, hit] of Object.entries(searchResponse.hits)) { + if (hit.objectID === objectID) { + return parseInt(position, 10); + } + } + return -1; + }; +}; + +const getObjects = (base) => { + return (objectIDs, requestOptions) => { + const { attributesToRetrieve, ...options } = requestOptions || {}; + const requests = objectIDs.map(objectID => { + return { + indexName: base.indexName, + objectID, + ...(attributesToRetrieve ? { attributesToRetrieve } : {}), + }; + }); + return base.transporter.read({ + method: MethodEnum.Post, + path: '1/indexes/*/objects', + data: { + requests, + }, + }, options); + }; +}; + +const getRule = (base) => { + return (objectID, requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Get, + path: encode('1/indexes/%s/rules/%s', base.indexName, objectID), + }, requestOptions); + }; +}; + +const getSettings = (base) => { + return (requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Get, + path: encode('1/indexes/%s/settings', base.indexName), + data: { + getVersion: 2, + }, + }, requestOptions); + }; +}; + +const getSynonym = (base) => { + return (objectID, requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Get, + path: encode(`1/indexes/%s/synonyms/%s`, base.indexName, objectID), + }, requestOptions); + }; +}; + +const getTask = (base) => { + return (taskID, requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Get, + path: encode('1/indexes/%s/task/%s', base.indexName, taskID.toString()), + }, requestOptions); + }; +}; + +const partialUpdateObject = (base) => { + return (object, requestOptions) => { + return createWaitablePromise(partialUpdateObjects(base)([object], requestOptions).then(response => { + return { + objectID: response.objectIDs[0], + taskID: response.taskIDs[0], + }; + }), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const partialUpdateObjects = (base) => { + return (objects, requestOptions) => { + const { createIfNotExists, ...options } = requestOptions || {}; + const action = createIfNotExists + ? BatchActionEnum.PartialUpdateObject + : BatchActionEnum.PartialUpdateObjectNoCreate; + return chunkedBatch(base)(objects, action, options); + }; +}; + +const replaceAllObjects = (base) => { + return (objects, requestOptions) => { + const { safe, autoGenerateObjectIDIfNotExist, batchSize, ...options } = requestOptions || {}; + const operation = (from, to, type, operationRequestOptions) => { + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Post, + path: encode('1/indexes/%s/operation', from), + data: { + operation: type, + destination: to, + }, + }, operationRequestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; + const randomSuffix = Math.random() + .toString(36) + .substring(7); + const temporaryIndexName = `${base.indexName}_tmp_${randomSuffix}`; + const saveObjectsInTemporary = saveObjects({ + appId: base.appId, + transporter: base.transporter, + indexName: temporaryIndexName, + }); + // @ts-ignore + // eslint-disable-next-line prefer-const, functional/no-let, functional/prefer-readonly-type + let responses = []; + const copyWaitablePromise = operation(base.indexName, temporaryIndexName, 'copy', { + ...options, + scope: ['settings', 'synonyms', 'rules'], + }); + // eslint-disable-next-line functional/immutable-data + responses.push(copyWaitablePromise); + const result = (safe + ? copyWaitablePromise.wait(options) + : copyWaitablePromise) + .then(() => { + const saveObjectsWaitablePromise = saveObjectsInTemporary(objects, { + ...options, + autoGenerateObjectIDIfNotExist, + batchSize, + }); + // eslint-disable-next-line functional/immutable-data + responses.push(saveObjectsWaitablePromise); + return safe ? saveObjectsWaitablePromise.wait(options) : saveObjectsWaitablePromise; + }) + .then(() => { + const moveWaitablePromise = operation(temporaryIndexName, base.indexName, 'move', options); + // eslint-disable-next-line functional/immutable-data + responses.push(moveWaitablePromise); + return safe ? moveWaitablePromise.wait(options) : moveWaitablePromise; + }) + .then(() => Promise.all(responses)) + .then(([copyResponse, saveObjectsResponse, moveResponse]) => { + return { + objectIDs: saveObjectsResponse.objectIDs, + taskIDs: [copyResponse.taskID, ...saveObjectsResponse.taskIDs, moveResponse.taskID], + }; + }); + return createWaitablePromise(result, (_, waitRequestOptions) => { + return Promise.all(responses.map(response => response.wait(waitRequestOptions))); + }); + }; +}; + +const replaceAllRules = (base) => { + return (rules, requestOptions) => { + return saveRules(base)(rules, { + ...requestOptions, + clearExistingRules: true, + }); + }; +}; + +const replaceAllSynonyms = (base) => { + return (synonyms, requestOptions) => { + return saveSynonyms(base)(synonyms, { + ...requestOptions, + clearExistingSynonyms: true, + }); + }; +}; + +const saveObject = (base) => { + return (object, requestOptions) => { + return createWaitablePromise(saveObjects(base)([object], requestOptions).then(response => { + return { + objectID: response.objectIDs[0], + taskID: response.taskIDs[0], + }; + }), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const saveObjects = (base) => { + return (objects, requestOptions) => { + const { autoGenerateObjectIDIfNotExist, ...options } = requestOptions || {}; + const action = autoGenerateObjectIDIfNotExist + ? BatchActionEnum.AddObject + : BatchActionEnum.UpdateObject; + if (action === BatchActionEnum.UpdateObject) { + // eslint-disable-next-line functional/no-loop-statement + for (const object of objects) { + if (object.objectID === undefined) { + return createWaitablePromise(Promise.reject(createMissingObjectIDError())); + } + } + } + return chunkedBatch(base)(objects, action, options); + }; +}; + +const saveRule = (base) => { + return (rule, requestOptions) => { + return saveRules(base)([rule], requestOptions); + }; +}; + +const saveRules = (base) => { + return (rules, requestOptions) => { + const { forwardToReplicas, clearExistingRules, ...options } = requestOptions || {}; + const mappedRequestOptions = createMappedRequestOptions(options); + if (forwardToReplicas) { + mappedRequestOptions.queryParameters.forwardToReplicas = 1; // eslint-disable-line functional/immutable-data + } + if (clearExistingRules) { + mappedRequestOptions.queryParameters.clearExistingRules = 1; // eslint-disable-line functional/immutable-data + } + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Post, + path: encode('1/indexes/%s/rules/batch', base.indexName), + data: rules, + }, mappedRequestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const saveSynonym = (base) => { + return (synonym, requestOptions) => { + return saveSynonyms(base)([synonym], requestOptions); + }; +}; + +const saveSynonyms = (base) => { + return (synonyms, requestOptions) => { + const { forwardToReplicas, clearExistingSynonyms, replaceExistingSynonyms, ...options } = requestOptions || {}; + const mappedRequestOptions = createMappedRequestOptions(options); + if (forwardToReplicas) { + mappedRequestOptions.queryParameters.forwardToReplicas = 1; // eslint-disable-line functional/immutable-data + } + if (replaceExistingSynonyms || clearExistingSynonyms) { + mappedRequestOptions.queryParameters.replaceExistingSynonyms = 1; // eslint-disable-line functional/immutable-data + } + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Post, + path: encode('1/indexes/%s/synonyms/batch', base.indexName), + data: synonyms, + }, mappedRequestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const search = (base) => { + return (query, requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Post, + path: encode('1/indexes/%s/query', base.indexName), + data: { + query, + }, + cacheable: true, + }, requestOptions); + }; +}; + +const searchForFacetValues = (base) => { + return (facetName, facetQuery, requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Post, + path: encode('1/indexes/%s/facets/%s/query', base.indexName, facetName), + data: { + facetQuery, + }, + cacheable: true, + }, requestOptions); + }; +}; + +const searchRules = (base) => { + return (query, requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Post, + path: encode('1/indexes/%s/rules/search', base.indexName), + data: { + query, + }, + }, requestOptions); + }; +}; + +const searchSynonyms = (base) => { + return (query, requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Post, + path: encode('1/indexes/%s/synonyms/search', base.indexName), + data: { + query, + }, + }, requestOptions); + }; +}; + +const setSettings = (base) => { + return (settings, requestOptions) => { + const { forwardToReplicas, ...options } = requestOptions || {}; + const mappedRequestOptions = createMappedRequestOptions(options); + if (forwardToReplicas) { + mappedRequestOptions.queryParameters.forwardToReplicas = 1; // eslint-disable-line functional/immutable-data + } + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Put, + path: encode('1/indexes/%s/settings', base.indexName), + data: settings, + }, mappedRequestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const waitTask = (base) => { + return (taskID, requestOptions) => { + return createRetryablePromise(retry => { + return getTask(base)(taskID, requestOptions).then(response => { + return response.status !== 'published' ? retry() : undefined; + }); + }); + }; +}; + +const ApiKeyACLEnum = { + AddObject: 'addObject', + Analytics: 'analytics', + Browser: 'browse', + DeleteIndex: 'deleteIndex', + DeleteObject: 'deleteObject', + EditSettings: 'editSettings', + Inference: 'inference', + ListIndexes: 'listIndexes', + Logs: 'logs', + Personalization: 'personalization', + Recommendation: 'recommendation', + Search: 'search', + SeeUnretrievableAttributes: 'seeUnretrievableAttributes', + Settings: 'settings', + Usage: 'usage', +}; + +const BatchActionEnum = { + AddObject: 'addObject', + UpdateObject: 'updateObject', + PartialUpdateObject: 'partialUpdateObject', + PartialUpdateObjectNoCreate: 'partialUpdateObjectNoCreate', + DeleteObject: 'deleteObject', + DeleteIndex: 'delete', + ClearIndex: 'clear', +}; + +const ScopeEnum = { + Settings: 'settings', + Synonyms: 'synonyms', + Rules: 'rules', +}; + +const StrategyEnum = { + None: 'none', + StopIfEnoughMatches: 'stopIfEnoughMatches', +}; + +const SynonymEnum = { + Synonym: 'synonym', + OneWaySynonym: 'oneWaySynonym', + AltCorrection1: 'altCorrection1', + AltCorrection2: 'altCorrection2', + Placeholder: 'placeholder', +}; + +export { ApiKeyACLEnum, BatchActionEnum, ScopeEnum, StrategyEnum, SynonymEnum, addApiKey, assignUserID, assignUserIDs, batch, browseObjects, browseRules, browseSynonyms, chunkedBatch, clearDictionaryEntries, clearObjects, clearRules, clearSynonyms, copyIndex, copyRules, copySettings, copySynonyms, createBrowsablePromise, createMissingObjectIDError, createObjectNotFoundError, createSearchClient, createValidUntilNotFoundError, customRequest, deleteApiKey, deleteBy, deleteDictionaryEntries, deleteIndex, deleteObject, deleteObjects, deleteRule, deleteSynonym, exists, findAnswers, findObject, generateSecuredApiKey, getApiKey, getAppTask, getDictionarySettings, getLogs, getObject, getObjectPosition, getObjects, getRule, getSecuredApiKeyRemainingValidity, getSettings, getSynonym, getTask, getTopUserIDs, getUserID, hasPendingMappings, initIndex, listApiKeys, listClusters, listIndices, listUserIDs, moveIndex, multipleBatch, multipleGetObjects, multipleQueries, multipleSearchForFacetValues, partialUpdateObject, partialUpdateObjects, removeUserID, replaceAllObjects, replaceAllRules, replaceAllSynonyms, replaceDictionaryEntries, restoreApiKey, saveDictionaryEntries, saveObject, saveObjects, saveRule, saveRules, saveSynonym, saveSynonyms, search, searchDictionaryEntries, searchForFacetValues, searchRules, searchSynonyms, searchUserIDs, setDictionarySettings, setSettings, updateApiKey, waitAppTask, waitTask }; diff --git a/scripts/node_modules/@algolia/client-search/index.js b/scripts/node_modules/@algolia/client-search/index.js new file mode 100644 index 000000000..eebe74cb4 --- /dev/null +++ b/scripts/node_modules/@algolia/client-search/index.js @@ -0,0 +1,2 @@ +// eslint-disable-next-line functional/immutable-data, import/no-commonjs +module.exports = require('./dist/client-search.cjs.js'); diff --git a/scripts/node_modules/@algolia/client-search/package.json b/scripts/node_modules/@algolia/client-search/package.json new file mode 100644 index 000000000..ac668e4f7 --- /dev/null +++ b/scripts/node_modules/@algolia/client-search/package.json @@ -0,0 +1,23 @@ +{ + "name": "@algolia/client-search", + "version": "4.24.0", + "private": false, + "repository": { + "type": "git", + "url": "git://github.com/algolia/algoliasearch-client-javascript.git" + }, + "license": "MIT", + "sideEffects": false, + "main": "index.js", + "module": "dist/client-search.esm.js", + "types": "dist/client-search.d.ts", + "files": [ + "index.js", + "dist" + ], + "dependencies": { + "@algolia/client-common": "4.24.0", + "@algolia/requester-common": "4.24.0", + "@algolia/transporter": "4.24.0" + } +} diff --git a/scripts/node_modules/@algolia/logger-common/dist/logger-common.cjs.js b/scripts/node_modules/@algolia/logger-common/dist/logger-common.cjs.js new file mode 100644 index 000000000..8468c3179 --- /dev/null +++ b/scripts/node_modules/@algolia/logger-common/dist/logger-common.cjs.js @@ -0,0 +1,26 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +function createNullLogger() { + return { + debug(_message, _args) { + return Promise.resolve(); + }, + info(_message, _args) { + return Promise.resolve(); + }, + error(_message, _args) { + return Promise.resolve(); + }, + }; +} + +const LogLevelEnum = { + Debug: 1, + Info: 2, + Error: 3, +}; + +exports.LogLevelEnum = LogLevelEnum; +exports.createNullLogger = createNullLogger; diff --git a/scripts/node_modules/@algolia/logger-common/dist/logger-common.d.ts b/scripts/node_modules/@algolia/logger-common/dist/logger-common.d.ts new file mode 100644 index 000000000..66fdcd633 --- /dev/null +++ b/scripts/node_modules/@algolia/logger-common/dist/logger-common.d.ts @@ -0,0 +1,22 @@ +export declare function createNullLogger(): Logger; + +export declare type Logger = { + /** + * Logs debug messages. + */ + readonly debug: (message: string, args?: any) => Readonly>; + /** + * Logs info messages. + */ + readonly info: (message: string, args?: any) => Readonly>; + /** + * Logs error messages. + */ + readonly error: (message: string, args?: any) => Readonly>; +}; + +export declare const LogLevelEnum: Readonly>; + +export declare type LogLevelType = 1 | 2 | 3; + +export { } diff --git a/scripts/node_modules/@algolia/logger-common/dist/logger-common.esm.js b/scripts/node_modules/@algolia/logger-common/dist/logger-common.esm.js new file mode 100644 index 000000000..d7c830c99 --- /dev/null +++ b/scripts/node_modules/@algolia/logger-common/dist/logger-common.esm.js @@ -0,0 +1,21 @@ +function createNullLogger() { + return { + debug(_message, _args) { + return Promise.resolve(); + }, + info(_message, _args) { + return Promise.resolve(); + }, + error(_message, _args) { + return Promise.resolve(); + }, + }; +} + +const LogLevelEnum = { + Debug: 1, + Info: 2, + Error: 3, +}; + +export { LogLevelEnum, createNullLogger }; diff --git a/scripts/node_modules/@algolia/logger-common/index.js b/scripts/node_modules/@algolia/logger-common/index.js new file mode 100644 index 000000000..56c0010ed --- /dev/null +++ b/scripts/node_modules/@algolia/logger-common/index.js @@ -0,0 +1,2 @@ +// eslint-disable-next-line functional/immutable-data, import/no-commonjs +module.exports = require('./dist/logger-common.cjs.js'); diff --git a/scripts/node_modules/@algolia/logger-common/package.json b/scripts/node_modules/@algolia/logger-common/package.json new file mode 100644 index 000000000..afbf812cb --- /dev/null +++ b/scripts/node_modules/@algolia/logger-common/package.json @@ -0,0 +1,19 @@ +{ + "name": "@algolia/logger-common", + "version": "4.24.0", + "private": false, + "description": "Common interfaces for promise-based log libraries", + "repository": { + "type": "git", + "url": "git://github.com/algolia/algoliasearch-client-js.git" + }, + "license": "MIT", + "sideEffects": false, + "main": "index.js", + "module": "dist/logger-common.esm.js", + "types": "dist/logger-common.d.ts", + "files": [ + "index.js", + "dist" + ] +} diff --git a/scripts/node_modules/@algolia/logger-console/dist/logger-console.cjs.js b/scripts/node_modules/@algolia/logger-console/dist/logger-console.cjs.js new file mode 100644 index 000000000..90cf4bc0e --- /dev/null +++ b/scripts/node_modules/@algolia/logger-console/dist/logger-console.cjs.js @@ -0,0 +1,29 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var loggerCommon = require('@algolia/logger-common'); + +/* eslint no-console: 0 */ +function createConsoleLogger(logLevel) { + return { + debug(message, args) { + if (loggerCommon.LogLevelEnum.Debug >= logLevel) { + console.debug(message, args); + } + return Promise.resolve(); + }, + info(message, args) { + if (loggerCommon.LogLevelEnum.Info >= logLevel) { + console.info(message, args); + } + return Promise.resolve(); + }, + error(message, args) { + console.error(message, args); + return Promise.resolve(); + }, + }; +} + +exports.createConsoleLogger = createConsoleLogger; diff --git a/scripts/node_modules/@algolia/logger-console/dist/logger-console.d.ts b/scripts/node_modules/@algolia/logger-console/dist/logger-console.d.ts new file mode 100644 index 000000000..46d24aa60 --- /dev/null +++ b/scripts/node_modules/@algolia/logger-console/dist/logger-console.d.ts @@ -0,0 +1,6 @@ +import { Logger } from '@algolia/logger-common'; +import { LogLevelType } from '@algolia/logger-common'; + +export declare function createConsoleLogger(logLevel: LogLevelType): Logger; + +export { } diff --git a/scripts/node_modules/@algolia/logger-console/dist/logger-console.esm.js b/scripts/node_modules/@algolia/logger-console/dist/logger-console.esm.js new file mode 100644 index 000000000..ce36e9921 --- /dev/null +++ b/scripts/node_modules/@algolia/logger-console/dist/logger-console.esm.js @@ -0,0 +1,25 @@ +import { LogLevelEnum } from '@algolia/logger-common'; + +/* eslint no-console: 0 */ +function createConsoleLogger(logLevel) { + return { + debug(message, args) { + if (LogLevelEnum.Debug >= logLevel) { + console.debug(message, args); + } + return Promise.resolve(); + }, + info(message, args) { + if (LogLevelEnum.Info >= logLevel) { + console.info(message, args); + } + return Promise.resolve(); + }, + error(message, args) { + console.error(message, args); + return Promise.resolve(); + }, + }; +} + +export { createConsoleLogger }; diff --git a/scripts/node_modules/@algolia/logger-console/index.js b/scripts/node_modules/@algolia/logger-console/index.js new file mode 100644 index 000000000..1a8f955bd --- /dev/null +++ b/scripts/node_modules/@algolia/logger-console/index.js @@ -0,0 +1,2 @@ +// eslint-disable-next-line functional/immutable-data, import/no-commonjs +module.exports = require('./dist/logger-console.cjs.js'); diff --git a/scripts/node_modules/@algolia/logger-console/package.json b/scripts/node_modules/@algolia/logger-console/package.json new file mode 100644 index 000000000..ab8a6eb57 --- /dev/null +++ b/scripts/node_modules/@algolia/logger-console/package.json @@ -0,0 +1,22 @@ +{ + "name": "@algolia/logger-console", + "version": "4.24.0", + "private": false, + "description": "Promise-based log library using console log.", + "repository": { + "type": "git", + "url": "git://github.com/algolia/algoliasearch-client-javascript.git" + }, + "license": "MIT", + "sideEffects": false, + "main": "index.js", + "module": "dist/logger-console.esm.js", + "types": "dist/logger-console.d.ts", + "files": [ + "index.js", + "dist" + ], + "dependencies": { + "@algolia/logger-common": "4.24.0" + } +} diff --git a/scripts/node_modules/@algolia/recommend/README.md b/scripts/node_modules/@algolia/recommend/README.md new file mode 100644 index 000000000..33c79a68d --- /dev/null +++ b/scripts/node_modules/@algolia/recommend/README.md @@ -0,0 +1,76 @@ +

+

Algolia Recommend

+ +

The perfect starting point to integrate Algolia Recommend within your JavaScript project

+ +

+ NPM version + License +

+

+ +

+ Documentation • + UI library • + Community Forum • + Stack Overflow • + Report a bug • + Support +

+ +## ✨ Features + +- Thin & **minimal low-level HTTP client** to interact with Algolia's Recommend API +- Works both on the **browser** and **node.js** +- **UMD compatible**, you can use it with any module loader +- Built with TypeScript + +## 💡 Getting Started + +First, install Algolia Recommend API Client via the [npm](https://www.npmjs.com/get-npm) package manager: + +```bash +npm install @algolia/recommend +``` + +Then, let's retrieve recommendations: + +```js +const algoliarecommend = require('@algolia/recommend'); + +const client = algoliarecommend('YourApplicationID', 'YourAdminAPIKey'); + +client + .getFrequentlyBoughtTogether([ + { + indexName: 'your_index_name', + objectID: 'your_object_id', + }, + ]) + .then(({ results }) => { + console.log(results); + }) + .catch(err => { + console.log(err); + }); + +client + .getRelatedProducts([ + { + indexName: 'your_index_name', + objectID: 'your_object_id', + }, + ]) + .then(({ results }) => { + console.log(results); + }) + .catch(err => { + console.log(err); + }); +``` + +For full documentation, visit the **[online documentation](https://www.algolia.com/doc/api-client/methods/recommend/)**. + +## 📄 License + +Algolia Recommend API Client is an open-sourced software licensed under the [MIT license](LICENSE.md). diff --git a/scripts/node_modules/@algolia/recommend/dist/recommend.cjs.js b/scripts/node_modules/@algolia/recommend/dist/recommend.cjs.js new file mode 100644 index 000000000..8269d5c17 --- /dev/null +++ b/scripts/node_modules/@algolia/recommend/dist/recommend.cjs.js @@ -0,0 +1,201 @@ +'use strict'; + +var cacheCommon = require('@algolia/cache-common'); +var cacheInMemory = require('@algolia/cache-in-memory'); +var clientCommon = require('@algolia/client-common'); +var loggerCommon = require('@algolia/logger-common'); +var requesterNodeHttp = require('@algolia/requester-node-http'); +var transporter = require('@algolia/transporter'); +var requesterCommon = require('@algolia/requester-common'); + +const createRecommendClient = options => { + const appId = options.appId; + const auth = clientCommon.createAuth(options.authMode !== undefined ? options.authMode : clientCommon.AuthMode.WithinHeaders, appId, options.apiKey); + const transporter$1 = transporter.createTransporter({ + hosts: [ + { url: `${appId}-dsn.algolia.net`, accept: transporter.CallEnum.Read }, + { url: `${appId}.algolia.net`, accept: transporter.CallEnum.Write }, + ].concat(clientCommon.shuffle([ + { url: `${appId}-1.algolianet.com` }, + { url: `${appId}-2.algolianet.com` }, + { url: `${appId}-3.algolianet.com` }, + ])), + ...options, + headers: { + ...auth.headers(), + ...{ 'content-type': 'application/x-www-form-urlencoded' }, + ...options.headers, + }, + queryParameters: { + ...auth.queryParameters(), + ...options.queryParameters, + }, + }); + const base = { + transporter: transporter$1, + appId, + addAlgoliaAgent(segment, version) { + transporter$1.userAgent.add({ segment, version }); + }, + clearCache() { + return Promise.all([ + transporter$1.requestsCache.clear(), + transporter$1.responsesCache.clear(), + ]).then(() => undefined); + }, + }; + return clientCommon.addMethods(base, options.methods); +}; + +const getRecommendations = base => { + return (queries, requestOptions) => { + const requests = queries.map(query => ({ + ...query, + // The `threshold` param is required by the endpoint to make it easier + // to provide a default value later, so we default it in the client + // so that users don't have to provide a value. + threshold: query.threshold || 0, + })); + return base.transporter.read({ + method: requesterCommon.MethodEnum.Post, + path: '1/indexes/*/recommendations', + data: { + requests, + }, + cacheable: true, + }, requestOptions); + }; +}; + +const getFrequentlyBoughtTogether = base => { + return (queries, requestOptions) => { + return getRecommendations(base)(queries.map(query => ({ + ...query, + fallbackParameters: {}, + model: 'bought-together', + })), requestOptions); + }; +}; + +const getRelatedProducts = base => { + return (queries, requestOptions) => { + return getRecommendations(base)(queries.map(query => ({ + ...query, + model: 'related-products', + })), requestOptions); + }; +}; + +const getTrendingFacets = base => { + return (queries, requestOptions) => { + const requests = queries.map(query => ({ + ...query, + model: 'trending-facets', + // The `threshold` param is required by the endpoint to make it easier + // to provide a default value later, so we default it in the client + // so that users don't have to provide a value. + threshold: query.threshold || 0, + })); + return base.transporter.read({ + method: requesterCommon.MethodEnum.Post, + path: '1/indexes/*/recommendations', + data: { + requests, + }, + cacheable: true, + }, requestOptions); + }; +}; + +const getTrendingItems = base => { + return (queries, requestOptions) => { + const requests = queries.map(query => ({ + ...query, + model: 'trending-items', + // The `threshold` param is required by the endpoint to make it easier + // to provide a default value later, so we default it in the client + // so that users don't have to provide a value. + threshold: query.threshold || 0, + })); + return base.transporter.read({ + method: requesterCommon.MethodEnum.Post, + path: '1/indexes/*/recommendations', + data: { + requests, + }, + cacheable: true, + }, requestOptions); + }; +}; + +const getLookingSimilar = base => { + return (queries, requestOptions) => { + return getRecommendations(base)(queries.map(query => ({ + ...query, + model: 'looking-similar', + })), requestOptions); + }; +}; + +const getRecommendedForYou = base => { + return (queries, requestOptions) => { + const requests = queries.map(query => ({ + ...query, + model: 'recommended-for-you', + threshold: query.threshold || 0, + })); + return base.transporter.read({ + method: requesterCommon.MethodEnum.Post, + path: '1/indexes/*/recommendations', + data: { + requests, + }, + cacheable: true, + }, requestOptions); + }; +}; + +function recommend(appId, apiKey, options) { + const commonOptions = { + appId, + apiKey, + timeouts: { + connect: 2, + read: 5, + write: 30, + }, + requester: requesterNodeHttp.createNodeHttpRequester(), + logger: loggerCommon.createNullLogger(), + responsesCache: cacheCommon.createNullCache(), + requestsCache: cacheCommon.createNullCache(), + hostsCache: cacheInMemory.createInMemoryCache(), + userAgent: transporter.createUserAgent(clientCommon.version) + .add({ segment: 'Recommend', version: clientCommon.version }) + .add({ segment: 'Node.js', version: process.versions.node }), + }; + return createRecommendClient({ + ...commonOptions, + ...options, + methods: { + destroy: clientCommon.destroy, + getFrequentlyBoughtTogether, + getRecommendations, + getRelatedProducts, + getTrendingFacets, + getTrendingItems, + getLookingSimilar, + getRecommendedForYou, + }, + }); +} +/* eslint-disable functional/immutable-data */ +recommend.version = clientCommon.version; +recommend.getFrequentlyBoughtTogether = getFrequentlyBoughtTogether; +recommend.getRecommendations = getRecommendations; +recommend.getRelatedProducts = getRelatedProducts; +recommend.getTrendingFacets = getTrendingFacets; +recommend.getTrendingItems = getTrendingItems; +recommend.getLookingSimilar = getLookingSimilar; +recommend.getRecommendedForYou = getRecommendedForYou; + +module.exports = recommend; diff --git a/scripts/node_modules/@algolia/recommend/dist/recommend.d.ts b/scripts/node_modules/@algolia/recommend/dist/recommend.d.ts new file mode 100644 index 000000000..a6d817ca9 --- /dev/null +++ b/scripts/node_modules/@algolia/recommend/dist/recommend.d.ts @@ -0,0 +1,587 @@ +import { AuthModeType } from '@algolia/client-common'; +import { ClientTransporterOptions } from '@algolia/client-common'; +import { Destroyable } from '@algolia/requester-common'; +import { RecommendSearchOptions as RecommendSearchOptions_2 } from '@algolia/recommend'; +import { RequestOptions } from '@algolia/transporter'; +import { SearchOptions } from '@algolia/client-search'; +import { SearchResponse } from '@algolia/client-search'; +import { Transporter } from '@algolia/transporter'; + +export declare type BaseRecommendClient = { + /** + * The application id. + */ + readonly appId: string; + /** + * The underlying transporter. + */ + readonly transporter: Transporter; + /** + * Mutates the transporter, adding the given user agent. + */ + readonly addAlgoliaAgent: (segment: string, version?: string) => void; + /** + * Clears both requests and responses caches. + */ + readonly clearCache: () => Readonly>; +}; + +export declare type FrequentlyBoughtTogetherQuery = Omit; + +export declare type LookingSimilarQuery = Omit; + +declare function recommend(appId: string, apiKey: string, options?: RecommendOptions): RecommendClient; + +declare namespace recommend { + var version: string; + var getFrequentlyBoughtTogether: (base: BaseRecommendClient) => (queries: readonly Pick[], requestOptions?: (RequestOptions_2 & SearchOptions_2) | undefined) => Readonly>>; + var getRecommendations: (base: BaseRecommendClient) => (queries: readonly (RecommendationsQuery | (TrendingItemsQuery & { + readonly model: TrendingModel; + }) | (TrendingFacetsQuery & { + readonly model: TrendingModel; + }) | RecommendedForYouQuery)[], requestOptions?: (RequestOptions_2 & SearchOptions_2) | undefined) => Readonly>>; + var getRelatedProducts: (base: BaseRecommendClient) => (queries: readonly Pick[], requestOptions?: (RequestOptions_2 & SearchOptions_2) | undefined) => Readonly>>; + var getTrendingFacets: (base: BaseRecommendClient) => (queries: readonly TrendingFacetsQuery[], requestOptions?: (RequestOptions_2 & SearchOptions_2) | undefined) => Readonly>; + var getTrendingItems: (base: BaseRecommendClient) => (queries: readonly TrendingItemsQuery[], requestOptions?: (RequestOptions_2 & SearchOptions_2) | undefined) => Readonly>>; + var getLookingSimilar: (base: BaseRecommendClient) => (queries: readonly Pick[], requestOptions?: (RequestOptions_2 & SearchOptions_2) | undefined) => Readonly>>; + var getRecommendedForYou: (base: BaseRecommendClient) => (queries: readonly Pick[], requestOptions?: (RequestOptions_2 & SearchOptions_2) | undefined) => Readonly>>; +} +export default recommend; + +export declare type RecommendationsQuery = { + /** + * The name of the target index. + */ + readonly indexName: string; + /** + * The name of the Recommendation model to use. + */ + readonly model: 'related-products' | 'bought-together' | 'looking-similar'; + /** + * The `objectID` of the item to get recommendations for. + */ + readonly objectID: string; + /** + * Threshold for the recommendations confidence score (between 0 and 100). Only recommendations with a greater score are returned. + */ + readonly threshold?: number; + /** + * How many recommendations to retrieve. + */ + readonly maxRecommendations?: number; + /** + * List of [search parameters](https://www.algolia.com/doc/api-reference/search-api-parameters/) to send. + */ + readonly queryParameters?: RecommendSearchOptions; + /** + * List of [search parameters](https://www.algolia.com/doc/api-reference/search-api-parameters/) to send. + * + * Additional filters to use as fallback when there aren’t enough recommendations. + */ + readonly fallbackParameters?: RecommendSearchOptions; +}; + +export declare type RecommendClient = WithRecommendMethods & Destroyable; + +export declare type RecommendClientOptions = { + /** + * The application id. + */ + readonly appId: string; + /** + * The api key. + */ + readonly apiKey: string; + /** + * The auth mode type. In browser environments credentials may + * be passed within the headers. + */ + readonly authMode?: AuthModeType; +}; + +/** + * The parameters used for `getRecommendedForYou` method. + */ +export declare type RecommendedForYouParams = Omit; + +export declare type RecommendedForYouQuery = Omit & { + readonly model: 'recommended-for-you'; + /** + * List of [search parameters](https://www.algolia.com/doc/api-reference/search-api-parameters/) to send. + */ + readonly queryParameters: Omit & { + /** + * A user identifier. + * Format: alpha numeric string [a-zA-Z0-9_-] + * Length: between 1 and 64 characters. + */ + readonly userToken: string; + }; +}; + +export declare type RecommendModel = 'related-products' | 'bought-together' | 'looking-similar' | 'recommended-for-you' | TrendingModel; + +export declare type RecommendOptions = Partial; + +export declare type RecommendQueriesResponse = { + /** + * The list of results. + */ + readonly results: ReadonlyArray>; +}; + +export declare type RecommendSearchOptions = Omit; + +export declare type RecommendTrendingFacetsQueriesResponse = { + /** + * The list of results. + */ + readonly results: readonly TrendingFacetsResponse[]; +}; + +export declare type RelatedProductsQuery = Omit; + +declare type RequestOptions_2 = { + /** + * If the given request should persist on the cache. Keep in mind, + * that some methods may have this option enabled by default. + */ + readonly cacheable?: boolean; + /** + * Custom timeout for the request. Note that, in normal situacions + * the given timeout will be applied. But the transporter layer may + * increase this timeout if there is need for it. + */ + readonly timeout?: number; + /** + * Custom headers for the request. This headers are + * going to be merged the transporter headers. + */ + readonly headers?: Readonly>; + /** + * Custom query parameters for the request. This query parameters are + * going to be merged the transporter query parameters. + */ + readonly queryParameters?: Record; + /** + * Custom data for the request. This data are + * going to be merged the transporter data. + */ + readonly data?: Record; + /** + * Additional request body values. It's only taken in + * consideration in `POST` and `PUT` requests. + */ + [key: string]: any; +}; + +declare type SearchOptions_2 = { + /** + * Create a new query with an empty search query. + */ + readonly query?: string; + /** + * Allows a search for similar objects, but the query has to be constructed on your end and included alongside an empty query. + * + * The similarQuery should be made from the tags and keywords of the relevant object. + */ + readonly similarQuery?: string; + /** + * Filter hits by facet value. + */ + readonly facetFilters?: string | readonly string[] | ReadonlyArray; + /** + * Create filters for ranking purposes, where records that match the filter are ranked highest. + */ + readonly optionalFilters?: string | readonly string[] | ReadonlyArray; + /** + * Filter on numeric attributes. + */ + readonly numericFilters?: string | readonly string[] | ReadonlyArray; + /** + * Filter hits by tags. tagFilters is a different way of filtering, which relies on the _tags + * attribute. It uses a simpler syntax than filters. You can use it when you want to do + * simple filtering based on tags. + */ + readonly tagFilters?: string | readonly string[] | ReadonlyArray; + /** + * Determines how to calculate the total score for filtering. + */ + readonly sumOrFiltersScores?: boolean; + /** + * Filter the query with numeric, facet and/or tag filters. + */ + readonly filters?: string; + /** + * Specify the page to retrieve. + */ + readonly page?: number; + /** + * Set the number of hits per page. + */ + readonly hitsPerPage?: number; + /** + * Specify the offset of the first hit to return. + */ + readonly offset?: number; + /** + * Set the number of hits to retrieve (used only with offset). + */ + readonly length?: number; + /** + * List of attributes to highlight. + */ + readonly attributesToHighlight?: readonly string[]; + /** + * List of attributes to snippet, with an optional maximum number of words to snippet. + */ + readonly attributesToSnippet?: readonly string[]; + /** + * Gives control over which attributes to retrieve and which not to retrieve. + */ + readonly attributesToRetrieve?: readonly string[]; + /** + * The HTML string to insert before the highlighted parts in all highlight and snippet results. + */ + readonly highlightPreTag?: string; + /** + * The HTML string to insert after the highlighted parts in all highlight and snippet results + */ + readonly highlightPostTag?: string; + /** + * String used as an ellipsis indicator when a snippet is truncated. + */ + readonly snippetEllipsisText?: string; + /** + * Restrict highlighting and snippeting to items that matched the query. + */ + readonly restrictHighlightAndSnippetArrays?: boolean; + /** + * Facets to retrieve. + */ + readonly facets?: readonly string[]; + /** + * Maximum number of facet values to return for each facet during a regular search. + */ + readonly maxValuesPerFacet?: number; + /** + * Force faceting to be applied after de-duplication (via the Distinct setting). + */ + readonly facetingAfterDistinct?: boolean; + /** + * Minimum number of characters a word in the query string must contain to accept matches with 1 typo + */ + readonly minWordSizefor1Typo?: number; + /** + * Minimum number of characters a word in the query string must contain to accept matches with 2 typos. + */ + readonly minWordSizefor2Typos?: number; + /** + * Whether to allow typos on numbers (“numeric tokens”) in the query string. + */ + readonly allowTyposOnNumericTokens?: boolean; + /** + * List of attributes on which you want to disable typo tolerance. + */ + readonly disableTypoToleranceOnAttributes?: readonly string[]; + /** + * Controls if and how query words are interpreted as prefixes. + */ + readonly queryType?: 'prefixLast' | 'prefixAll' | 'prefixNone'; + /** + * Selects a strategy to remove words from the query when it doesn’t match any hits. + */ + readonly removeWordsIfNoResults?: 'none' | 'lastWords' | 'firstWords' | 'allOptional'; + /** + * Enables the advanced query syntax. + */ + readonly advancedSyntax?: boolean; + /** + * AdvancedSyntaxFeatures can be exactPhrase or excludeWords + */ + readonly advancedSyntaxFeatures?: ReadonlyArray<'exactPhrase' | 'excludeWords'>; + /** + * A list of words that should be considered as optional when found in the query. + */ + readonly optionalWords?: string | readonly string[]; + /** + * List of attributes on which you want to disable the exact ranking criterion. + */ + readonly disableExactOnAttributes?: readonly string[]; + /** + * Controls how the exact ranking criterion is computed when the query contains only one word. + */ + readonly exactOnSingleWordQuery?: 'attribute' | 'none' | 'word'; + /** + * List of alternatives that should be considered an exact match by the exact ranking criterion. + */ + readonly alternativesAsExact?: ReadonlyArray<'ignorePlurals' | 'singleWordSynonym' | 'multiWordsSynonym'>; + /** + * Whether rules should be globally enabled. + */ + readonly enableRules?: boolean; + /** + * Enables contextual rules. + */ + readonly ruleContexts?: readonly string[]; + /** + * Enables de-duplication or grouping of results. + */ + readonly distinct?: boolean | number; + /** + * Whether the current query will be taken into account in the Analytics + */ + readonly analytics?: boolean; + /** + * List of tags to apply to the query in the analytics. + */ + readonly analyticsTags?: readonly string[]; + /** + * Whether to take into account an index’s synonyms for a particular search. + */ + readonly synonyms?: boolean; + /** + * Whether to highlight and snippet the original word that matches the synonym or the synonym itself. + */ + readonly replaceSynonymsInHighlight?: boolean; + /** + * Precision of the proximity ranking criterion. + */ + readonly minProximity?: number; + /** + * Choose which fields the response will contain. Applies to search and browse queries. + */ + readonly responseFields?: readonly string[]; + /** + * Maximum number of facet hits to return during a search for facet values. + */ + readonly maxFacetHits?: number; + /** + * Whether to include or exclude a query from the processing-time percentile computation. + */ + readonly percentileComputation?: boolean; + /** + * Enable the Click Analytics feature. + */ + readonly clickAnalytics?: boolean; + /** + * The `personalizationImpact` parameter sets the percentage of the impact that personalization has on ranking records. The + * value must be between 0 and 100 (inclusive). This parameter will not be taken into account if `enablePersonalization` + * is **false**. + */ + readonly personalizationImpact?: number; + /** + * Enable personalization for the query + */ + readonly enablePersonalization?: boolean; + /** + * Restricts a given query to look in only a subset of your searchable attributes. + */ + readonly restrictSearchableAttributes?: readonly string[]; + /** + * Controls how facet values are sorted. + */ + readonly sortFacetValuesBy?: 'count' | 'alpha'; + /** + * Controls whether typo tolerance is enabled and how it is applied. + */ + readonly typoTolerance?: boolean | 'min' | 'strict'; + /** + * Search for entries around a central geolocation, enabling a geo search within a circular area. + */ + readonly aroundLatLng?: string; + /** + * Search for entries around a given location automatically computed from the requester’s IP address. + */ + readonly aroundLatLngViaIP?: boolean; + /** + * Define the maximum radius for a geo search (in meters). + */ + readonly aroundRadius?: number | 'all'; + /** + * Precision of geo search (in meters), to add grouping by geo location to the ranking formula. + */ + readonly aroundPrecision?: number | ReadonlyArray<{ + readonly from: number; + readonly value: number; + }>; + /** + * Minimum radius (in meters) used for a geo search when aroundRadius is not set. + */ + readonly minimumAroundRadius?: number; + /** + * Search inside a rectangular area (in geo coordinates). + */ + readonly insideBoundingBox?: ReadonlyArray | string; + /** + * Search inside a polygon (in geo coordinates). + */ + readonly insidePolygon?: ReadonlyArray; + /** + * Treats singular, plurals, and other forms of declensions as matching terms. + */ + readonly ignorePlurals?: boolean | readonly string[]; + /** + * Removes stop (common) words from the query before executing it. + */ + readonly removeStopWords?: boolean | readonly string[]; + /** + * List of supported languages with their associated language ISO code. + * + * Apply a set of natural language best practices such as ignorePlurals, + * removeStopWords, removeWordsIfNoResults, analyticsTags and ruleContexts. + */ + readonly naturalLanguages?: readonly string[]; + /** + * When true, each hit in the response contains an additional _rankingInfo object. + */ + readonly getRankingInfo?: boolean; + /** + * A user identifier. + * Format: alpha numeric string [a-zA-Z0-9_-] + * Length: between 1 and 64 characters. + */ + readonly userToken?: string; + /** + * Can be to enable or disable A/B tests at query time. + * Engine's default: true + */ + readonly enableABTest?: boolean; + /** + * Enable word segmentation (also called decompounding) at query time for + * compatible languages. For example, this turns the Dutch query + * "spaanplaatbehang" into "spaan plaat behang" to retrieve more relevant + * results. + */ + readonly decompoundQuery?: boolean; + /** + * The relevancy threshold to apply to search in a virtual index [0-100]. A Bigger + * value means fewer, but more relevant results, smaller value means more, but + * less relevant results. + */ + readonly relevancyStrictness?: number; + /** + * Whether this search should use Dynamic Re-Ranking. + * @link https://www.algolia.com/doc/guides/algolia-ai/re-ranking/ + * + * Note: You need to turn on Dynamic Re-Ranking on your index for it to have an effect on + * your search results. You can do this through the Re-Ranking page on the dashboard. + * This parameter is only used to turn off Dynamic Re-Ranking (with false) at search time. + */ + readonly enableReRanking?: boolean; + /** + * When Dynamic Re-Ranking is enabled, only records that match these filters will be impacted by Dynamic Re-Ranking. + */ + readonly reRankingApplyFilter?: string | readonly string[] | ReadonlyArray | null; + /** + * Sets the languages to be used by language-specific settings and functionalities such as ignorePlurals, removeStopWords, and CJK word-detection. + */ + readonly queryLanguages?: readonly string[]; + /** + * Enriches the API’s response with meta-information as to how the query was processed. + */ + readonly explain?: readonly string[]; +}; + +export declare type TrendingFacetHit = { + readonly _score: number; + readonly facetName: string; + readonly facetValue: string; +}; + +export declare type TrendingFacetsQuery = { + /** + * The name of the target index. + */ + readonly indexName: string; + /** + * Threshold for the recommendations confidence score (between 0 and 100). Only recommendations with a greater score are returned. + */ + readonly threshold?: number; + /** + * How many recommendations to retrieve. + */ + readonly maxRecommendations?: number; + /** + * The facet attribute to get recommendations for. + */ + readonly facetName: string; +}; + +export declare type TrendingFacetsResponse = Omit & { + readonly hits: readonly TrendingFacetHit[]; +}; + +export declare type TrendingItemsQuery = { + /** + * The name of the target index. + */ + readonly indexName: string; + /** + * Threshold for the recommendations confidence score (between 0 and 100). Only recommendations with a greater score are returned. + */ + readonly threshold?: number; + /** + * How many recommendations to retrieve. + */ + readonly maxRecommendations?: number; + /** + * List of [search parameters](https://www.algolia.com/doc/api-reference/search-api-parameters/) to send. + */ + readonly queryParameters?: RecommendSearchOptions_2; + /** + * List of [search parameters](https://www.algolia.com/doc/api-reference/search-api-parameters/) to send. + * + * Additional filters to use as fallback when there aren’t enough recommendations. + */ + readonly fallbackParameters?: RecommendSearchOptions_2; + /** + * The facet attribute to get recommendations for. + */ + readonly facetName?: string; + /** + * The value of the target facet. + */ + readonly facetValue?: string; +}; + +export declare type TrendingModel = 'trending-items' | 'trending-facets'; + +export declare type TrendingQuery = (TrendingItemsQuery & { + readonly model: TrendingModel; +}) | (TrendingFacetsQuery & { + readonly model: TrendingModel; +}); + +export declare type WithRecommendMethods = TType & { + /** + * Returns recommendations. + */ + readonly getRecommendations: (queries: ReadonlyArray, requestOptions?: RequestOptions & SearchOptions) => Readonly>>; + /** + * Returns [Related Products](https://algolia.com/doc/guides/algolia-ai/recommend/#related-products). + */ + readonly getRelatedProducts: (queries: readonly RelatedProductsQuery[], requestOptions?: RequestOptions & SearchOptions) => Readonly>>; + /** + * Returns [Frequently Bought Together](https://algolia.com/doc/guides/algolia-ai/recommend/#frequently-bought-together) products. + */ + readonly getFrequentlyBoughtTogether: (queries: readonly FrequentlyBoughtTogetherQuery[], requestOptions?: RequestOptions & SearchOptions) => Readonly>>; + /** + * Returns trending items + */ + readonly getTrendingItems: (queries: readonly TrendingItemsQuery[], requestOptions?: RequestOptions & SearchOptions) => Readonly>>; + /** + * Returns trending items per facet + */ + readonly getTrendingFacets: (queries: readonly TrendingFacetsQuery[], requestOptions?: RequestOptions & SearchOptions) => Readonly>; + /** + * Returns Looking Similar + */ + readonly getLookingSimilar: (queries: readonly LookingSimilarQuery[], requestOptions?: RequestOptions & SearchOptions) => Readonly>>; + /** + * Returns Recommended for you + */ + readonly getRecommendedForYou: (queries: readonly RecommendedForYouParams[], requestOptions?: RequestOptions & SearchOptions) => Readonly>>; +}; + +export { } diff --git a/scripts/node_modules/@algolia/recommend/dist/recommend.esm.browser.js b/scripts/node_modules/@algolia/recommend/dist/recommend.esm.browser.js new file mode 100644 index 000000000..e6f3ba315 --- /dev/null +++ b/scripts/node_modules/@algolia/recommend/dist/recommend.esm.browser.js @@ -0,0 +1,958 @@ +function createBrowserLocalStorageCache(options) { + const namespaceKey = `algoliasearch-client-js-${options.key}`; + // eslint-disable-next-line functional/no-let + let storage; + const getStorage = () => { + if (storage === undefined) { + storage = options.localStorage || window.localStorage; + } + return storage; + }; + const getNamespace = () => { + return JSON.parse(getStorage().getItem(namespaceKey) || '{}'); + }; + const setNamespace = (namespace) => { + getStorage().setItem(namespaceKey, JSON.stringify(namespace)); + }; + const removeOutdatedCacheItems = () => { + const timeToLive = options.timeToLive ? options.timeToLive * 1000 : null; + const namespace = getNamespace(); + const filteredNamespaceWithoutOldFormattedCacheItems = Object.fromEntries(Object.entries(namespace).filter(([, cacheItem]) => { + return cacheItem.timestamp !== undefined; + })); + setNamespace(filteredNamespaceWithoutOldFormattedCacheItems); + if (!timeToLive) + return; + const filteredNamespaceWithoutExpiredItems = Object.fromEntries(Object.entries(filteredNamespaceWithoutOldFormattedCacheItems).filter(([, cacheItem]) => { + const currentTimestamp = new Date().getTime(); + const isExpired = cacheItem.timestamp + timeToLive < currentTimestamp; + return !isExpired; + })); + setNamespace(filteredNamespaceWithoutExpiredItems); + }; + return { + get(key, defaultValue, events = { + miss: () => Promise.resolve(), + }) { + return Promise.resolve() + .then(() => { + removeOutdatedCacheItems(); + const keyAsString = JSON.stringify(key); + return getNamespace()[keyAsString]; + }) + .then(value => { + return Promise.all([value ? value.value : defaultValue(), value !== undefined]); + }) + .then(([value, exists]) => { + return Promise.all([value, exists || events.miss(value)]); + }) + .then(([value]) => value); + }, + set(key, value) { + return Promise.resolve().then(() => { + const namespace = getNamespace(); + // eslint-disable-next-line functional/immutable-data + namespace[JSON.stringify(key)] = { + timestamp: new Date().getTime(), + value, + }; + getStorage().setItem(namespaceKey, JSON.stringify(namespace)); + return value; + }); + }, + delete(key) { + return Promise.resolve().then(() => { + const namespace = getNamespace(); + // eslint-disable-next-line functional/immutable-data + delete namespace[JSON.stringify(key)]; + getStorage().setItem(namespaceKey, JSON.stringify(namespace)); + }); + }, + clear() { + return Promise.resolve().then(() => { + getStorage().removeItem(namespaceKey); + }); + }, + }; +} + +// @todo Add logger on options to debug when caches go wrong. +function createFallbackableCache(options) { + const caches = [...options.caches]; + const current = caches.shift(); // eslint-disable-line functional/immutable-data + if (current === undefined) { + return createNullCache(); + } + return { + get(key, defaultValue, events = { + miss: () => Promise.resolve(), + }) { + return current.get(key, defaultValue, events).catch(() => { + return createFallbackableCache({ caches }).get(key, defaultValue, events); + }); + }, + set(key, value) { + return current.set(key, value).catch(() => { + return createFallbackableCache({ caches }).set(key, value); + }); + }, + delete(key) { + return current.delete(key).catch(() => { + return createFallbackableCache({ caches }).delete(key); + }); + }, + clear() { + return current.clear().catch(() => { + return createFallbackableCache({ caches }).clear(); + }); + }, + }; +} + +function createNullCache() { + return { + get(_key, defaultValue, events = { + miss: () => Promise.resolve(), + }) { + const value = defaultValue(); + return value + .then(result => Promise.all([result, events.miss(result)])) + .then(([result]) => result); + }, + set(_key, value) { + return Promise.resolve(value); + }, + delete(_key) { + return Promise.resolve(); + }, + clear() { + return Promise.resolve(); + }, + }; +} + +function createInMemoryCache(options = { serializable: true }) { + // eslint-disable-next-line functional/no-let + let cache = {}; + return { + get(key, defaultValue, events = { + miss: () => Promise.resolve(), + }) { + const keyAsString = JSON.stringify(key); + if (keyAsString in cache) { + return Promise.resolve(options.serializable ? JSON.parse(cache[keyAsString]) : cache[keyAsString]); + } + const promise = defaultValue(); + const miss = (events && events.miss) || (() => Promise.resolve()); + return promise.then((value) => miss(value)).then(() => promise); + }, + set(key, value) { + // eslint-disable-next-line functional/immutable-data + cache[JSON.stringify(key)] = options.serializable ? JSON.stringify(value) : value; + return Promise.resolve(value); + }, + delete(key) { + // eslint-disable-next-line functional/immutable-data + delete cache[JSON.stringify(key)]; + return Promise.resolve(); + }, + clear() { + cache = {}; + return Promise.resolve(); + }, + }; +} + +function createAuth(authMode, appId, apiKey) { + const credentials = { + 'x-algolia-api-key': apiKey, + 'x-algolia-application-id': appId, + }; + return { + headers() { + return authMode === AuthMode.WithinHeaders ? credentials : {}; + }, + queryParameters() { + return authMode === AuthMode.WithinQueryParameters ? credentials : {}; + }, + }; +} + +// eslint-disable-next-line functional/prefer-readonly-type +function shuffle(array) { + let c = array.length - 1; // eslint-disable-line functional/no-let + // eslint-disable-next-line functional/no-loop-statement + for (c; c > 0; c--) { + const b = Math.floor(Math.random() * (c + 1)); + const a = array[c]; + array[c] = array[b]; // eslint-disable-line functional/immutable-data, no-param-reassign + array[b] = a; // eslint-disable-line functional/immutable-data, no-param-reassign + } + return array; +} +function addMethods(base, methods) { + if (!methods) { + return base; + } + Object.keys(methods).forEach(key => { + // eslint-disable-next-line functional/immutable-data, no-param-reassign + base[key] = methods[key](base); + }); + return base; +} +function encode(format, ...args) { + // eslint-disable-next-line functional/no-let + let i = 0; + return format.replace(/%s/g, () => encodeURIComponent(args[i++])); +} + +const version = '4.24.0'; + +const AuthMode = { + /** + * If auth credentials should be in query parameters. + */ + WithinQueryParameters: 0, + /** + * If auth credentials should be in headers. + */ + WithinHeaders: 1, +}; + +const LogLevelEnum = { + Debug: 1, + Info: 2, + Error: 3, +}; + +/* eslint no-console: 0 */ +function createConsoleLogger(logLevel) { + return { + debug(message, args) { + if (LogLevelEnum.Debug >= logLevel) { + console.debug(message, args); + } + return Promise.resolve(); + }, + info(message, args) { + if (LogLevelEnum.Info >= logLevel) { + console.info(message, args); + } + return Promise.resolve(); + }, + error(message, args) { + console.error(message, args); + return Promise.resolve(); + }, + }; +} + +function createBrowserXhrRequester() { + return { + send(request) { + return new Promise((resolve) => { + const baseRequester = new XMLHttpRequest(); + baseRequester.open(request.method, request.url, true); + Object.keys(request.headers).forEach(key => baseRequester.setRequestHeader(key, request.headers[key])); + const createTimeout = (timeout, content) => { + return setTimeout(() => { + baseRequester.abort(); + resolve({ + status: 0, + content, + isTimedOut: true, + }); + }, timeout * 1000); + }; + const connectTimeout = createTimeout(request.connectTimeout, 'Connection timeout'); + // eslint-disable-next-line functional/no-let + let responseTimeout; + // eslint-disable-next-line functional/immutable-data + baseRequester.onreadystatechange = () => { + if (baseRequester.readyState > baseRequester.OPENED && responseTimeout === undefined) { + clearTimeout(connectTimeout); + responseTimeout = createTimeout(request.responseTimeout, 'Socket timeout'); + } + }; + // eslint-disable-next-line functional/immutable-data + baseRequester.onerror = () => { + // istanbul ignore next + if (baseRequester.status === 0) { + clearTimeout(connectTimeout); + clearTimeout(responseTimeout); + resolve({ + content: baseRequester.responseText || 'Network request failed', + status: baseRequester.status, + isTimedOut: false, + }); + } + }; + // eslint-disable-next-line functional/immutable-data + baseRequester.onload = () => { + clearTimeout(connectTimeout); + clearTimeout(responseTimeout); + resolve({ + content: baseRequester.responseText, + status: baseRequester.status, + isTimedOut: false, + }); + }; + baseRequester.send(request.data); + }); + }, + }; +} + +function createMappedRequestOptions(requestOptions, timeout) { + const options = requestOptions || {}; + const data = options.data || {}; + Object.keys(options).forEach(key => { + if (['timeout', 'headers', 'queryParameters', 'data', 'cacheable'].indexOf(key) === -1) { + data[key] = options[key]; // eslint-disable-line functional/immutable-data + } + }); + return { + data: Object.entries(data).length > 0 ? data : undefined, + timeout: options.timeout || timeout, + headers: options.headers || {}, + queryParameters: options.queryParameters || {}, + cacheable: options.cacheable, + }; +} + +const CallEnum = { + /** + * If the host is read only. + */ + Read: 1, + /** + * If the host is write only. + */ + Write: 2, + /** + * If the host is both read and write. + */ + Any: 3, +}; + +const HostStatusEnum = { + Up: 1, + Down: 2, + Timeouted: 3, +}; + +// By default, API Clients at Algolia have expiration delay +// of 5 mins. In the JavaScript client, we have 2 mins. +const EXPIRATION_DELAY = 2 * 60 * 1000; +function createStatefulHost(host, status = HostStatusEnum.Up) { + return { + ...host, + status, + lastUpdate: Date.now(), + }; +} +function isStatefulHostUp(host) { + return host.status === HostStatusEnum.Up || Date.now() - host.lastUpdate > EXPIRATION_DELAY; +} +function isStatefulHostTimeouted(host) { + return (host.status === HostStatusEnum.Timeouted && Date.now() - host.lastUpdate <= EXPIRATION_DELAY); +} + +function createStatelessHost(options) { + if (typeof options === 'string') { + return { + protocol: 'https', + url: options, + accept: CallEnum.Any, + }; + } + return { + protocol: options.protocol || 'https', + url: options.url, + accept: options.accept || CallEnum.Any, + }; +} + +const MethodEnum = { + Delete: 'DELETE', + Get: 'GET', + Post: 'POST', + Put: 'PUT', +}; + +function createRetryableOptions(hostsCache, statelessHosts) { + return Promise.all(statelessHosts.map(statelessHost => { + return hostsCache.get(statelessHost, () => { + return Promise.resolve(createStatefulHost(statelessHost)); + }); + })).then(statefulHosts => { + const hostsUp = statefulHosts.filter(host => isStatefulHostUp(host)); + const hostsTimeouted = statefulHosts.filter(host => isStatefulHostTimeouted(host)); + /** + * Note, we put the hosts that previously timeouted on the end of the list. + */ + const hostsAvailable = [...hostsUp, ...hostsTimeouted]; + const statelessHostsAvailable = hostsAvailable.length > 0 + ? hostsAvailable.map(host => createStatelessHost(host)) + : statelessHosts; + return { + getTimeout(timeoutsCount, baseTimeout) { + /** + * Imagine that you have 4 hosts, if timeouts will increase + * on the following way: 1 (timeouted) > 4 (timeouted) > 5 (200) + * + * Note that, the very next request, we start from the previous timeout + * + * 5 (timeouted) > 6 (timeouted) > 7 ... + * + * This strategy may need to be reviewed, but is the strategy on the our + * current v3 version. + */ + const timeoutMultiplier = hostsTimeouted.length === 0 && timeoutsCount === 0 + ? 1 + : hostsTimeouted.length + 3 + timeoutsCount; + return timeoutMultiplier * baseTimeout; + }, + statelessHosts: statelessHostsAvailable, + }; + }); +} + +const isNetworkError = ({ isTimedOut, status }) => { + return !isTimedOut && ~~status === 0; +}; +const isRetryable = (response) => { + const status = response.status; + const isTimedOut = response.isTimedOut; + return (isTimedOut || isNetworkError(response) || (~~(status / 100) !== 2 && ~~(status / 100) !== 4)); +}; +const isSuccess = ({ status }) => { + return ~~(status / 100) === 2; +}; +const retryDecision = (response, outcomes) => { + if (isRetryable(response)) { + return outcomes.onRetry(response); + } + if (isSuccess(response)) { + return outcomes.onSuccess(response); + } + return outcomes.onFail(response); +}; + +function retryableRequest(transporter, statelessHosts, request, requestOptions) { + const stackTrace = []; // eslint-disable-line functional/prefer-readonly-type + /** + * First we prepare the payload that do not depend from hosts. + */ + const data = serializeData(request, requestOptions); + const headers = serializeHeaders(transporter, requestOptions); + const method = request.method; + // On `GET`, the data is proxied to query parameters. + const dataQueryParameters = request.method !== MethodEnum.Get + ? {} + : { + ...request.data, + ...requestOptions.data, + }; + const queryParameters = { + 'x-algolia-agent': transporter.userAgent.value, + ...transporter.queryParameters, + ...dataQueryParameters, + ...requestOptions.queryParameters, + }; + let timeoutsCount = 0; // eslint-disable-line functional/no-let + const retry = (hosts, // eslint-disable-line functional/prefer-readonly-type + getTimeout) => { + /** + * We iterate on each host, until there is no host left. + */ + const host = hosts.pop(); // eslint-disable-line functional/immutable-data + if (host === undefined) { + throw createRetryError(stackTraceWithoutCredentials(stackTrace)); + } + const payload = { + data, + headers, + method, + url: serializeUrl(host, request.path, queryParameters), + connectTimeout: getTimeout(timeoutsCount, transporter.timeouts.connect), + responseTimeout: getTimeout(timeoutsCount, requestOptions.timeout), + }; + /** + * The stackFrame is pushed to the stackTrace so we + * can have information about onRetry and onFailure + * decisions. + */ + const pushToStackTrace = (response) => { + const stackFrame = { + request: payload, + response, + host, + triesLeft: hosts.length, + }; + // eslint-disable-next-line functional/immutable-data + stackTrace.push(stackFrame); + return stackFrame; + }; + const decisions = { + onSuccess: response => deserializeSuccess(response), + onRetry(response) { + const stackFrame = pushToStackTrace(response); + /** + * If response is a timeout, we increaset the number of + * timeouts so we can increase the timeout later. + */ + if (response.isTimedOut) { + timeoutsCount++; + } + return Promise.all([ + /** + * Failures are individually send the logger, allowing + * the end user to debug / store stack frames even + * when a retry error does not happen. + */ + transporter.logger.info('Retryable failure', stackFrameWithoutCredentials(stackFrame)), + /** + * We also store the state of the host in failure cases. If the host, is + * down it will remain down for the next 2 minutes. In a timeout situation, + * this host will be added end of the list of hosts on the next request. + */ + transporter.hostsCache.set(host, createStatefulHost(host, response.isTimedOut ? HostStatusEnum.Timeouted : HostStatusEnum.Down)), + ]).then(() => retry(hosts, getTimeout)); + }, + onFail(response) { + pushToStackTrace(response); + throw deserializeFailure(response, stackTraceWithoutCredentials(stackTrace)); + }, + }; + return transporter.requester.send(payload).then(response => { + return retryDecision(response, decisions); + }); + }; + /** + * Finally, for each retryable host perform request until we got a non + * retryable response. Some notes here: + * + * 1. The reverse here is applied so we can apply a `pop` later on => more performant. + * 2. We also get from the retryable options a timeout multiplier that is tailored + * for the current context. + */ + return createRetryableOptions(transporter.hostsCache, statelessHosts).then(options => { + return retry([...options.statelessHosts].reverse(), options.getTimeout); + }); +} + +function createTransporter(options) { + const { hostsCache, logger, requester, requestsCache, responsesCache, timeouts, userAgent, hosts, queryParameters, headers, } = options; + const transporter = { + hostsCache, + logger, + requester, + requestsCache, + responsesCache, + timeouts, + userAgent, + headers, + queryParameters, + hosts: hosts.map(host => createStatelessHost(host)), + read(request, requestOptions) { + /** + * First, we compute the user request options. Now, keep in mind, + * that using request options the user is able to modified the intire + * payload of the request. Such as headers, query parameters, and others. + */ + const mappedRequestOptions = createMappedRequestOptions(requestOptions, transporter.timeouts.read); + const createRetryableRequest = () => { + /** + * Then, we prepare a function factory that contains the construction of + * the retryable request. At this point, we may *not* perform the actual + * request. But we want to have the function factory ready. + */ + return retryableRequest(transporter, transporter.hosts.filter(host => (host.accept & CallEnum.Read) !== 0), request, mappedRequestOptions); + }; + /** + * Once we have the function factory ready, we need to determine of the + * request is "cacheable" - should be cached. Note that, once again, + * the user can force this option. + */ + const cacheable = mappedRequestOptions.cacheable !== undefined + ? mappedRequestOptions.cacheable + : request.cacheable; + /** + * If is not "cacheable", we immediatly trigger the retryable request, no + * need to check cache implementations. + */ + if (cacheable !== true) { + return createRetryableRequest(); + } + /** + * If the request is "cacheable", we need to first compute the key to ask + * the cache implementations if this request is on progress or if the + * response already exists on the cache. + */ + const key = { + request, + mappedRequestOptions, + transporter: { + queryParameters: transporter.queryParameters, + headers: transporter.headers, + }, + }; + /** + * With the computed key, we first ask the responses cache + * implemention if this request was been resolved before. + */ + return transporter.responsesCache.get(key, () => { + /** + * If the request has never resolved before, we actually ask if there + * is a current request with the same key on progress. + */ + return transporter.requestsCache.get(key, () => { + return (transporter.requestsCache + /** + * Finally, if there is no request in progress with the same key, + * this `createRetryableRequest()` will actually trigger the + * retryable request. + */ + .set(key, createRetryableRequest()) + .then(response => Promise.all([transporter.requestsCache.delete(key), response]), err => Promise.all([transporter.requestsCache.delete(key), Promise.reject(err)])) + .then(([_, response]) => response)); + }); + }, { + /** + * Of course, once we get this response back from the server, we + * tell response cache to actually store the received response + * to be used later. + */ + miss: response => transporter.responsesCache.set(key, response), + }); + }, + write(request, requestOptions) { + /** + * On write requests, no cache mechanisms are applied, and we + * proxy the request immediately to the requester. + */ + return retryableRequest(transporter, transporter.hosts.filter(host => (host.accept & CallEnum.Write) !== 0), request, createMappedRequestOptions(requestOptions, transporter.timeouts.write)); + }, + }; + return transporter; +} + +function createUserAgent(version) { + const userAgent = { + value: `Algolia for JavaScript (${version})`, + add(options) { + const addedUserAgent = `; ${options.segment}${options.version !== undefined ? ` (${options.version})` : ''}`; + if (userAgent.value.indexOf(addedUserAgent) === -1) { + // eslint-disable-next-line functional/immutable-data + userAgent.value = `${userAgent.value}${addedUserAgent}`; + } + return userAgent; + }, + }; + return userAgent; +} + +function deserializeSuccess(response) { + // eslint-disable-next-line functional/no-try-statement + try { + return JSON.parse(response.content); + } + catch (e) { + throw createDeserializationError(e.message, response); + } +} +function deserializeFailure({ content, status }, stackFrame) { + // eslint-disable-next-line functional/no-let + let message = content; + // eslint-disable-next-line functional/no-try-statement + try { + message = JSON.parse(content).message; + } + catch (e) { + // .. + } + return createApiError(message, status, stackFrame); +} + +function serializeUrl(host, path, queryParameters) { + const queryParametersAsString = serializeQueryParameters(queryParameters); + // eslint-disable-next-line functional/no-let + let url = `${host.protocol}://${host.url}/${path.charAt(0) === '/' ? path.substr(1) : path}`; + if (queryParametersAsString.length) { + url += `?${queryParametersAsString}`; + } + return url; +} +function serializeQueryParameters(parameters) { + const isObjectOrArray = (value) => Object.prototype.toString.call(value) === '[object Object]' || + Object.prototype.toString.call(value) === '[object Array]'; + return Object.keys(parameters) + .map(key => encode('%s=%s', key, isObjectOrArray(parameters[key]) ? JSON.stringify(parameters[key]) : parameters[key])) + .join('&'); +} +function serializeData(request, requestOptions) { + if (request.method === MethodEnum.Get || + (request.data === undefined && requestOptions.data === undefined)) { + return undefined; + } + const data = Array.isArray(request.data) + ? request.data + : { ...request.data, ...requestOptions.data }; + return JSON.stringify(data); +} +function serializeHeaders(transporter, requestOptions) { + const headers = { + ...transporter.headers, + ...requestOptions.headers, + }; + const serializedHeaders = {}; + Object.keys(headers).forEach(header => { + const value = headers[header]; + // @ts-ignore + // eslint-disable-next-line functional/immutable-data + serializedHeaders[header.toLowerCase()] = value; + }); + return serializedHeaders; +} + +function stackTraceWithoutCredentials(stackTrace) { + return stackTrace.map(stackFrame => stackFrameWithoutCredentials(stackFrame)); +} +function stackFrameWithoutCredentials(stackFrame) { + const modifiedHeaders = stackFrame.request.headers['x-algolia-api-key'] + ? { 'x-algolia-api-key': '*****' } + : {}; + return { + ...stackFrame, + request: { + ...stackFrame.request, + headers: { + ...stackFrame.request.headers, + ...modifiedHeaders, + }, + }, + }; +} + +function createApiError(message, status, transporterStackTrace) { + return { + name: 'ApiError', + message, + status, + transporterStackTrace, + }; +} + +function createDeserializationError(message, response) { + return { + name: 'DeserializationError', + message, + response, + }; +} + +function createRetryError(transporterStackTrace) { + return { + name: 'RetryError', + message: 'Unreachable hosts - your application id may be incorrect. If the error persists, please reach out to the Algolia Support team: https://alg.li/support .', + transporterStackTrace, + }; +} + +const createRecommendClient = options => { + const appId = options.appId; + const auth = createAuth(options.authMode !== undefined ? options.authMode : AuthMode.WithinHeaders, appId, options.apiKey); + const transporter = createTransporter({ + hosts: [ + { url: `${appId}-dsn.algolia.net`, accept: CallEnum.Read }, + { url: `${appId}.algolia.net`, accept: CallEnum.Write }, + ].concat(shuffle([ + { url: `${appId}-1.algolianet.com` }, + { url: `${appId}-2.algolianet.com` }, + { url: `${appId}-3.algolianet.com` }, + ])), + ...options, + headers: { + ...auth.headers(), + ...{ 'content-type': 'application/x-www-form-urlencoded' }, + ...options.headers, + }, + queryParameters: { + ...auth.queryParameters(), + ...options.queryParameters, + }, + }); + const base = { + transporter, + appId, + addAlgoliaAgent(segment, version) { + transporter.userAgent.add({ segment, version }); + }, + clearCache() { + return Promise.all([ + transporter.requestsCache.clear(), + transporter.responsesCache.clear(), + ]).then(() => undefined); + }, + }; + return addMethods(base, options.methods); +}; + +const getRecommendations = base => { + return (queries, requestOptions) => { + const requests = queries.map(query => ({ + ...query, + // The `threshold` param is required by the endpoint to make it easier + // to provide a default value later, so we default it in the client + // so that users don't have to provide a value. + threshold: query.threshold || 0, + })); + return base.transporter.read({ + method: MethodEnum.Post, + path: '1/indexes/*/recommendations', + data: { + requests, + }, + cacheable: true, + }, requestOptions); + }; +}; + +const getFrequentlyBoughtTogether = base => { + return (queries, requestOptions) => { + return getRecommendations(base)(queries.map(query => ({ + ...query, + fallbackParameters: {}, + model: 'bought-together', + })), requestOptions); + }; +}; + +const getRelatedProducts = base => { + return (queries, requestOptions) => { + return getRecommendations(base)(queries.map(query => ({ + ...query, + model: 'related-products', + })), requestOptions); + }; +}; + +const getTrendingFacets = base => { + return (queries, requestOptions) => { + const requests = queries.map(query => ({ + ...query, + model: 'trending-facets', + // The `threshold` param is required by the endpoint to make it easier + // to provide a default value later, so we default it in the client + // so that users don't have to provide a value. + threshold: query.threshold || 0, + })); + return base.transporter.read({ + method: MethodEnum.Post, + path: '1/indexes/*/recommendations', + data: { + requests, + }, + cacheable: true, + }, requestOptions); + }; +}; + +const getTrendingItems = base => { + return (queries, requestOptions) => { + const requests = queries.map(query => ({ + ...query, + model: 'trending-items', + // The `threshold` param is required by the endpoint to make it easier + // to provide a default value later, so we default it in the client + // so that users don't have to provide a value. + threshold: query.threshold || 0, + })); + return base.transporter.read({ + method: MethodEnum.Post, + path: '1/indexes/*/recommendations', + data: { + requests, + }, + cacheable: true, + }, requestOptions); + }; +}; + +const getLookingSimilar = base => { + return (queries, requestOptions) => { + return getRecommendations(base)(queries.map(query => ({ + ...query, + model: 'looking-similar', + })), requestOptions); + }; +}; + +const getRecommendedForYou = base => { + return (queries, requestOptions) => { + const requests = queries.map(query => ({ + ...query, + model: 'recommended-for-you', + threshold: query.threshold || 0, + })); + return base.transporter.read({ + method: MethodEnum.Post, + path: '1/indexes/*/recommendations', + data: { + requests, + }, + cacheable: true, + }, requestOptions); + }; +}; + +function recommend(appId, apiKey, options) { + const commonOptions = { + appId, + apiKey, + timeouts: { + connect: 1, + read: 2, + write: 30, + }, + requester: createBrowserXhrRequester(), + logger: createConsoleLogger(LogLevelEnum.Error), + responsesCache: createInMemoryCache(), + requestsCache: createInMemoryCache({ serializable: false }), + hostsCache: createFallbackableCache({ + caches: [ + createBrowserLocalStorageCache({ key: `${version}-${appId}` }), + createInMemoryCache(), + ], + }), + userAgent: createUserAgent(version) + .add({ segment: 'Recommend', version }) + .add({ segment: 'Browser' }), + authMode: AuthMode.WithinQueryParameters, + }; + return createRecommendClient({ + ...commonOptions, + ...options, + methods: { + getFrequentlyBoughtTogether, + getRecommendations, + getRelatedProducts, + getTrendingFacets, + getTrendingItems, + getLookingSimilar, + getRecommendedForYou, + }, + }); +} +/* eslint-disable functional/immutable-data */ +recommend.version = version; +recommend.getFrequentlyBoughtTogether = getFrequentlyBoughtTogether; +recommend.getRecommendations = getRecommendations; +recommend.getRelatedProducts = getRelatedProducts; +recommend.getTrendingFacets = getTrendingFacets; +recommend.getTrendingItems = getTrendingItems; +recommend.getLookingSimilar = getLookingSimilar; +recommend.getRecommendedForYou = getRecommendedForYou; + +export default recommend; diff --git a/scripts/node_modules/@algolia/recommend/dist/recommend.umd.js b/scripts/node_modules/@algolia/recommend/dist/recommend.umd.js new file mode 100644 index 000000000..e1e824d64 --- /dev/null +++ b/scripts/node_modules/@algolia/recommend/dist/recommend.umd.js @@ -0,0 +1,2 @@ +/*! recommend.umd.js | 4.24.0 | © Algolia, inc. | https://github.com/algolia/algoliasearch-client-javascript */ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self)["@algolia/recommend"]=t()}(this,(function(){"use strict";function e(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function t(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function r(r){for(var n=1;n2&&void 0!==arguments[2]?arguments[2]:{miss:function(){return Promise.resolve()}};return Promise.resolve().then((function(){u();var t=JSON.stringify(e);return a()[t]})).then((function(e){return Promise.all([e?e.value:t(),void 0!==e])})).then((function(e){var t=n(e,2),o=t[0],a=t[1];return Promise.all([o,a||r.miss(o)])})).then((function(e){return n(e,1)[0]}))},set:function(e,t){return Promise.resolve().then((function(){var n=a();return n[JSON.stringify(e)]={timestamp:(new Date).getTime(),value:t},o().setItem(r,JSON.stringify(n)),t}))},delete:function(e){return Promise.resolve().then((function(){var t=a();delete t[JSON.stringify(e)],o().setItem(r,JSON.stringify(t))}))},clear:function(){return Promise.resolve().then((function(){o().removeItem(r)}))}}}function i(e){var t=o(e.caches),r=t.shift();return void 0===r?{get:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{miss:function(){return Promise.resolve()}},o=t();return o.then((function(e){return Promise.all([e,r.miss(e)])})).then((function(e){return n(e,1)[0]}))},set:function(e,t){return Promise.resolve(t)},delete:function(e){return Promise.resolve()},clear:function(){return Promise.resolve()}}:{get:function(e,n){var o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{miss:function(){return Promise.resolve()}};return r.get(e,n,o).catch((function(){return i({caches:t}).get(e,n,o)}))},set:function(e,n){return r.set(e,n).catch((function(){return i({caches:t}).set(e,n)}))},delete:function(e){return r.delete(e).catch((function(){return i({caches:t}).delete(e)}))},clear:function(){return r.clear().catch((function(){return i({caches:t}).clear()}))}}}function u(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{serializable:!0},t={};return{get:function(r,n){var o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{miss:function(){return Promise.resolve()}},a=JSON.stringify(r);if(a in t)return Promise.resolve(e.serializable?JSON.parse(t[a]):t[a]);var i=n(),u=o&&o.miss||function(){return Promise.resolve()};return i.then((function(e){return u(e)})).then((function(){return i}))},set:function(r,n){return t[JSON.stringify(r)]=e.serializable?JSON.stringify(n):n,Promise.resolve(n)},delete:function(e){return delete t[JSON.stringify(e)],Promise.resolve()},clear:function(){return t={},Promise.resolve()}}}function s(e){for(var t=e.length-1;t>0;t--){var r=Math.floor(Math.random()*(t+1)),n=e[t];e[t]=e[r],e[r]=n}return e}var c={WithinQueryParameters:0,WithinHeaders:1},l=1,f=2,m=3;function d(e,t){var r=e||{},n=r.data||{};return Object.keys(r).forEach((function(e){-1===["timeout","headers","queryParameters","data","cacheable"].indexOf(e)&&(n[e]=r[e])})),{data:Object.entries(n).length>0?n:void 0,timeout:r.timeout||t,headers:r.headers||{},queryParameters:r.queryParameters||{},cacheable:r.cacheable}}var h={Read:1,Write:2,Any:3},p=1,g=2,v=3;function y(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:p;return r(r({},e),{},{status:t,lastUpdate:Date.now()})}function b(e){return"string"==typeof e?{protocol:"https",url:e,accept:h.Any}:{protocol:e.protocol||"https",url:e.url,accept:e.accept||h.Any}}var O="GET",P="POST";function q(e,t){return Promise.all(t.map((function(t){return e.get(t,(function(){return Promise.resolve(y(t))}))}))).then((function(e){var r=e.filter((function(e){return function(e){return e.status===p||Date.now()-e.lastUpdate>12e4}(e)})),n=e.filter((function(e){return function(e){return e.status===v&&Date.now()-e.lastUpdate<=12e4}(e)})),a=[].concat(o(r),o(n));return{getTimeout:function(e,t){return(0===n.length&&0===e?1:n.length+3+e)*t},statelessHosts:a.length>0?a.map((function(e){return b(e)})):t}}))}function S(e,t,n,a){var i=[],u=function(e,t){if(e.method===O||void 0===e.data&&void 0===t.data)return;var n=Array.isArray(e.data)?e.data:r(r({},e.data),t.data);return JSON.stringify(n)}(n,a),s=function(e,t){var n=r(r({},e.headers),t.headers),o={};return Object.keys(n).forEach((function(e){var t=n[e];o[e.toLowerCase()]=t})),o}(e,a),c=n.method,l=n.method!==O?{}:r(r({},n.data),a.data),f=r(r(r({"x-algolia-agent":e.userAgent.value},e.queryParameters),l),a.queryParameters),m=0,d=function t(r,o){var l=r.pop();if(void 0===l)throw{name:"RetryError",message:"Unreachable hosts - your application id may be incorrect. If the error persists, please reach out to the Algolia Support team: https://alg.li/support .",transporterStackTrace:w(i)};var d={data:u,headers:s,method:c,url:T(l,n.path,f),connectTimeout:o(m,e.timeouts.connect),responseTimeout:o(m,a.timeout)},h=function(e){var t={request:d,response:e,host:l,triesLeft:r.length};return i.push(t),t},p={onSuccess:function(e){return function(e){try{return JSON.parse(e.content)}catch(t){throw function(e,t){return{name:"DeserializationError",message:e,response:t}}(t.message,e)}}(e)},onRetry:function(n){var a=h(n);return n.isTimedOut&&m++,Promise.all([e.logger.info("Retryable failure",A(a)),e.hostsCache.set(l,y(l,n.isTimedOut?v:g))]).then((function(){return t(r,o)}))},onFail:function(e){throw h(e),function(e,t){var r=e.content,n=e.status,o=r;try{o=JSON.parse(r).message}catch(e){}return function(e,t,r){return{name:"ApiError",message:e,status:t,transporterStackTrace:r}}(o,n,t)}(e,w(i))}};return e.requester.send(d).then((function(e){return function(e,t){return function(e){var t=e.status;return e.isTimedOut||function(e){var t=e.isTimedOut,r=e.status;return!t&&0==~~r}(e)||2!=~~(t/100)&&4!=~~(t/100)}(e)?t.onRetry(e):2==~~(e.status/100)?t.onSuccess(e):t.onFail(e)}(e,p)}))};return q(e.hostsCache,t).then((function(e){return d(o(e.statelessHosts).reverse(),e.getTimeout)}))}function j(e){var t={value:"Algolia for JavaScript (".concat(e,")"),add:function(e){var r="; ".concat(e.segment).concat(void 0!==e.version?" (".concat(e.version,")"):"");return-1===t.value.indexOf(r)&&(t.value="".concat(t.value).concat(r)),t}};return t}function T(e,t,r){var n,o=(n=r,Object.keys(n).map((function(e){return function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;nr.OPENED&&void 0===n&&(clearTimeout(a),n=o(e.responseTimeout,"Socket timeout"))},r.onerror=function(){0===r.status&&(clearTimeout(a),clearTimeout(n),t({content:r.responseText||"Network request failed",status:r.status,isTimedOut:!1}))},r.onload=function(){clearTimeout(a),clearTimeout(n),t({content:r.responseText,status:r.status,isTimedOut:!1})},r.send(e.data)}))}},logger:(o=m,{debug:function(e,t){return l>=o&&console.debug(e,t),Promise.resolve()},info:function(e,t){return f>=o&&console.info(e,t),Promise.resolve()},error:function(e,t){return console.error(e,t),Promise.resolve()}}),responsesCache:u(),requestsCache:u({serializable:!1}),hostsCache:i({caches:[a({key:"".concat("4.24.0","-").concat(e)}),u()]}),userAgent:j("4.24.0").add({segment:"Recommend",version:"4.24.0"}).add({segment:"Browser"}),authMode:c.WithinQueryParameters};return C(r(r(r({},s),n),{},{methods:{getFrequentlyBoughtTogether:N,getRecommendations:k,getRelatedProducts:R,getTrendingFacets:x,getTrendingItems:J,getLookingSimilar:E,getRecommendedForYou:I}}))}return D.version="4.24.0",D.getFrequentlyBoughtTogether=N,D.getRecommendations=k,D.getRelatedProducts=R,D.getTrendingFacets=x,D.getTrendingItems=J,D.getLookingSimilar=E,D.getRecommendedForYou=I,D})); diff --git a/scripts/node_modules/@algolia/recommend/index.d.ts b/scripts/node_modules/@algolia/recommend/index.d.ts new file mode 100644 index 000000000..70d1e5942 --- /dev/null +++ b/scripts/node_modules/@algolia/recommend/index.d.ts @@ -0,0 +1,3 @@ +/* eslint-disable import/no-unresolved*/ +export * from './dist/recommend'; +export { default } from './dist/recommend'; diff --git a/scripts/node_modules/@algolia/recommend/index.js b/scripts/node_modules/@algolia/recommend/index.js new file mode 100644 index 000000000..8122c2480 --- /dev/null +++ b/scripts/node_modules/@algolia/recommend/index.js @@ -0,0 +1,15 @@ +/* eslint-disable functional/immutable-data, import/no-commonjs */ +const recommend = require('./dist/recommend.cjs.js'); + +/** + * The Common JS build is the default entry point for the Node environment. Keep in + * in mind, that for the browser environment, we hint the bundler to use the UMD + * build instead as specified on the key `browser` of our `package.json` file. + */ +module.exports = recommend; + +/** + * In addition, we also set explicitly the default export below making + * this Common JS module in compliance with es6 modules specification. + */ +module.exports.default = recommend; diff --git a/scripts/node_modules/@algolia/recommend/package.json b/scripts/node_modules/@algolia/recommend/package.json new file mode 100644 index 000000000..bc084b5d1 --- /dev/null +++ b/scripts/node_modules/@algolia/recommend/package.json @@ -0,0 +1,40 @@ +{ + "name": "@algolia/recommend", + "version": "4.24.0", + "private": false, + "description": "The perfect starting point to integrate Algolia Recommend within your JavaScript project.", + "repository": { + "type": "git", + "url": "git://github.com/algolia/algoliasearch-client-javascript.git" + }, + "license": "MIT", + "sideEffects": false, + "main": "index.js", + "jsdelivr": "./dist/recommend.umd.js", + "unpkg": "./dist/recommend.umd.js", + "browser": { + "./index.js": "./dist/recommend.umd.js" + }, + "types": "index.d.ts", + "files": [ + "dist", + "index.js", + "index.d.ts" + ], + "scripts": { + "test:exports": "node --experimental-modules test/module/is-es-module.mjs && node test/module/is-cjs-module.cjs" + }, + "dependencies": { + "@algolia/cache-browser-local-storage": "4.24.0", + "@algolia/cache-common": "4.24.0", + "@algolia/cache-in-memory": "4.24.0", + "@algolia/client-common": "4.24.0", + "@algolia/client-search": "4.24.0", + "@algolia/logger-common": "4.24.0", + "@algolia/logger-console": "4.24.0", + "@algolia/requester-browser-xhr": "4.24.0", + "@algolia/requester-common": "4.24.0", + "@algolia/requester-node-http": "4.24.0", + "@algolia/transporter": "4.24.0" + } +} diff --git a/scripts/node_modules/@algolia/requester-browser-xhr/dist/requester-browser-xhr.cjs.js b/scripts/node_modules/@algolia/requester-browser-xhr/dist/requester-browser-xhr.cjs.js new file mode 100644 index 000000000..4c4465f3f --- /dev/null +++ b/scripts/node_modules/@algolia/requester-browser-xhr/dist/requester-browser-xhr.cjs.js @@ -0,0 +1,61 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +function createBrowserXhrRequester() { + return { + send(request) { + return new Promise((resolve) => { + const baseRequester = new XMLHttpRequest(); + baseRequester.open(request.method, request.url, true); + Object.keys(request.headers).forEach(key => baseRequester.setRequestHeader(key, request.headers[key])); + const createTimeout = (timeout, content) => { + return setTimeout(() => { + baseRequester.abort(); + resolve({ + status: 0, + content, + isTimedOut: true, + }); + }, timeout * 1000); + }; + const connectTimeout = createTimeout(request.connectTimeout, 'Connection timeout'); + // eslint-disable-next-line functional/no-let + let responseTimeout; + // eslint-disable-next-line functional/immutable-data + baseRequester.onreadystatechange = () => { + if (baseRequester.readyState > baseRequester.OPENED && responseTimeout === undefined) { + clearTimeout(connectTimeout); + responseTimeout = createTimeout(request.responseTimeout, 'Socket timeout'); + } + }; + // eslint-disable-next-line functional/immutable-data + baseRequester.onerror = () => { + // istanbul ignore next + if (baseRequester.status === 0) { + clearTimeout(connectTimeout); + clearTimeout(responseTimeout); + resolve({ + content: baseRequester.responseText || 'Network request failed', + status: baseRequester.status, + isTimedOut: false, + }); + } + }; + // eslint-disable-next-line functional/immutable-data + baseRequester.onload = () => { + clearTimeout(connectTimeout); + clearTimeout(responseTimeout); + resolve({ + content: baseRequester.responseText, + status: baseRequester.status, + isTimedOut: false, + }); + }; + baseRequester.send(request.data); + }); + }, + }; +} + +exports.createBrowserXhrRequester = createBrowserXhrRequester; diff --git a/scripts/node_modules/@algolia/requester-browser-xhr/dist/requester-browser-xhr.d.ts b/scripts/node_modules/@algolia/requester-browser-xhr/dist/requester-browser-xhr.d.ts new file mode 100644 index 000000000..5e50a32e3 --- /dev/null +++ b/scripts/node_modules/@algolia/requester-browser-xhr/dist/requester-browser-xhr.d.ts @@ -0,0 +1,5 @@ +import { Requester } from '@algolia/requester-common'; + +export declare function createBrowserXhrRequester(): Requester; + +export { } diff --git a/scripts/node_modules/@algolia/requester-browser-xhr/dist/requester-browser-xhr.esm.js b/scripts/node_modules/@algolia/requester-browser-xhr/dist/requester-browser-xhr.esm.js new file mode 100644 index 000000000..55e444788 --- /dev/null +++ b/scripts/node_modules/@algolia/requester-browser-xhr/dist/requester-browser-xhr.esm.js @@ -0,0 +1,57 @@ +function createBrowserXhrRequester() { + return { + send(request) { + return new Promise((resolve) => { + const baseRequester = new XMLHttpRequest(); + baseRequester.open(request.method, request.url, true); + Object.keys(request.headers).forEach(key => baseRequester.setRequestHeader(key, request.headers[key])); + const createTimeout = (timeout, content) => { + return setTimeout(() => { + baseRequester.abort(); + resolve({ + status: 0, + content, + isTimedOut: true, + }); + }, timeout * 1000); + }; + const connectTimeout = createTimeout(request.connectTimeout, 'Connection timeout'); + // eslint-disable-next-line functional/no-let + let responseTimeout; + // eslint-disable-next-line functional/immutable-data + baseRequester.onreadystatechange = () => { + if (baseRequester.readyState > baseRequester.OPENED && responseTimeout === undefined) { + clearTimeout(connectTimeout); + responseTimeout = createTimeout(request.responseTimeout, 'Socket timeout'); + } + }; + // eslint-disable-next-line functional/immutable-data + baseRequester.onerror = () => { + // istanbul ignore next + if (baseRequester.status === 0) { + clearTimeout(connectTimeout); + clearTimeout(responseTimeout); + resolve({ + content: baseRequester.responseText || 'Network request failed', + status: baseRequester.status, + isTimedOut: false, + }); + } + }; + // eslint-disable-next-line functional/immutable-data + baseRequester.onload = () => { + clearTimeout(connectTimeout); + clearTimeout(responseTimeout); + resolve({ + content: baseRequester.responseText, + status: baseRequester.status, + isTimedOut: false, + }); + }; + baseRequester.send(request.data); + }); + }, + }; +} + +export { createBrowserXhrRequester }; diff --git a/scripts/node_modules/@algolia/requester-browser-xhr/index.js b/scripts/node_modules/@algolia/requester-browser-xhr/index.js new file mode 100644 index 000000000..bc56b3262 --- /dev/null +++ b/scripts/node_modules/@algolia/requester-browser-xhr/index.js @@ -0,0 +1,2 @@ +// eslint-disable-next-line functional/immutable-data, import/no-commonjs +module.exports = require('./dist/requester-browser-xhr.cjs.js'); diff --git a/scripts/node_modules/@algolia/requester-browser-xhr/package.json b/scripts/node_modules/@algolia/requester-browser-xhr/package.json new file mode 100644 index 000000000..7267859e5 --- /dev/null +++ b/scripts/node_modules/@algolia/requester-browser-xhr/package.json @@ -0,0 +1,22 @@ +{ + "name": "@algolia/requester-browser-xhr", + "version": "4.24.0", + "private": false, + "description": "Promise-based request library for browser using xhr.", + "repository": { + "type": "git", + "url": "git://github.com/algolia/algoliasearch-client-javascript.git" + }, + "license": "MIT", + "sideEffects": false, + "main": "index.js", + "module": "dist/requester-browser-xhr.esm.js", + "types": "dist/requester-browser-xhr.d.ts", + "files": [ + "index.js", + "dist" + ], + "dependencies": { + "@algolia/requester-common": "4.24.0" + } +} diff --git a/scripts/node_modules/@algolia/requester-common/dist/requester-common.cjs.js b/scripts/node_modules/@algolia/requester-common/dist/requester-common.cjs.js new file mode 100644 index 000000000..9655a02eb --- /dev/null +++ b/scripts/node_modules/@algolia/requester-common/dist/requester-common.cjs.js @@ -0,0 +1,12 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +const MethodEnum = { + Delete: 'DELETE', + Get: 'GET', + Post: 'POST', + Put: 'PUT', +}; + +exports.MethodEnum = MethodEnum; diff --git a/scripts/node_modules/@algolia/requester-common/dist/requester-common.d.ts b/scripts/node_modules/@algolia/requester-common/dist/requester-common.d.ts new file mode 100644 index 000000000..4fd79cb21 --- /dev/null +++ b/scripts/node_modules/@algolia/requester-common/dist/requester-common.d.ts @@ -0,0 +1,67 @@ +export declare type Destroyable = { + /** + * Destroy any sockets that are currently in use by the agent. + * + * It is usually not necessary to do this. However, if using an agent with keepAlive enabled, then + * it is best to explicitly shut down the agent when it will no longer be used. Otherwise, sockets + * may hang open for quite a long time before the server terminates them. + */ + readonly destroy: () => Readonly>; +}; + +export declare const MethodEnum: Readonly>; + +export declare type MethodType = 'DELETE' | 'GET' | 'POST' | 'PUT'; + +declare type Request_2 = { + /** + * The headers of the request. + */ + readonly headers: Readonly>; + /** + * The method of the request. `GET`, etc. + */ + readonly method: MethodType; + /** + * The complete url of the request, with the protocol. + */ + readonly url: string; + /** + * The timeout to stablish a connection with the server. + */ + readonly connectTimeout: number; + /** + * The timeout to receive the response. + */ + readonly responseTimeout: number; + /** + * The data to be transfered to the server. + */ + readonly data: string | undefined; +}; +export { Request_2 as Request } + +export declare type Requester = { + /** + * Sends the given `request` to the server. + */ + readonly send: (request: Request_2) => Readonly>; +}; + +declare type Response_2 = { + /** + * The raw response from the server. + */ + content: string; + /** + * If the request timeouted. + */ + isTimedOut: boolean; + /** + * The http status code. + */ + status: number; +}; +export { Response_2 as Response } + +export { } diff --git a/scripts/node_modules/@algolia/requester-common/dist/requester-common.esm.js b/scripts/node_modules/@algolia/requester-common/dist/requester-common.esm.js new file mode 100644 index 000000000..4a89de744 --- /dev/null +++ b/scripts/node_modules/@algolia/requester-common/dist/requester-common.esm.js @@ -0,0 +1,8 @@ +const MethodEnum = { + Delete: 'DELETE', + Get: 'GET', + Post: 'POST', + Put: 'PUT', +}; + +export { MethodEnum }; diff --git a/scripts/node_modules/@algolia/requester-common/index.js b/scripts/node_modules/@algolia/requester-common/index.js new file mode 100644 index 000000000..0ced494c4 --- /dev/null +++ b/scripts/node_modules/@algolia/requester-common/index.js @@ -0,0 +1,2 @@ +// eslint-disable-next-line functional/immutable-data, import/no-commonjs +module.exports = require('./dist/requester-common.cjs.js'); diff --git a/scripts/node_modules/@algolia/requester-common/package.json b/scripts/node_modules/@algolia/requester-common/package.json new file mode 100644 index 000000000..163875031 --- /dev/null +++ b/scripts/node_modules/@algolia/requester-common/package.json @@ -0,0 +1,19 @@ +{ + "name": "@algolia/requester-common", + "version": "4.24.0", + "private": false, + "description": "Common interfaces for promise-based request libraries", + "repository": { + "type": "git", + "url": "git://github.com/algolia/algoliasearch-client-js.git" + }, + "license": "MIT", + "sideEffects": false, + "main": "index.js", + "module": "dist/requester-common.esm.js", + "types": "dist/requester-common.d.ts", + "files": [ + "index.js", + "dist" + ] +} diff --git a/scripts/node_modules/@algolia/requester-node-http/dist/requester-node-http.cjs.js b/scripts/node_modules/@algolia/requester-node-http/dist/requester-node-http.cjs.js new file mode 100644 index 000000000..88552795a --- /dev/null +++ b/scripts/node_modules/@algolia/requester-node-http/dist/requester-node-http.cjs.js @@ -0,0 +1,87 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var http = require('http'); +var https = require('https'); +var URL = require('url'); + +/* eslint functional/prefer-readonly-type: 0 */ +const agentOptions = { keepAlive: true }; +const defaultHttpAgent = new http.Agent(agentOptions); +const defaultHttpsAgent = new https.Agent(agentOptions); +function createNodeHttpRequester({ agent: userGlobalAgent, httpAgent: userHttpAgent, httpsAgent: userHttpsAgent, requesterOptions = {}, } = {}) { + const httpAgent = userHttpAgent || userGlobalAgent || defaultHttpAgent; + const httpsAgent = userHttpsAgent || userGlobalAgent || defaultHttpsAgent; + return { + send(request) { + return new Promise(resolve => { + const url = URL.parse(request.url); + const path = url.query === null ? url.pathname : `${url.pathname}?${url.query}`; + const options = { + ...requesterOptions, + agent: url.protocol === 'https:' ? httpsAgent : httpAgent, + hostname: url.hostname, + path, + method: request.method, + headers: { + ...(requesterOptions && requesterOptions.headers ? requesterOptions.headers : {}), + ...request.headers, + }, + ...(url.port !== undefined ? { port: url.port || '' } : {}), + }; + const req = (url.protocol === 'https:' ? https : http).request(options, response => { + // eslint-disable-next-line functional/no-let + let contentBuffers = []; + response.on('data', chunk => { + contentBuffers = contentBuffers.concat(chunk); + }); + response.on('end', () => { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + clearTimeout(connectTimeout); + // eslint-disable-next-line @typescript-eslint/no-use-before-define + clearTimeout(responseTimeout); + resolve({ + status: response.statusCode || 0, + content: Buffer.concat(contentBuffers).toString(), + isTimedOut: false, + }); + }); + }); + const createTimeout = (timeout, content) => { + return setTimeout(() => { + req.abort(); + resolve({ + status: 0, + content, + isTimedOut: true, + }); + }, timeout * 1000); + }; + const connectTimeout = createTimeout(request.connectTimeout, 'Connection timeout'); + // eslint-disable-next-line functional/no-let + let responseTimeout; + req.on('error', error => { + clearTimeout(connectTimeout); + clearTimeout(responseTimeout); + resolve({ status: 0, content: error.message, isTimedOut: false }); + }); + req.once('response', () => { + clearTimeout(connectTimeout); + responseTimeout = createTimeout(request.responseTimeout, 'Socket timeout'); + }); + if (request.data !== undefined) { + req.write(request.data); + } + req.end(); + }); + }, + destroy() { + httpAgent.destroy(); + httpsAgent.destroy(); + return Promise.resolve(); + }, + }; +} + +exports.createNodeHttpRequester = createNodeHttpRequester; diff --git a/scripts/node_modules/@algolia/requester-node-http/dist/requester-node-http.d.ts b/scripts/node_modules/@algolia/requester-node-http/dist/requester-node-http.d.ts new file mode 100644 index 000000000..5bd7ddbd9 --- /dev/null +++ b/scripts/node_modules/@algolia/requester-node-http/dist/requester-node-http.d.ts @@ -0,0 +1,17 @@ +/// + +import { Destroyable } from '@algolia/requester-common'; +import * as http from 'http'; +import * as https from 'https'; +import { Requester } from '@algolia/requester-common'; + +export declare function createNodeHttpRequester({ agent: userGlobalAgent, httpAgent: userHttpAgent, httpsAgent: userHttpsAgent, requesterOptions, }?: NodeHttpRequesterOptions): Requester & Destroyable; + +export declare type NodeHttpRequesterOptions = { + agent?: https.Agent | http.Agent; + httpAgent?: http.Agent; + httpsAgent?: https.Agent; + requesterOptions?: https.RequestOptions; +}; + +export { } diff --git a/scripts/node_modules/@algolia/requester-node-http/dist/requester-node-http.esm.js b/scripts/node_modules/@algolia/requester-node-http/dist/requester-node-http.esm.js new file mode 100644 index 000000000..1b83c6123 --- /dev/null +++ b/scripts/node_modules/@algolia/requester-node-http/dist/requester-node-http.esm.js @@ -0,0 +1,85 @@ +import * as http from 'http'; +import { Agent } from 'http'; +import * as https from 'https'; +import { Agent as Agent$1 } from 'https'; +import { parse } from 'url'; + +/* eslint functional/prefer-readonly-type: 0 */ +const agentOptions = { keepAlive: true }; +const defaultHttpAgent = new Agent(agentOptions); +const defaultHttpsAgent = new Agent$1(agentOptions); +function createNodeHttpRequester({ agent: userGlobalAgent, httpAgent: userHttpAgent, httpsAgent: userHttpsAgent, requesterOptions = {}, } = {}) { + const httpAgent = userHttpAgent || userGlobalAgent || defaultHttpAgent; + const httpsAgent = userHttpsAgent || userGlobalAgent || defaultHttpsAgent; + return { + send(request) { + return new Promise(resolve => { + const url = parse(request.url); + const path = url.query === null ? url.pathname : `${url.pathname}?${url.query}`; + const options = { + ...requesterOptions, + agent: url.protocol === 'https:' ? httpsAgent : httpAgent, + hostname: url.hostname, + path, + method: request.method, + headers: { + ...(requesterOptions && requesterOptions.headers ? requesterOptions.headers : {}), + ...request.headers, + }, + ...(url.port !== undefined ? { port: url.port || '' } : {}), + }; + const req = (url.protocol === 'https:' ? https : http).request(options, response => { + // eslint-disable-next-line functional/no-let + let contentBuffers = []; + response.on('data', chunk => { + contentBuffers = contentBuffers.concat(chunk); + }); + response.on('end', () => { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + clearTimeout(connectTimeout); + // eslint-disable-next-line @typescript-eslint/no-use-before-define + clearTimeout(responseTimeout); + resolve({ + status: response.statusCode || 0, + content: Buffer.concat(contentBuffers).toString(), + isTimedOut: false, + }); + }); + }); + const createTimeout = (timeout, content) => { + return setTimeout(() => { + req.abort(); + resolve({ + status: 0, + content, + isTimedOut: true, + }); + }, timeout * 1000); + }; + const connectTimeout = createTimeout(request.connectTimeout, 'Connection timeout'); + // eslint-disable-next-line functional/no-let + let responseTimeout; + req.on('error', error => { + clearTimeout(connectTimeout); + clearTimeout(responseTimeout); + resolve({ status: 0, content: error.message, isTimedOut: false }); + }); + req.once('response', () => { + clearTimeout(connectTimeout); + responseTimeout = createTimeout(request.responseTimeout, 'Socket timeout'); + }); + if (request.data !== undefined) { + req.write(request.data); + } + req.end(); + }); + }, + destroy() { + httpAgent.destroy(); + httpsAgent.destroy(); + return Promise.resolve(); + }, + }; +} + +export { createNodeHttpRequester }; diff --git a/scripts/node_modules/@algolia/requester-node-http/index.js b/scripts/node_modules/@algolia/requester-node-http/index.js new file mode 100644 index 000000000..fb864517c --- /dev/null +++ b/scripts/node_modules/@algolia/requester-node-http/index.js @@ -0,0 +1,2 @@ +// eslint-disable-next-line functional/immutable-data, import/no-commonjs +module.exports = require('./dist/requester-node-http.cjs.js'); diff --git a/scripts/node_modules/@algolia/requester-node-http/package.json b/scripts/node_modules/@algolia/requester-node-http/package.json new file mode 100644 index 000000000..a59165581 --- /dev/null +++ b/scripts/node_modules/@algolia/requester-node-http/package.json @@ -0,0 +1,22 @@ +{ + "name": "@algolia/requester-node-http", + "version": "4.24.0", + "private": false, + "description": "Promise-based request library for node using the native http module.", + "repository": { + "type": "git", + "url": "git://github.com/algolia/algoliasearch-client-javascript.git" + }, + "license": "MIT", + "sideEffects": false, + "main": "index.js", + "module": "dist/requester-node-http.esm.js", + "types": "dist/requester-node-http.d.ts", + "files": [ + "index.js", + "dist" + ], + "dependencies": { + "@algolia/requester-common": "4.24.0" + } +} diff --git a/scripts/node_modules/@algolia/transporter/dist/transporter.cjs.js b/scripts/node_modules/@algolia/transporter/dist/transporter.cjs.js new file mode 100644 index 000000000..1d15feed0 --- /dev/null +++ b/scripts/node_modules/@algolia/transporter/dist/transporter.cjs.js @@ -0,0 +1,483 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var requesterCommon = require('@algolia/requester-common'); + +function createMappedRequestOptions(requestOptions, timeout) { + const options = requestOptions || {}; + const data = options.data || {}; + Object.keys(options).forEach(key => { + if (['timeout', 'headers', 'queryParameters', 'data', 'cacheable'].indexOf(key) === -1) { + data[key] = options[key]; // eslint-disable-line functional/immutable-data + } + }); + return { + data: Object.entries(data).length > 0 ? data : undefined, + timeout: options.timeout || timeout, + headers: options.headers || {}, + queryParameters: options.queryParameters || {}, + cacheable: options.cacheable, + }; +} + +const CallEnum = { + /** + * If the host is read only. + */ + Read: 1, + /** + * If the host is write only. + */ + Write: 2, + /** + * If the host is both read and write. + */ + Any: 3, +}; + +const HostStatusEnum = { + Up: 1, + Down: 2, + Timeouted: 3, +}; + +// By default, API Clients at Algolia have expiration delay +// of 5 mins. In the JavaScript client, we have 2 mins. +const EXPIRATION_DELAY = 2 * 60 * 1000; +function createStatefulHost(host, status = HostStatusEnum.Up) { + return { + ...host, + status, + lastUpdate: Date.now(), + }; +} +function isStatefulHostUp(host) { + return host.status === HostStatusEnum.Up || Date.now() - host.lastUpdate > EXPIRATION_DELAY; +} +function isStatefulHostTimeouted(host) { + return (host.status === HostStatusEnum.Timeouted && Date.now() - host.lastUpdate <= EXPIRATION_DELAY); +} + +function createStatelessHost(options) { + if (typeof options === 'string') { + return { + protocol: 'https', + url: options, + accept: CallEnum.Any, + }; + } + return { + protocol: options.protocol || 'https', + url: options.url, + accept: options.accept || CallEnum.Any, + }; +} + +function createRetryableOptions(hostsCache, statelessHosts) { + return Promise.all(statelessHosts.map(statelessHost => { + return hostsCache.get(statelessHost, () => { + return Promise.resolve(createStatefulHost(statelessHost)); + }); + })).then(statefulHosts => { + const hostsUp = statefulHosts.filter(host => isStatefulHostUp(host)); + const hostsTimeouted = statefulHosts.filter(host => isStatefulHostTimeouted(host)); + /** + * Note, we put the hosts that previously timeouted on the end of the list. + */ + const hostsAvailable = [...hostsUp, ...hostsTimeouted]; + const statelessHostsAvailable = hostsAvailable.length > 0 + ? hostsAvailable.map(host => createStatelessHost(host)) + : statelessHosts; + return { + getTimeout(timeoutsCount, baseTimeout) { + /** + * Imagine that you have 4 hosts, if timeouts will increase + * on the following way: 1 (timeouted) > 4 (timeouted) > 5 (200) + * + * Note that, the very next request, we start from the previous timeout + * + * 5 (timeouted) > 6 (timeouted) > 7 ... + * + * This strategy may need to be reviewed, but is the strategy on the our + * current v3 version. + */ + const timeoutMultiplier = hostsTimeouted.length === 0 && timeoutsCount === 0 + ? 1 + : hostsTimeouted.length + 3 + timeoutsCount; + return timeoutMultiplier * baseTimeout; + }, + statelessHosts: statelessHostsAvailable, + }; + }); +} + +const isNetworkError = ({ isTimedOut, status }) => { + return !isTimedOut && ~~status === 0; +}; +const isRetryable = (response) => { + const status = response.status; + const isTimedOut = response.isTimedOut; + return (isTimedOut || isNetworkError(response) || (~~(status / 100) !== 2 && ~~(status / 100) !== 4)); +}; +const isSuccess = ({ status }) => { + return ~~(status / 100) === 2; +}; +const retryDecision = (response, outcomes) => { + if (isRetryable(response)) { + return outcomes.onRetry(response); + } + if (isSuccess(response)) { + return outcomes.onSuccess(response); + } + return outcomes.onFail(response); +}; + +function retryableRequest(transporter, statelessHosts, request, requestOptions) { + const stackTrace = []; // eslint-disable-line functional/prefer-readonly-type + /** + * First we prepare the payload that do not depend from hosts. + */ + const data = serializeData(request, requestOptions); + const headers = serializeHeaders(transporter, requestOptions); + const method = request.method; + // On `GET`, the data is proxied to query parameters. + const dataQueryParameters = request.method !== requesterCommon.MethodEnum.Get + ? {} + : { + ...request.data, + ...requestOptions.data, + }; + const queryParameters = { + 'x-algolia-agent': transporter.userAgent.value, + ...transporter.queryParameters, + ...dataQueryParameters, + ...requestOptions.queryParameters, + }; + let timeoutsCount = 0; // eslint-disable-line functional/no-let + const retry = (hosts, // eslint-disable-line functional/prefer-readonly-type + getTimeout) => { + /** + * We iterate on each host, until there is no host left. + */ + const host = hosts.pop(); // eslint-disable-line functional/immutable-data + if (host === undefined) { + throw createRetryError(stackTraceWithoutCredentials(stackTrace)); + } + const payload = { + data, + headers, + method, + url: serializeUrl(host, request.path, queryParameters), + connectTimeout: getTimeout(timeoutsCount, transporter.timeouts.connect), + responseTimeout: getTimeout(timeoutsCount, requestOptions.timeout), + }; + /** + * The stackFrame is pushed to the stackTrace so we + * can have information about onRetry and onFailure + * decisions. + */ + const pushToStackTrace = (response) => { + const stackFrame = { + request: payload, + response, + host, + triesLeft: hosts.length, + }; + // eslint-disable-next-line functional/immutable-data + stackTrace.push(stackFrame); + return stackFrame; + }; + const decisions = { + onSuccess: response => deserializeSuccess(response), + onRetry(response) { + const stackFrame = pushToStackTrace(response); + /** + * If response is a timeout, we increaset the number of + * timeouts so we can increase the timeout later. + */ + if (response.isTimedOut) { + timeoutsCount++; + } + return Promise.all([ + /** + * Failures are individually send the logger, allowing + * the end user to debug / store stack frames even + * when a retry error does not happen. + */ + transporter.logger.info('Retryable failure', stackFrameWithoutCredentials(stackFrame)), + /** + * We also store the state of the host in failure cases. If the host, is + * down it will remain down for the next 2 minutes. In a timeout situation, + * this host will be added end of the list of hosts on the next request. + */ + transporter.hostsCache.set(host, createStatefulHost(host, response.isTimedOut ? HostStatusEnum.Timeouted : HostStatusEnum.Down)), + ]).then(() => retry(hosts, getTimeout)); + }, + onFail(response) { + pushToStackTrace(response); + throw deserializeFailure(response, stackTraceWithoutCredentials(stackTrace)); + }, + }; + return transporter.requester.send(payload).then(response => { + return retryDecision(response, decisions); + }); + }; + /** + * Finally, for each retryable host perform request until we got a non + * retryable response. Some notes here: + * + * 1. The reverse here is applied so we can apply a `pop` later on => more performant. + * 2. We also get from the retryable options a timeout multiplier that is tailored + * for the current context. + */ + return createRetryableOptions(transporter.hostsCache, statelessHosts).then(options => { + return retry([...options.statelessHosts].reverse(), options.getTimeout); + }); +} + +function createTransporter(options) { + const { hostsCache, logger, requester, requestsCache, responsesCache, timeouts, userAgent, hosts, queryParameters, headers, } = options; + const transporter = { + hostsCache, + logger, + requester, + requestsCache, + responsesCache, + timeouts, + userAgent, + headers, + queryParameters, + hosts: hosts.map(host => createStatelessHost(host)), + read(request, requestOptions) { + /** + * First, we compute the user request options. Now, keep in mind, + * that using request options the user is able to modified the intire + * payload of the request. Such as headers, query parameters, and others. + */ + const mappedRequestOptions = createMappedRequestOptions(requestOptions, transporter.timeouts.read); + const createRetryableRequest = () => { + /** + * Then, we prepare a function factory that contains the construction of + * the retryable request. At this point, we may *not* perform the actual + * request. But we want to have the function factory ready. + */ + return retryableRequest(transporter, transporter.hosts.filter(host => (host.accept & CallEnum.Read) !== 0), request, mappedRequestOptions); + }; + /** + * Once we have the function factory ready, we need to determine of the + * request is "cacheable" - should be cached. Note that, once again, + * the user can force this option. + */ + const cacheable = mappedRequestOptions.cacheable !== undefined + ? mappedRequestOptions.cacheable + : request.cacheable; + /** + * If is not "cacheable", we immediatly trigger the retryable request, no + * need to check cache implementations. + */ + if (cacheable !== true) { + return createRetryableRequest(); + } + /** + * If the request is "cacheable", we need to first compute the key to ask + * the cache implementations if this request is on progress or if the + * response already exists on the cache. + */ + const key = { + request, + mappedRequestOptions, + transporter: { + queryParameters: transporter.queryParameters, + headers: transporter.headers, + }, + }; + /** + * With the computed key, we first ask the responses cache + * implemention if this request was been resolved before. + */ + return transporter.responsesCache.get(key, () => { + /** + * If the request has never resolved before, we actually ask if there + * is a current request with the same key on progress. + */ + return transporter.requestsCache.get(key, () => { + return (transporter.requestsCache + /** + * Finally, if there is no request in progress with the same key, + * this `createRetryableRequest()` will actually trigger the + * retryable request. + */ + .set(key, createRetryableRequest()) + .then(response => Promise.all([transporter.requestsCache.delete(key), response]), err => Promise.all([transporter.requestsCache.delete(key), Promise.reject(err)])) + .then(([_, response]) => response)); + }); + }, { + /** + * Of course, once we get this response back from the server, we + * tell response cache to actually store the received response + * to be used later. + */ + miss: response => transporter.responsesCache.set(key, response), + }); + }, + write(request, requestOptions) { + /** + * On write requests, no cache mechanisms are applied, and we + * proxy the request immediately to the requester. + */ + return retryableRequest(transporter, transporter.hosts.filter(host => (host.accept & CallEnum.Write) !== 0), request, createMappedRequestOptions(requestOptions, transporter.timeouts.write)); + }, + }; + return transporter; +} + +function createUserAgent(version) { + const userAgent = { + value: `Algolia for JavaScript (${version})`, + add(options) { + const addedUserAgent = `; ${options.segment}${options.version !== undefined ? ` (${options.version})` : ''}`; + if (userAgent.value.indexOf(addedUserAgent) === -1) { + // eslint-disable-next-line functional/immutable-data + userAgent.value = `${userAgent.value}${addedUserAgent}`; + } + return userAgent; + }, + }; + return userAgent; +} + +function deserializeSuccess(response) { + // eslint-disable-next-line functional/no-try-statement + try { + return JSON.parse(response.content); + } + catch (e) { + throw createDeserializationError(e.message, response); + } +} +function deserializeFailure({ content, status }, stackFrame) { + // eslint-disable-next-line functional/no-let + let message = content; + // eslint-disable-next-line functional/no-try-statement + try { + message = JSON.parse(content).message; + } + catch (e) { + // .. + } + return createApiError(message, status, stackFrame); +} + +// eslint-disable-next-line functional/prefer-readonly-type +function encode(format, ...args) { + // eslint-disable-next-line functional/no-let + let i = 0; + return format.replace(/%s/g, () => encodeURIComponent(args[i++])); +} + +function serializeUrl(host, path, queryParameters) { + const queryParametersAsString = serializeQueryParameters(queryParameters); + // eslint-disable-next-line functional/no-let + let url = `${host.protocol}://${host.url}/${path.charAt(0) === '/' ? path.substr(1) : path}`; + if (queryParametersAsString.length) { + url += `?${queryParametersAsString}`; + } + return url; +} +function serializeQueryParameters(parameters) { + const isObjectOrArray = (value) => Object.prototype.toString.call(value) === '[object Object]' || + Object.prototype.toString.call(value) === '[object Array]'; + return Object.keys(parameters) + .map(key => encode('%s=%s', key, isObjectOrArray(parameters[key]) ? JSON.stringify(parameters[key]) : parameters[key])) + .join('&'); +} +function serializeData(request, requestOptions) { + if (request.method === requesterCommon.MethodEnum.Get || + (request.data === undefined && requestOptions.data === undefined)) { + return undefined; + } + const data = Array.isArray(request.data) + ? request.data + : { ...request.data, ...requestOptions.data }; + return JSON.stringify(data); +} +function serializeHeaders(transporter, requestOptions) { + const headers = { + ...transporter.headers, + ...requestOptions.headers, + }; + const serializedHeaders = {}; + Object.keys(headers).forEach(header => { + const value = headers[header]; + // @ts-ignore + // eslint-disable-next-line functional/immutable-data + serializedHeaders[header.toLowerCase()] = value; + }); + return serializedHeaders; +} + +function stackTraceWithoutCredentials(stackTrace) { + return stackTrace.map(stackFrame => stackFrameWithoutCredentials(stackFrame)); +} +function stackFrameWithoutCredentials(stackFrame) { + const modifiedHeaders = stackFrame.request.headers['x-algolia-api-key'] + ? { 'x-algolia-api-key': '*****' } + : {}; + return { + ...stackFrame, + request: { + ...stackFrame.request, + headers: { + ...stackFrame.request.headers, + ...modifiedHeaders, + }, + }, + }; +} + +function createApiError(message, status, transporterStackTrace) { + return { + name: 'ApiError', + message, + status, + transporterStackTrace, + }; +} + +function createDeserializationError(message, response) { + return { + name: 'DeserializationError', + message, + response, + }; +} + +function createRetryError(transporterStackTrace) { + return { + name: 'RetryError', + message: 'Unreachable hosts - your application id may be incorrect. If the error persists, please reach out to the Algolia Support team: https://alg.li/support .', + transporterStackTrace, + }; +} + +exports.CallEnum = CallEnum; +exports.HostStatusEnum = HostStatusEnum; +exports.createApiError = createApiError; +exports.createDeserializationError = createDeserializationError; +exports.createMappedRequestOptions = createMappedRequestOptions; +exports.createRetryError = createRetryError; +exports.createStatefulHost = createStatefulHost; +exports.createStatelessHost = createStatelessHost; +exports.createTransporter = createTransporter; +exports.createUserAgent = createUserAgent; +exports.deserializeFailure = deserializeFailure; +exports.deserializeSuccess = deserializeSuccess; +exports.isStatefulHostTimeouted = isStatefulHostTimeouted; +exports.isStatefulHostUp = isStatefulHostUp; +exports.serializeData = serializeData; +exports.serializeHeaders = serializeHeaders; +exports.serializeQueryParameters = serializeQueryParameters; +exports.serializeUrl = serializeUrl; +exports.stackFrameWithoutCredentials = stackFrameWithoutCredentials; +exports.stackTraceWithoutCredentials = stackTraceWithoutCredentials; diff --git a/scripts/node_modules/@algolia/transporter/dist/transporter.d.ts b/scripts/node_modules/@algolia/transporter/dist/transporter.d.ts new file mode 100644 index 000000000..9d2c0da18 --- /dev/null +++ b/scripts/node_modules/@algolia/transporter/dist/transporter.d.ts @@ -0,0 +1,383 @@ +import { Cache as Cache_2 } from '@algolia/cache-common'; +import { Logger } from '@algolia/logger-common'; +import { MethodType } from '@algolia/requester-common'; +import { Request as Request_3 } from '@algolia/requester-common'; +import { Requester } from '@algolia/requester-common'; +import { Response as Response_2 } from '@algolia/requester-common'; + +export declare type ApiError = Error & { + /** + * The http status code. + */ + readonly status: number; + /** + * Contains report of stack frames of the + * execution of a certain request. + */ + readonly transporterStackTrace: readonly StackFrame[]; +}; + +export declare const CallEnum: Readonly>; + +export declare type CallType = 1 | 2 | 3; + +export declare function createApiError(message: string, status: number, transporterStackTrace: readonly StackFrame[]): ApiError; + +export declare function createDeserializationError(message: string, response: Response_2): DeserializationError; + +export declare function createMappedRequestOptions(requestOptions?: RequestOptions, timeout?: number): MappedRequestOptions; + +export declare function createRetryError(transporterStackTrace: readonly StackFrame[]): RetryError; + +export declare function createStatefulHost(host: StatelessHost, status?: HostStatusType): StatefulHost; + +export declare function createStatelessHost(options: HostOptions): StatelessHost; + +export declare function createTransporter(options: TransporterOptions): Transporter; + +export declare function createUserAgent(version: string): UserAgent; + +export declare type DeserializationError = Error & { + /** + * The raw response from the server. + */ + readonly response: Response_2; +}; + +export declare function deserializeFailure({ content, status }: Response_2, stackFrame: readonly StackFrame[]): Error; + +export declare function deserializeSuccess(response: Response_2): TObject; + +declare type Headers_2 = Readonly>; +export { Headers_2 as Headers } + +export declare type HostOptions = string | { + /** + * The url of the server, without the protocol. + */ + readonly url: string; + /** + * The type of host. Defaults to `Any`. + */ + readonly accept?: CallType; + /** + * The protocol. Defaults to `https`. + */ + readonly protocol?: string; +}; + +export declare const HostStatusEnum: Readonly>; + +export declare type HostStatusType = 1 | 2 | 3; + +export declare function isStatefulHostTimeouted(host: StatefulHost): boolean; + +export declare function isStatefulHostUp(host: StatefulHost): boolean; + +export declare type MappedRequestOptions = { + /** + * If the request should be cached. + */ + readonly cacheable: boolean | undefined; + /** + * The `read` or `write` timeout of the request. + */ + readonly timeout: number | undefined; + /** + * The headers of the request. + */ + readonly headers: Record; + /** + * The query parameters of the request. + */ + readonly queryParameters: Record; + /** + * The data to be transfered to the server. + */ + readonly data?: Record; +}; + +export declare type QueryParameters = Readonly>; + +declare type Request_2 = { + /** + * The method of the request. `GET`, etc. + */ + readonly method: MethodType; + /** + * The path of the request. i.e: `/1/indexes`. + */ + readonly path: string; + /** + * The data to transfer to the server. + */ + readonly data?: Record | ReadonlyArray>; + /** + * If the response should persist on cache. + */ + readonly cacheable?: boolean; +}; +export { Request_2 as Request } + +export declare type RequestOptions = { + /** + * If the given request should persist on the cache. Keep in mind, + * that some methods may have this option enabled by default. + */ + readonly cacheable?: boolean; + /** + * Custom timeout for the request. Note that, in normal situacions + * the given timeout will be applied. But the transporter layer may + * increase this timeout if there is need for it. + */ + readonly timeout?: number; + /** + * Custom headers for the request. This headers are + * going to be merged the transporter headers. + */ + readonly headers?: Readonly>; + /** + * Custom query parameters for the request. This query parameters are + * going to be merged the transporter query parameters. + */ + readonly queryParameters?: Record; + /** + * Custom data for the request. This data are + * going to be merged the transporter data. + */ + readonly data?: Record; + /** + * Additional request body values. It's only taken in + * consideration in `POST` and `PUT` requests. + */ + [key: string]: any; +}; + +export declare type RetryError = Error & { + /** + * Contains report of stack frames of the + * execution of a certain request. + */ + readonly transporterStackTrace: readonly StackFrame[]; +}; + +export declare function serializeData(request: Request_2, requestOptions: RequestOptions): string | undefined; + +export declare function serializeHeaders(transporter: Transporter, requestOptions: RequestOptions): Headers_2; + +export declare function serializeQueryParameters(parameters: Readonly>): string; + +export declare function serializeUrl(host: StatelessHost, path: string, queryParameters: Readonly>): string; + +export declare type StackFrame = { + /** + * The request made. + */ + readonly request: Request_3; + /** + * The received response. + */ + readonly response: Response_2; + /** + * The host associated with the `request` and the `response`. + */ + readonly host: StatelessHost; + /** + * The number of tries left. + */ + readonly triesLeft: number; +}; + +export declare function stackFrameWithoutCredentials(stackFrame: StackFrame): StackFrame; + +export declare function stackTraceWithoutCredentials(stackTrace: readonly StackFrame[]): readonly StackFrame[]; + +export declare type StatefulHost = StatelessHost & { + /** + * Holds the last time this host failed in milliseconds elapsed + * since the UNIX epoch. This failure can be because of an + * timeout error or a because the host is not available. + */ + readonly lastUpdate: number; + /** + * Holds the host status. Note that, depending of the `lastUpdate` + * an host may be considered as `Up` on the transporter layer. + */ + readonly status: HostStatusType; +}; + +export declare type StatelessHost = { + /** + * The protocol of the stateless host. Between `http` and `https`. + */ + readonly protocol: string; + /** + * The url, without protocol. + */ + readonly url: string; + /** + * The type of the host. + */ + readonly accept: CallType; +}; + +export declare type Timeouts = { + /** + * The timeout to stablish a connection with the server. + */ + readonly connect: number; + /** + * The timeout to receive the response on read requests. + */ + readonly read: number; + /** + * The timeout to receive the response on write requests. + */ + readonly write: number; +}; + +export declare type Transporter = { + /** + * The cache of the hosts. Usually used to persist + * the state of the host when its down. + */ + readonly hostsCache: Cache_2; + /** + * The logger instance to send events of the transporter. + */ + readonly logger: Logger; + /** + * The underlying requester used. Should differ + * depending of the enviroment where the client + * will be used. + */ + readonly requester: Requester; + /** + * The cache of the requests. When requests are + * `cacheable`, the returned promised persists + * in this cache to shared in similar resquests + * before being resolved. + */ + readonly requestsCache: Cache_2; + /** + * The cache of the responses. When requests are + * `cacheable`, the returned responses persists + * in this cache to shared in similar resquests. + */ + readonly responsesCache: Cache_2; + /** + * The timeouts used by the requester. The transporter + * layer may increase this timeouts as defined on the + * retry strategy. + */ + readonly timeouts: Timeouts; + /** + * The user agent used. Sent on query parameters. + */ + readonly userAgent: UserAgent; + /** + * The headers used on each request. + */ + readonly headers: Headers_2; + /** + * The query parameters used on each request. + */ + readonly queryParameters: QueryParameters; + /** + * The hosts used by the retry strategy. + * + * @readonly + */ + hosts: readonly StatelessHost[]; + /** + * Performs a read request using read hosts. + */ + readonly read: (request: Request_2, requestOptions?: RequestOptions) => Readonly>; + /** + * Performs a write request using write hosts. + */ + readonly write: (request: Request_2, requestOptions?: RequestOptions) => Readonly>; +}; + +export declare type TransporterOptions = { + /** + * The cache of the hosts. Usually used to persist + * the state of the host when its down. + */ + readonly hostsCache: Cache_2; + /** + * The logger instance to send events of the transporter. + */ + readonly logger: Logger; + /** + * The underlying requester used. Should differ + * depending of the enviroment where the client + * will be used. + */ + readonly requester: Requester; + /** + * The cache of the requests. When requests are + * `cacheable`, the returned promised persists + * in this cache to shared in similar resquests + * before being resolved. + */ + readonly requestsCache: Cache_2; + /** + * The cache of the responses. When requests are + * `cacheable`, the returned responses persists + * in this cache to shared in similar resquests. + */ + readonly responsesCache: Cache_2; + /** + * The timeouts used by the requester. The transporter + * layer may increase this timeouts as defined on the + * retry strategy. + */ + readonly timeouts: Timeouts; + /** + * The hosts used by the requester. + */ + readonly hosts: readonly HostOptions[]; + /** + * The headers used by the requester. The transporter + * layer may add some extra headers during the request + * for the user agent, and others. + */ + readonly headers: Headers_2; + /** + * The query parameters used by the requester. The transporter + * layer may add some extra headers during the request + * for the user agent, and others. + */ + readonly queryParameters: QueryParameters; + /** + * The user agent used. Sent on query parameters. + */ + readonly userAgent: UserAgent; +}; + +export declare type UserAgent = { + /** + * The raw value of the user agent. + * + * @readonly + */ + value: string; + /** + * Mutates the current user agent ading the given user agent options. + */ + readonly add: (options: UserAgentOptions) => UserAgent; +}; + +export declare type UserAgentOptions = { + /** + * The segment. Usually the integration name. + */ + readonly segment: string; + /** + * The version. Usually the integration version. + */ + readonly version?: string; +}; + +export { } diff --git a/scripts/node_modules/@algolia/transporter/dist/transporter.esm.js b/scripts/node_modules/@algolia/transporter/dist/transporter.esm.js new file mode 100644 index 000000000..566d7f01d --- /dev/null +++ b/scripts/node_modules/@algolia/transporter/dist/transporter.esm.js @@ -0,0 +1,460 @@ +import { MethodEnum } from '@algolia/requester-common'; + +function createMappedRequestOptions(requestOptions, timeout) { + const options = requestOptions || {}; + const data = options.data || {}; + Object.keys(options).forEach(key => { + if (['timeout', 'headers', 'queryParameters', 'data', 'cacheable'].indexOf(key) === -1) { + data[key] = options[key]; // eslint-disable-line functional/immutable-data + } + }); + return { + data: Object.entries(data).length > 0 ? data : undefined, + timeout: options.timeout || timeout, + headers: options.headers || {}, + queryParameters: options.queryParameters || {}, + cacheable: options.cacheable, + }; +} + +const CallEnum = { + /** + * If the host is read only. + */ + Read: 1, + /** + * If the host is write only. + */ + Write: 2, + /** + * If the host is both read and write. + */ + Any: 3, +}; + +const HostStatusEnum = { + Up: 1, + Down: 2, + Timeouted: 3, +}; + +// By default, API Clients at Algolia have expiration delay +// of 5 mins. In the JavaScript client, we have 2 mins. +const EXPIRATION_DELAY = 2 * 60 * 1000; +function createStatefulHost(host, status = HostStatusEnum.Up) { + return { + ...host, + status, + lastUpdate: Date.now(), + }; +} +function isStatefulHostUp(host) { + return host.status === HostStatusEnum.Up || Date.now() - host.lastUpdate > EXPIRATION_DELAY; +} +function isStatefulHostTimeouted(host) { + return (host.status === HostStatusEnum.Timeouted && Date.now() - host.lastUpdate <= EXPIRATION_DELAY); +} + +function createStatelessHost(options) { + if (typeof options === 'string') { + return { + protocol: 'https', + url: options, + accept: CallEnum.Any, + }; + } + return { + protocol: options.protocol || 'https', + url: options.url, + accept: options.accept || CallEnum.Any, + }; +} + +function createRetryableOptions(hostsCache, statelessHosts) { + return Promise.all(statelessHosts.map(statelessHost => { + return hostsCache.get(statelessHost, () => { + return Promise.resolve(createStatefulHost(statelessHost)); + }); + })).then(statefulHosts => { + const hostsUp = statefulHosts.filter(host => isStatefulHostUp(host)); + const hostsTimeouted = statefulHosts.filter(host => isStatefulHostTimeouted(host)); + /** + * Note, we put the hosts that previously timeouted on the end of the list. + */ + const hostsAvailable = [...hostsUp, ...hostsTimeouted]; + const statelessHostsAvailable = hostsAvailable.length > 0 + ? hostsAvailable.map(host => createStatelessHost(host)) + : statelessHosts; + return { + getTimeout(timeoutsCount, baseTimeout) { + /** + * Imagine that you have 4 hosts, if timeouts will increase + * on the following way: 1 (timeouted) > 4 (timeouted) > 5 (200) + * + * Note that, the very next request, we start from the previous timeout + * + * 5 (timeouted) > 6 (timeouted) > 7 ... + * + * This strategy may need to be reviewed, but is the strategy on the our + * current v3 version. + */ + const timeoutMultiplier = hostsTimeouted.length === 0 && timeoutsCount === 0 + ? 1 + : hostsTimeouted.length + 3 + timeoutsCount; + return timeoutMultiplier * baseTimeout; + }, + statelessHosts: statelessHostsAvailable, + }; + }); +} + +const isNetworkError = ({ isTimedOut, status }) => { + return !isTimedOut && ~~status === 0; +}; +const isRetryable = (response) => { + const status = response.status; + const isTimedOut = response.isTimedOut; + return (isTimedOut || isNetworkError(response) || (~~(status / 100) !== 2 && ~~(status / 100) !== 4)); +}; +const isSuccess = ({ status }) => { + return ~~(status / 100) === 2; +}; +const retryDecision = (response, outcomes) => { + if (isRetryable(response)) { + return outcomes.onRetry(response); + } + if (isSuccess(response)) { + return outcomes.onSuccess(response); + } + return outcomes.onFail(response); +}; + +function retryableRequest(transporter, statelessHosts, request, requestOptions) { + const stackTrace = []; // eslint-disable-line functional/prefer-readonly-type + /** + * First we prepare the payload that do not depend from hosts. + */ + const data = serializeData(request, requestOptions); + const headers = serializeHeaders(transporter, requestOptions); + const method = request.method; + // On `GET`, the data is proxied to query parameters. + const dataQueryParameters = request.method !== MethodEnum.Get + ? {} + : { + ...request.data, + ...requestOptions.data, + }; + const queryParameters = { + 'x-algolia-agent': transporter.userAgent.value, + ...transporter.queryParameters, + ...dataQueryParameters, + ...requestOptions.queryParameters, + }; + let timeoutsCount = 0; // eslint-disable-line functional/no-let + const retry = (hosts, // eslint-disable-line functional/prefer-readonly-type + getTimeout) => { + /** + * We iterate on each host, until there is no host left. + */ + const host = hosts.pop(); // eslint-disable-line functional/immutable-data + if (host === undefined) { + throw createRetryError(stackTraceWithoutCredentials(stackTrace)); + } + const payload = { + data, + headers, + method, + url: serializeUrl(host, request.path, queryParameters), + connectTimeout: getTimeout(timeoutsCount, transporter.timeouts.connect), + responseTimeout: getTimeout(timeoutsCount, requestOptions.timeout), + }; + /** + * The stackFrame is pushed to the stackTrace so we + * can have information about onRetry and onFailure + * decisions. + */ + const pushToStackTrace = (response) => { + const stackFrame = { + request: payload, + response, + host, + triesLeft: hosts.length, + }; + // eslint-disable-next-line functional/immutable-data + stackTrace.push(stackFrame); + return stackFrame; + }; + const decisions = { + onSuccess: response => deserializeSuccess(response), + onRetry(response) { + const stackFrame = pushToStackTrace(response); + /** + * If response is a timeout, we increaset the number of + * timeouts so we can increase the timeout later. + */ + if (response.isTimedOut) { + timeoutsCount++; + } + return Promise.all([ + /** + * Failures are individually send the logger, allowing + * the end user to debug / store stack frames even + * when a retry error does not happen. + */ + transporter.logger.info('Retryable failure', stackFrameWithoutCredentials(stackFrame)), + /** + * We also store the state of the host in failure cases. If the host, is + * down it will remain down for the next 2 minutes. In a timeout situation, + * this host will be added end of the list of hosts on the next request. + */ + transporter.hostsCache.set(host, createStatefulHost(host, response.isTimedOut ? HostStatusEnum.Timeouted : HostStatusEnum.Down)), + ]).then(() => retry(hosts, getTimeout)); + }, + onFail(response) { + pushToStackTrace(response); + throw deserializeFailure(response, stackTraceWithoutCredentials(stackTrace)); + }, + }; + return transporter.requester.send(payload).then(response => { + return retryDecision(response, decisions); + }); + }; + /** + * Finally, for each retryable host perform request until we got a non + * retryable response. Some notes here: + * + * 1. The reverse here is applied so we can apply a `pop` later on => more performant. + * 2. We also get from the retryable options a timeout multiplier that is tailored + * for the current context. + */ + return createRetryableOptions(transporter.hostsCache, statelessHosts).then(options => { + return retry([...options.statelessHosts].reverse(), options.getTimeout); + }); +} + +function createTransporter(options) { + const { hostsCache, logger, requester, requestsCache, responsesCache, timeouts, userAgent, hosts, queryParameters, headers, } = options; + const transporter = { + hostsCache, + logger, + requester, + requestsCache, + responsesCache, + timeouts, + userAgent, + headers, + queryParameters, + hosts: hosts.map(host => createStatelessHost(host)), + read(request, requestOptions) { + /** + * First, we compute the user request options. Now, keep in mind, + * that using request options the user is able to modified the intire + * payload of the request. Such as headers, query parameters, and others. + */ + const mappedRequestOptions = createMappedRequestOptions(requestOptions, transporter.timeouts.read); + const createRetryableRequest = () => { + /** + * Then, we prepare a function factory that contains the construction of + * the retryable request. At this point, we may *not* perform the actual + * request. But we want to have the function factory ready. + */ + return retryableRequest(transporter, transporter.hosts.filter(host => (host.accept & CallEnum.Read) !== 0), request, mappedRequestOptions); + }; + /** + * Once we have the function factory ready, we need to determine of the + * request is "cacheable" - should be cached. Note that, once again, + * the user can force this option. + */ + const cacheable = mappedRequestOptions.cacheable !== undefined + ? mappedRequestOptions.cacheable + : request.cacheable; + /** + * If is not "cacheable", we immediatly trigger the retryable request, no + * need to check cache implementations. + */ + if (cacheable !== true) { + return createRetryableRequest(); + } + /** + * If the request is "cacheable", we need to first compute the key to ask + * the cache implementations if this request is on progress or if the + * response already exists on the cache. + */ + const key = { + request, + mappedRequestOptions, + transporter: { + queryParameters: transporter.queryParameters, + headers: transporter.headers, + }, + }; + /** + * With the computed key, we first ask the responses cache + * implemention if this request was been resolved before. + */ + return transporter.responsesCache.get(key, () => { + /** + * If the request has never resolved before, we actually ask if there + * is a current request with the same key on progress. + */ + return transporter.requestsCache.get(key, () => { + return (transporter.requestsCache + /** + * Finally, if there is no request in progress with the same key, + * this `createRetryableRequest()` will actually trigger the + * retryable request. + */ + .set(key, createRetryableRequest()) + .then(response => Promise.all([transporter.requestsCache.delete(key), response]), err => Promise.all([transporter.requestsCache.delete(key), Promise.reject(err)])) + .then(([_, response]) => response)); + }); + }, { + /** + * Of course, once we get this response back from the server, we + * tell response cache to actually store the received response + * to be used later. + */ + miss: response => transporter.responsesCache.set(key, response), + }); + }, + write(request, requestOptions) { + /** + * On write requests, no cache mechanisms are applied, and we + * proxy the request immediately to the requester. + */ + return retryableRequest(transporter, transporter.hosts.filter(host => (host.accept & CallEnum.Write) !== 0), request, createMappedRequestOptions(requestOptions, transporter.timeouts.write)); + }, + }; + return transporter; +} + +function createUserAgent(version) { + const userAgent = { + value: `Algolia for JavaScript (${version})`, + add(options) { + const addedUserAgent = `; ${options.segment}${options.version !== undefined ? ` (${options.version})` : ''}`; + if (userAgent.value.indexOf(addedUserAgent) === -1) { + // eslint-disable-next-line functional/immutable-data + userAgent.value = `${userAgent.value}${addedUserAgent}`; + } + return userAgent; + }, + }; + return userAgent; +} + +function deserializeSuccess(response) { + // eslint-disable-next-line functional/no-try-statement + try { + return JSON.parse(response.content); + } + catch (e) { + throw createDeserializationError(e.message, response); + } +} +function deserializeFailure({ content, status }, stackFrame) { + // eslint-disable-next-line functional/no-let + let message = content; + // eslint-disable-next-line functional/no-try-statement + try { + message = JSON.parse(content).message; + } + catch (e) { + // .. + } + return createApiError(message, status, stackFrame); +} + +// eslint-disable-next-line functional/prefer-readonly-type +function encode(format, ...args) { + // eslint-disable-next-line functional/no-let + let i = 0; + return format.replace(/%s/g, () => encodeURIComponent(args[i++])); +} + +function serializeUrl(host, path, queryParameters) { + const queryParametersAsString = serializeQueryParameters(queryParameters); + // eslint-disable-next-line functional/no-let + let url = `${host.protocol}://${host.url}/${path.charAt(0) === '/' ? path.substr(1) : path}`; + if (queryParametersAsString.length) { + url += `?${queryParametersAsString}`; + } + return url; +} +function serializeQueryParameters(parameters) { + const isObjectOrArray = (value) => Object.prototype.toString.call(value) === '[object Object]' || + Object.prototype.toString.call(value) === '[object Array]'; + return Object.keys(parameters) + .map(key => encode('%s=%s', key, isObjectOrArray(parameters[key]) ? JSON.stringify(parameters[key]) : parameters[key])) + .join('&'); +} +function serializeData(request, requestOptions) { + if (request.method === MethodEnum.Get || + (request.data === undefined && requestOptions.data === undefined)) { + return undefined; + } + const data = Array.isArray(request.data) + ? request.data + : { ...request.data, ...requestOptions.data }; + return JSON.stringify(data); +} +function serializeHeaders(transporter, requestOptions) { + const headers = { + ...transporter.headers, + ...requestOptions.headers, + }; + const serializedHeaders = {}; + Object.keys(headers).forEach(header => { + const value = headers[header]; + // @ts-ignore + // eslint-disable-next-line functional/immutable-data + serializedHeaders[header.toLowerCase()] = value; + }); + return serializedHeaders; +} + +function stackTraceWithoutCredentials(stackTrace) { + return stackTrace.map(stackFrame => stackFrameWithoutCredentials(stackFrame)); +} +function stackFrameWithoutCredentials(stackFrame) { + const modifiedHeaders = stackFrame.request.headers['x-algolia-api-key'] + ? { 'x-algolia-api-key': '*****' } + : {}; + return { + ...stackFrame, + request: { + ...stackFrame.request, + headers: { + ...stackFrame.request.headers, + ...modifiedHeaders, + }, + }, + }; +} + +function createApiError(message, status, transporterStackTrace) { + return { + name: 'ApiError', + message, + status, + transporterStackTrace, + }; +} + +function createDeserializationError(message, response) { + return { + name: 'DeserializationError', + message, + response, + }; +} + +function createRetryError(transporterStackTrace) { + return { + name: 'RetryError', + message: 'Unreachable hosts - your application id may be incorrect. If the error persists, please reach out to the Algolia Support team: https://alg.li/support .', + transporterStackTrace, + }; +} + +export { CallEnum, HostStatusEnum, createApiError, createDeserializationError, createMappedRequestOptions, createRetryError, createStatefulHost, createStatelessHost, createTransporter, createUserAgent, deserializeFailure, deserializeSuccess, isStatefulHostTimeouted, isStatefulHostUp, serializeData, serializeHeaders, serializeQueryParameters, serializeUrl, stackFrameWithoutCredentials, stackTraceWithoutCredentials }; diff --git a/scripts/node_modules/@algolia/transporter/index.js b/scripts/node_modules/@algolia/transporter/index.js new file mode 100644 index 000000000..e254eb1b4 --- /dev/null +++ b/scripts/node_modules/@algolia/transporter/index.js @@ -0,0 +1,2 @@ +// eslint-disable-next-line functional/immutable-data, import/no-commonjs +module.exports = require('./dist/transporter.cjs.js'); diff --git a/scripts/node_modules/@algolia/transporter/package.json b/scripts/node_modules/@algolia/transporter/package.json new file mode 100644 index 000000000..e3019971c --- /dev/null +++ b/scripts/node_modules/@algolia/transporter/package.json @@ -0,0 +1,24 @@ +{ + "name": "@algolia/transporter", + "version": "4.24.0", + "private": false, + "description": "Promise-based transporter layer with embedded retry strategy.", + "repository": { + "type": "git", + "url": "git://github.com/algolia/algoliasearch-client-javascript.git" + }, + "license": "MIT", + "sideEffects": false, + "main": "index.js", + "module": "dist/transporter.esm.js", + "types": "dist/transporter.d.ts", + "files": [ + "index.js", + "dist" + ], + "dependencies": { + "@algolia/cache-common": "4.24.0", + "@algolia/logger-common": "4.24.0", + "@algolia/requester-common": "4.24.0" + } +} diff --git a/scripts/node_modules/algoliasearch/README.md b/scripts/node_modules/algoliasearch/README.md new file mode 100644 index 000000000..9e227e857 --- /dev/null +++ b/scripts/node_modules/algoliasearch/README.md @@ -0,0 +1,82 @@ +

+ + Algolia for JavaScript + + +

The perfect starting point to integrate Algolia within your JavaScript project

+ +

+ NPM version + NPM downloads + jsDelivr Downloads + License +

+

+ +

+ Documentation • + InstantSearch • + Community Forum • + Stack Overflow • + Report a bug • + Support +

+ +## ✨ Features + +- Thin & **minimal low-level HTTP client** to interact with Algolia's API +- Works both on the **browser** and **node.js** +- **UMD compatible**, you can use it with any module loader +- Built with TypeScript + +## 💡 Getting Started + +First, install Algolia JavaScript API Client via the [npm](https://www.npmjs.com/get-npm) package manager: + +```bash +npm install algoliasearch +``` + +Then, create objects on your index: + +```js +const algoliasearch = require("algoliasearch"); + +const client = algoliasearch("YourApplicationID", "YourAdminAPIKey"); +const index = client.initIndex("your_index_name"); + +const objects = [ + { + objectID: 1, + name: "Foo" + } +]; + +index + .saveObjects(objects) + .then(({ objectIDs }) => { + console.log(objectIDs); + }) + .catch(err => { + console.log(err); + }); +``` + +Finally, let's actually search using the `search` method: + +```js +index + .search("Fo") + .then(({ hits }) => { + console.log(hits); + }) + .catch(err => { + console.log(err); + }); +``` + +For full documentation, visit the **[online documentation](https://www.algolia.com/doc/api-client/getting-started/install/javascript/)**. + +## 📄 License + +Algolia JavaScript API Client is an open-sourced software licensed under the [MIT license](LICENSE.md). diff --git a/scripts/node_modules/algoliasearch/dist/algoliasearch-lite.d.ts b/scripts/node_modules/algoliasearch/dist/algoliasearch-lite.d.ts new file mode 100644 index 000000000..27395aee2 --- /dev/null +++ b/scripts/node_modules/algoliasearch/dist/algoliasearch-lite.d.ts @@ -0,0 +1,51 @@ +import { ClientTransporterOptions } from '@algolia/client-common'; +import { FindAnswersOptions } from '@algolia/client-search'; +import { FindAnswersResponse } from '@algolia/client-search'; +import { MultipleQueriesOptions } from '@algolia/client-search'; +import { MultipleQueriesQuery } from '@algolia/client-search'; +import { MultipleQueriesResponse } from '@algolia/client-search'; +import { Request as Request_2 } from '@algolia/transporter'; +import { RequestOptions } from '@algolia/transporter'; +import { SearchClient as SearchClient_2 } from '@algolia/client-search'; +import { SearchClientOptions } from '@algolia/client-search'; +import { SearchForFacetValuesQueryParams } from '@algolia/client-search'; +import { SearchForFacetValuesResponse } from '@algolia/client-search'; +import { SearchIndex as SearchIndex_2 } from '@algolia/client-search'; +import { SearchOptions } from '@algolia/client-search'; +import { SearchResponse } from '@algolia/client-search'; +import { WithRecommendMethods } from '@algolia/recommend'; + +declare function algoliasearch(appId: string, apiKey: string, options?: AlgoliaSearchOptions): SearchClient; + +declare namespace algoliasearch { + var version: string; +} +export default algoliasearch; + +export declare type AlgoliaSearchOptions = Partial & WithoutCredentials; + +declare type Credentials = { + readonly appId: string; + readonly apiKey: string; +}; + +export declare type SearchClient = SearchClient_2 & { + readonly initIndex: (indexName: string) => SearchIndex; + readonly search: (queries: readonly MultipleQueriesQuery[], requestOptions?: RequestOptions & MultipleQueriesOptions) => Readonly>>; + readonly searchForFacetValues: (queries: ReadonlyArray<{ + readonly indexName: string; + readonly params: SearchForFacetValuesQueryParams & SearchOptions; + }>, requestOptions?: RequestOptions) => Readonly>; + readonly customRequest: (request: Request_2, requestOptions?: RequestOptions) => Readonly>; + readonly getRecommendations: WithRecommendMethods['getRecommendations']; +}; + +export declare type SearchIndex = SearchIndex_2 & { + readonly search: (query: string, requestOptions?: RequestOptions & SearchOptions) => Readonly>>; + readonly searchForFacetValues: (facetName: string, facetQuery: string, requestOptions?: RequestOptions & SearchOptions) => Readonly>; + readonly findAnswers: (query: string, queryLanguages: readonly string[], requestOptions?: RequestOptions & FindAnswersOptions) => Readonly>>; +}; + +export declare type WithoutCredentials = Omit; + +export { } diff --git a/scripts/node_modules/algoliasearch/dist/algoliasearch-lite.esm.browser.js b/scripts/node_modules/algoliasearch/dist/algoliasearch-lite.esm.browser.js new file mode 100644 index 000000000..7d933ae6a --- /dev/null +++ b/scripts/node_modules/algoliasearch/dist/algoliasearch-lite.esm.browser.js @@ -0,0 +1,961 @@ +function createBrowserLocalStorageCache(options) { + const namespaceKey = `algoliasearch-client-js-${options.key}`; + // eslint-disable-next-line functional/no-let + let storage; + const getStorage = () => { + if (storage === undefined) { + storage = options.localStorage || window.localStorage; + } + return storage; + }; + const getNamespace = () => { + return JSON.parse(getStorage().getItem(namespaceKey) || '{}'); + }; + const setNamespace = (namespace) => { + getStorage().setItem(namespaceKey, JSON.stringify(namespace)); + }; + const removeOutdatedCacheItems = () => { + const timeToLive = options.timeToLive ? options.timeToLive * 1000 : null; + const namespace = getNamespace(); + const filteredNamespaceWithoutOldFormattedCacheItems = Object.fromEntries(Object.entries(namespace).filter(([, cacheItem]) => { + return cacheItem.timestamp !== undefined; + })); + setNamespace(filteredNamespaceWithoutOldFormattedCacheItems); + if (!timeToLive) + return; + const filteredNamespaceWithoutExpiredItems = Object.fromEntries(Object.entries(filteredNamespaceWithoutOldFormattedCacheItems).filter(([, cacheItem]) => { + const currentTimestamp = new Date().getTime(); + const isExpired = cacheItem.timestamp + timeToLive < currentTimestamp; + return !isExpired; + })); + setNamespace(filteredNamespaceWithoutExpiredItems); + }; + return { + get(key, defaultValue, events = { + miss: () => Promise.resolve(), + }) { + return Promise.resolve() + .then(() => { + removeOutdatedCacheItems(); + const keyAsString = JSON.stringify(key); + return getNamespace()[keyAsString]; + }) + .then(value => { + return Promise.all([value ? value.value : defaultValue(), value !== undefined]); + }) + .then(([value, exists]) => { + return Promise.all([value, exists || events.miss(value)]); + }) + .then(([value]) => value); + }, + set(key, value) { + return Promise.resolve().then(() => { + const namespace = getNamespace(); + // eslint-disable-next-line functional/immutable-data + namespace[JSON.stringify(key)] = { + timestamp: new Date().getTime(), + value, + }; + getStorage().setItem(namespaceKey, JSON.stringify(namespace)); + return value; + }); + }, + delete(key) { + return Promise.resolve().then(() => { + const namespace = getNamespace(); + // eslint-disable-next-line functional/immutable-data + delete namespace[JSON.stringify(key)]; + getStorage().setItem(namespaceKey, JSON.stringify(namespace)); + }); + }, + clear() { + return Promise.resolve().then(() => { + getStorage().removeItem(namespaceKey); + }); + }, + }; +} + +// @todo Add logger on options to debug when caches go wrong. +function createFallbackableCache(options) { + const caches = [...options.caches]; + const current = caches.shift(); // eslint-disable-line functional/immutable-data + if (current === undefined) { + return createNullCache(); + } + return { + get(key, defaultValue, events = { + miss: () => Promise.resolve(), + }) { + return current.get(key, defaultValue, events).catch(() => { + return createFallbackableCache({ caches }).get(key, defaultValue, events); + }); + }, + set(key, value) { + return current.set(key, value).catch(() => { + return createFallbackableCache({ caches }).set(key, value); + }); + }, + delete(key) { + return current.delete(key).catch(() => { + return createFallbackableCache({ caches }).delete(key); + }); + }, + clear() { + return current.clear().catch(() => { + return createFallbackableCache({ caches }).clear(); + }); + }, + }; +} + +function createNullCache() { + return { + get(_key, defaultValue, events = { + miss: () => Promise.resolve(), + }) { + const value = defaultValue(); + return value + .then(result => Promise.all([result, events.miss(result)])) + .then(([result]) => result); + }, + set(_key, value) { + return Promise.resolve(value); + }, + delete(_key) { + return Promise.resolve(); + }, + clear() { + return Promise.resolve(); + }, + }; +} + +function createInMemoryCache(options = { serializable: true }) { + // eslint-disable-next-line functional/no-let + let cache = {}; + return { + get(key, defaultValue, events = { + miss: () => Promise.resolve(), + }) { + const keyAsString = JSON.stringify(key); + if (keyAsString in cache) { + return Promise.resolve(options.serializable ? JSON.parse(cache[keyAsString]) : cache[keyAsString]); + } + const promise = defaultValue(); + const miss = (events && events.miss) || (() => Promise.resolve()); + return promise.then((value) => miss(value)).then(() => promise); + }, + set(key, value) { + // eslint-disable-next-line functional/immutable-data + cache[JSON.stringify(key)] = options.serializable ? JSON.stringify(value) : value; + return Promise.resolve(value); + }, + delete(key) { + // eslint-disable-next-line functional/immutable-data + delete cache[JSON.stringify(key)]; + return Promise.resolve(); + }, + clear() { + cache = {}; + return Promise.resolve(); + }, + }; +} + +function createAuth(authMode, appId, apiKey) { + const credentials = { + 'x-algolia-api-key': apiKey, + 'x-algolia-application-id': appId, + }; + return { + headers() { + return authMode === AuthMode.WithinHeaders ? credentials : {}; + }, + queryParameters() { + return authMode === AuthMode.WithinQueryParameters ? credentials : {}; + }, + }; +} + +// eslint-disable-next-line functional/prefer-readonly-type +function shuffle(array) { + let c = array.length - 1; // eslint-disable-line functional/no-let + // eslint-disable-next-line functional/no-loop-statement + for (c; c > 0; c--) { + const b = Math.floor(Math.random() * (c + 1)); + const a = array[c]; + array[c] = array[b]; // eslint-disable-line functional/immutable-data, no-param-reassign + array[b] = a; // eslint-disable-line functional/immutable-data, no-param-reassign + } + return array; +} +function addMethods(base, methods) { + if (!methods) { + return base; + } + Object.keys(methods).forEach(key => { + // eslint-disable-next-line functional/immutable-data, no-param-reassign + base[key] = methods[key](base); + }); + return base; +} +function encode(format, ...args) { + // eslint-disable-next-line functional/no-let + let i = 0; + return format.replace(/%s/g, () => encodeURIComponent(args[i++])); +} + +const version = '4.24.0'; + +const AuthMode = { + /** + * If auth credentials should be in query parameters. + */ + WithinQueryParameters: 0, + /** + * If auth credentials should be in headers. + */ + WithinHeaders: 1, +}; + +function createMappedRequestOptions(requestOptions, timeout) { + const options = requestOptions || {}; + const data = options.data || {}; + Object.keys(options).forEach(key => { + if (['timeout', 'headers', 'queryParameters', 'data', 'cacheable'].indexOf(key) === -1) { + data[key] = options[key]; // eslint-disable-line functional/immutable-data + } + }); + return { + data: Object.entries(data).length > 0 ? data : undefined, + timeout: options.timeout || timeout, + headers: options.headers || {}, + queryParameters: options.queryParameters || {}, + cacheable: options.cacheable, + }; +} + +const CallEnum = { + /** + * If the host is read only. + */ + Read: 1, + /** + * If the host is write only. + */ + Write: 2, + /** + * If the host is both read and write. + */ + Any: 3, +}; + +const HostStatusEnum = { + Up: 1, + Down: 2, + Timeouted: 3, +}; + +// By default, API Clients at Algolia have expiration delay +// of 5 mins. In the JavaScript client, we have 2 mins. +const EXPIRATION_DELAY = 2 * 60 * 1000; +function createStatefulHost(host, status = HostStatusEnum.Up) { + return { + ...host, + status, + lastUpdate: Date.now(), + }; +} +function isStatefulHostUp(host) { + return host.status === HostStatusEnum.Up || Date.now() - host.lastUpdate > EXPIRATION_DELAY; +} +function isStatefulHostTimeouted(host) { + return (host.status === HostStatusEnum.Timeouted && Date.now() - host.lastUpdate <= EXPIRATION_DELAY); +} + +function createStatelessHost(options) { + if (typeof options === 'string') { + return { + protocol: 'https', + url: options, + accept: CallEnum.Any, + }; + } + return { + protocol: options.protocol || 'https', + url: options.url, + accept: options.accept || CallEnum.Any, + }; +} + +const MethodEnum = { + Delete: 'DELETE', + Get: 'GET', + Post: 'POST', + Put: 'PUT', +}; + +function createRetryableOptions(hostsCache, statelessHosts) { + return Promise.all(statelessHosts.map(statelessHost => { + return hostsCache.get(statelessHost, () => { + return Promise.resolve(createStatefulHost(statelessHost)); + }); + })).then(statefulHosts => { + const hostsUp = statefulHosts.filter(host => isStatefulHostUp(host)); + const hostsTimeouted = statefulHosts.filter(host => isStatefulHostTimeouted(host)); + /** + * Note, we put the hosts that previously timeouted on the end of the list. + */ + const hostsAvailable = [...hostsUp, ...hostsTimeouted]; + const statelessHostsAvailable = hostsAvailable.length > 0 + ? hostsAvailable.map(host => createStatelessHost(host)) + : statelessHosts; + return { + getTimeout(timeoutsCount, baseTimeout) { + /** + * Imagine that you have 4 hosts, if timeouts will increase + * on the following way: 1 (timeouted) > 4 (timeouted) > 5 (200) + * + * Note that, the very next request, we start from the previous timeout + * + * 5 (timeouted) > 6 (timeouted) > 7 ... + * + * This strategy may need to be reviewed, but is the strategy on the our + * current v3 version. + */ + const timeoutMultiplier = hostsTimeouted.length === 0 && timeoutsCount === 0 + ? 1 + : hostsTimeouted.length + 3 + timeoutsCount; + return timeoutMultiplier * baseTimeout; + }, + statelessHosts: statelessHostsAvailable, + }; + }); +} + +const isNetworkError = ({ isTimedOut, status }) => { + return !isTimedOut && ~~status === 0; +}; +const isRetryable = (response) => { + const status = response.status; + const isTimedOut = response.isTimedOut; + return (isTimedOut || isNetworkError(response) || (~~(status / 100) !== 2 && ~~(status / 100) !== 4)); +}; +const isSuccess = ({ status }) => { + return ~~(status / 100) === 2; +}; +const retryDecision = (response, outcomes) => { + if (isRetryable(response)) { + return outcomes.onRetry(response); + } + if (isSuccess(response)) { + return outcomes.onSuccess(response); + } + return outcomes.onFail(response); +}; + +function retryableRequest(transporter, statelessHosts, request, requestOptions) { + const stackTrace = []; // eslint-disable-line functional/prefer-readonly-type + /** + * First we prepare the payload that do not depend from hosts. + */ + const data = serializeData(request, requestOptions); + const headers = serializeHeaders(transporter, requestOptions); + const method = request.method; + // On `GET`, the data is proxied to query parameters. + const dataQueryParameters = request.method !== MethodEnum.Get + ? {} + : { + ...request.data, + ...requestOptions.data, + }; + const queryParameters = { + 'x-algolia-agent': transporter.userAgent.value, + ...transporter.queryParameters, + ...dataQueryParameters, + ...requestOptions.queryParameters, + }; + let timeoutsCount = 0; // eslint-disable-line functional/no-let + const retry = (hosts, // eslint-disable-line functional/prefer-readonly-type + getTimeout) => { + /** + * We iterate on each host, until there is no host left. + */ + const host = hosts.pop(); // eslint-disable-line functional/immutable-data + if (host === undefined) { + throw createRetryError(stackTraceWithoutCredentials(stackTrace)); + } + const payload = { + data, + headers, + method, + url: serializeUrl(host, request.path, queryParameters), + connectTimeout: getTimeout(timeoutsCount, transporter.timeouts.connect), + responseTimeout: getTimeout(timeoutsCount, requestOptions.timeout), + }; + /** + * The stackFrame is pushed to the stackTrace so we + * can have information about onRetry and onFailure + * decisions. + */ + const pushToStackTrace = (response) => { + const stackFrame = { + request: payload, + response, + host, + triesLeft: hosts.length, + }; + // eslint-disable-next-line functional/immutable-data + stackTrace.push(stackFrame); + return stackFrame; + }; + const decisions = { + onSuccess: response => deserializeSuccess(response), + onRetry(response) { + const stackFrame = pushToStackTrace(response); + /** + * If response is a timeout, we increaset the number of + * timeouts so we can increase the timeout later. + */ + if (response.isTimedOut) { + timeoutsCount++; + } + return Promise.all([ + /** + * Failures are individually send the logger, allowing + * the end user to debug / store stack frames even + * when a retry error does not happen. + */ + transporter.logger.info('Retryable failure', stackFrameWithoutCredentials(stackFrame)), + /** + * We also store the state of the host in failure cases. If the host, is + * down it will remain down for the next 2 minutes. In a timeout situation, + * this host will be added end of the list of hosts on the next request. + */ + transporter.hostsCache.set(host, createStatefulHost(host, response.isTimedOut ? HostStatusEnum.Timeouted : HostStatusEnum.Down)), + ]).then(() => retry(hosts, getTimeout)); + }, + onFail(response) { + pushToStackTrace(response); + throw deserializeFailure(response, stackTraceWithoutCredentials(stackTrace)); + }, + }; + return transporter.requester.send(payload).then(response => { + return retryDecision(response, decisions); + }); + }; + /** + * Finally, for each retryable host perform request until we got a non + * retryable response. Some notes here: + * + * 1. The reverse here is applied so we can apply a `pop` later on => more performant. + * 2. We also get from the retryable options a timeout multiplier that is tailored + * for the current context. + */ + return createRetryableOptions(transporter.hostsCache, statelessHosts).then(options => { + return retry([...options.statelessHosts].reverse(), options.getTimeout); + }); +} + +function createTransporter(options) { + const { hostsCache, logger, requester, requestsCache, responsesCache, timeouts, userAgent, hosts, queryParameters, headers, } = options; + const transporter = { + hostsCache, + logger, + requester, + requestsCache, + responsesCache, + timeouts, + userAgent, + headers, + queryParameters, + hosts: hosts.map(host => createStatelessHost(host)), + read(request, requestOptions) { + /** + * First, we compute the user request options. Now, keep in mind, + * that using request options the user is able to modified the intire + * payload of the request. Such as headers, query parameters, and others. + */ + const mappedRequestOptions = createMappedRequestOptions(requestOptions, transporter.timeouts.read); + const createRetryableRequest = () => { + /** + * Then, we prepare a function factory that contains the construction of + * the retryable request. At this point, we may *not* perform the actual + * request. But we want to have the function factory ready. + */ + return retryableRequest(transporter, transporter.hosts.filter(host => (host.accept & CallEnum.Read) !== 0), request, mappedRequestOptions); + }; + /** + * Once we have the function factory ready, we need to determine of the + * request is "cacheable" - should be cached. Note that, once again, + * the user can force this option. + */ + const cacheable = mappedRequestOptions.cacheable !== undefined + ? mappedRequestOptions.cacheable + : request.cacheable; + /** + * If is not "cacheable", we immediatly trigger the retryable request, no + * need to check cache implementations. + */ + if (cacheable !== true) { + return createRetryableRequest(); + } + /** + * If the request is "cacheable", we need to first compute the key to ask + * the cache implementations if this request is on progress or if the + * response already exists on the cache. + */ + const key = { + request, + mappedRequestOptions, + transporter: { + queryParameters: transporter.queryParameters, + headers: transporter.headers, + }, + }; + /** + * With the computed key, we first ask the responses cache + * implemention if this request was been resolved before. + */ + return transporter.responsesCache.get(key, () => { + /** + * If the request has never resolved before, we actually ask if there + * is a current request with the same key on progress. + */ + return transporter.requestsCache.get(key, () => { + return (transporter.requestsCache + /** + * Finally, if there is no request in progress with the same key, + * this `createRetryableRequest()` will actually trigger the + * retryable request. + */ + .set(key, createRetryableRequest()) + .then(response => Promise.all([transporter.requestsCache.delete(key), response]), err => Promise.all([transporter.requestsCache.delete(key), Promise.reject(err)])) + .then(([_, response]) => response)); + }); + }, { + /** + * Of course, once we get this response back from the server, we + * tell response cache to actually store the received response + * to be used later. + */ + miss: response => transporter.responsesCache.set(key, response), + }); + }, + write(request, requestOptions) { + /** + * On write requests, no cache mechanisms are applied, and we + * proxy the request immediately to the requester. + */ + return retryableRequest(transporter, transporter.hosts.filter(host => (host.accept & CallEnum.Write) !== 0), request, createMappedRequestOptions(requestOptions, transporter.timeouts.write)); + }, + }; + return transporter; +} + +function createUserAgent(version) { + const userAgent = { + value: `Algolia for JavaScript (${version})`, + add(options) { + const addedUserAgent = `; ${options.segment}${options.version !== undefined ? ` (${options.version})` : ''}`; + if (userAgent.value.indexOf(addedUserAgent) === -1) { + // eslint-disable-next-line functional/immutable-data + userAgent.value = `${userAgent.value}${addedUserAgent}`; + } + return userAgent; + }, + }; + return userAgent; +} + +function deserializeSuccess(response) { + // eslint-disable-next-line functional/no-try-statement + try { + return JSON.parse(response.content); + } + catch (e) { + throw createDeserializationError(e.message, response); + } +} +function deserializeFailure({ content, status }, stackFrame) { + // eslint-disable-next-line functional/no-let + let message = content; + // eslint-disable-next-line functional/no-try-statement + try { + message = JSON.parse(content).message; + } + catch (e) { + // .. + } + return createApiError(message, status, stackFrame); +} + +function serializeUrl(host, path, queryParameters) { + const queryParametersAsString = serializeQueryParameters(queryParameters); + // eslint-disable-next-line functional/no-let + let url = `${host.protocol}://${host.url}/${path.charAt(0) === '/' ? path.substr(1) : path}`; + if (queryParametersAsString.length) { + url += `?${queryParametersAsString}`; + } + return url; +} +function serializeQueryParameters(parameters) { + const isObjectOrArray = (value) => Object.prototype.toString.call(value) === '[object Object]' || + Object.prototype.toString.call(value) === '[object Array]'; + return Object.keys(parameters) + .map(key => encode('%s=%s', key, isObjectOrArray(parameters[key]) ? JSON.stringify(parameters[key]) : parameters[key])) + .join('&'); +} +function serializeData(request, requestOptions) { + if (request.method === MethodEnum.Get || + (request.data === undefined && requestOptions.data === undefined)) { + return undefined; + } + const data = Array.isArray(request.data) + ? request.data + : { ...request.data, ...requestOptions.data }; + return JSON.stringify(data); +} +function serializeHeaders(transporter, requestOptions) { + const headers = { + ...transporter.headers, + ...requestOptions.headers, + }; + const serializedHeaders = {}; + Object.keys(headers).forEach(header => { + const value = headers[header]; + // @ts-ignore + // eslint-disable-next-line functional/immutable-data + serializedHeaders[header.toLowerCase()] = value; + }); + return serializedHeaders; +} + +function stackTraceWithoutCredentials(stackTrace) { + return stackTrace.map(stackFrame => stackFrameWithoutCredentials(stackFrame)); +} +function stackFrameWithoutCredentials(stackFrame) { + const modifiedHeaders = stackFrame.request.headers['x-algolia-api-key'] + ? { 'x-algolia-api-key': '*****' } + : {}; + return { + ...stackFrame, + request: { + ...stackFrame.request, + headers: { + ...stackFrame.request.headers, + ...modifiedHeaders, + }, + }, + }; +} + +function createApiError(message, status, transporterStackTrace) { + return { + name: 'ApiError', + message, + status, + transporterStackTrace, + }; +} + +function createDeserializationError(message, response) { + return { + name: 'DeserializationError', + message, + response, + }; +} + +function createRetryError(transporterStackTrace) { + return { + name: 'RetryError', + message: 'Unreachable hosts - your application id may be incorrect. If the error persists, please reach out to the Algolia Support team: https://alg.li/support .', + transporterStackTrace, + }; +} + +const createSearchClient = options => { + const appId = options.appId; + const auth = createAuth(options.authMode !== undefined ? options.authMode : AuthMode.WithinHeaders, appId, options.apiKey); + const transporter = createTransporter({ + hosts: [ + { url: `${appId}-dsn.algolia.net`, accept: CallEnum.Read }, + { url: `${appId}.algolia.net`, accept: CallEnum.Write }, + ].concat(shuffle([ + { url: `${appId}-1.algolianet.com` }, + { url: `${appId}-2.algolianet.com` }, + { url: `${appId}-3.algolianet.com` }, + ])), + ...options, + headers: { + ...auth.headers(), + ...{ 'content-type': 'application/x-www-form-urlencoded' }, + ...options.headers, + }, + queryParameters: { + ...auth.queryParameters(), + ...options.queryParameters, + }, + }); + const base = { + transporter, + appId, + addAlgoliaAgent(segment, version) { + transporter.userAgent.add({ segment, version }); + }, + clearCache() { + return Promise.all([ + transporter.requestsCache.clear(), + transporter.responsesCache.clear(), + ]).then(() => undefined); + }, + }; + return addMethods(base, options.methods); +}; + +const customRequest = (base) => { + return (request, requestOptions) => { + if (request.method === MethodEnum.Get) { + return base.transporter.read(request, requestOptions); + } + return base.transporter.write(request, requestOptions); + }; +}; + +const initIndex = (base) => { + return (indexName, options = {}) => { + const searchIndex = { + transporter: base.transporter, + appId: base.appId, + indexName, + }; + return addMethods(searchIndex, options.methods); + }; +}; + +const multipleQueries = (base) => { + return (queries, requestOptions) => { + const requests = queries.map(query => { + return { + ...query, + params: serializeQueryParameters(query.params || {}), + }; + }); + return base.transporter.read({ + method: MethodEnum.Post, + path: '1/indexes/*/queries', + data: { + requests, + }, + cacheable: true, + }, requestOptions); + }; +}; + +const multipleSearchForFacetValues = (base) => { + return (queries, requestOptions) => { + return Promise.all(queries.map(query => { + const { facetName, facetQuery, ...params } = query.params; + return initIndex(base)(query.indexName, { + methods: { searchForFacetValues }, + }).searchForFacetValues(facetName, facetQuery, { + ...requestOptions, + ...params, + }); + })); + }; +}; + +const findAnswers = (base) => { + return (query, queryLanguages, requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Post, + path: encode('1/answers/%s/prediction', base.indexName), + data: { + query, + queryLanguages, + }, + cacheable: true, + }, requestOptions); + }; +}; + +const search = (base) => { + return (query, requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Post, + path: encode('1/indexes/%s/query', base.indexName), + data: { + query, + }, + cacheable: true, + }, requestOptions); + }; +}; + +const searchForFacetValues = (base) => { + return (facetName, facetQuery, requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Post, + path: encode('1/indexes/%s/facets/%s/query', base.indexName, facetName), + data: { + facetQuery, + }, + cacheable: true, + }, requestOptions); + }; +}; + +const LogLevelEnum = { + Debug: 1, + Info: 2, + Error: 3, +}; + +/* eslint no-console: 0 */ +function createConsoleLogger(logLevel) { + return { + debug(message, args) { + if (LogLevelEnum.Debug >= logLevel) { + console.debug(message, args); + } + return Promise.resolve(); + }, + info(message, args) { + if (LogLevelEnum.Info >= logLevel) { + console.info(message, args); + } + return Promise.resolve(); + }, + error(message, args) { + console.error(message, args); + return Promise.resolve(); + }, + }; +} + +const getRecommendations = base => { + return (queries, requestOptions) => { + const requests = queries.map(query => ({ + ...query, + // The `threshold` param is required by the endpoint to make it easier + // to provide a default value later, so we default it in the client + // so that users don't have to provide a value. + threshold: query.threshold || 0, + })); + return base.transporter.read({ + method: MethodEnum.Post, + path: '1/indexes/*/recommendations', + data: { + requests, + }, + cacheable: true, + }, requestOptions); + }; +}; + +function createBrowserXhrRequester() { + return { + send(request) { + return new Promise((resolve) => { + const baseRequester = new XMLHttpRequest(); + baseRequester.open(request.method, request.url, true); + Object.keys(request.headers).forEach(key => baseRequester.setRequestHeader(key, request.headers[key])); + const createTimeout = (timeout, content) => { + return setTimeout(() => { + baseRequester.abort(); + resolve({ + status: 0, + content, + isTimedOut: true, + }); + }, timeout * 1000); + }; + const connectTimeout = createTimeout(request.connectTimeout, 'Connection timeout'); + // eslint-disable-next-line functional/no-let + let responseTimeout; + // eslint-disable-next-line functional/immutable-data + baseRequester.onreadystatechange = () => { + if (baseRequester.readyState > baseRequester.OPENED && responseTimeout === undefined) { + clearTimeout(connectTimeout); + responseTimeout = createTimeout(request.responseTimeout, 'Socket timeout'); + } + }; + // eslint-disable-next-line functional/immutable-data + baseRequester.onerror = () => { + // istanbul ignore next + if (baseRequester.status === 0) { + clearTimeout(connectTimeout); + clearTimeout(responseTimeout); + resolve({ + content: baseRequester.responseText || 'Network request failed', + status: baseRequester.status, + isTimedOut: false, + }); + } + }; + // eslint-disable-next-line functional/immutable-data + baseRequester.onload = () => { + clearTimeout(connectTimeout); + clearTimeout(responseTimeout); + resolve({ + content: baseRequester.responseText, + status: baseRequester.status, + isTimedOut: false, + }); + }; + baseRequester.send(request.data); + }); + }, + }; +} + +function algoliasearch(appId, apiKey, options) { + const commonOptions = { + appId, + apiKey, + timeouts: { + connect: 1, + read: 2, + write: 30, + }, + requester: createBrowserXhrRequester(), + logger: createConsoleLogger(LogLevelEnum.Error), + responsesCache: createInMemoryCache(), + requestsCache: createInMemoryCache({ serializable: false }), + hostsCache: createFallbackableCache({ + caches: [ + createBrowserLocalStorageCache({ key: `${version}-${appId}` }), + createInMemoryCache(), + ], + }), + userAgent: createUserAgent(version).add({ + segment: 'Browser', + version: 'lite', + }), + authMode: AuthMode.WithinQueryParameters, + }; + return createSearchClient({ + ...commonOptions, + ...options, + methods: { + search: multipleQueries, + searchForFacetValues: multipleSearchForFacetValues, + multipleQueries, + multipleSearchForFacetValues, + customRequest, + initIndex: base => (indexName) => { + return initIndex(base)(indexName, { + methods: { search, searchForFacetValues, findAnswers }, + }); + }, + getRecommendations, + }, + }); +} +// eslint-disable-next-line functional/immutable-data +algoliasearch.version = version; + +export default algoliasearch; diff --git a/scripts/node_modules/algoliasearch/dist/algoliasearch-lite.umd.js b/scripts/node_modules/algoliasearch/dist/algoliasearch-lite.umd.js new file mode 100644 index 000000000..c2e51159a --- /dev/null +++ b/scripts/node_modules/algoliasearch/dist/algoliasearch-lite.umd.js @@ -0,0 +1,2 @@ +/*! algoliasearch-lite.umd.js | 4.24.0 | © Algolia, inc. | https://github.com/algolia/algoliasearch-client-javascript */ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).algoliasearch=t()}(this,(function(){"use strict";function e(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function t(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function r(r){for(var n=1;n=0||(o[r]=e[r]);return o}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(n=0;n=0||Object.prototype.propertyIsEnumerable.call(e,r)&&(o[r]=e[r])}return o}function o(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){if(!(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e)))return;var r=[],n=!0,o=!1,a=void 0;try{for(var u,i=e[Symbol.iterator]();!(n=(u=i.next()).done)&&(r.push(u.value),!t||r.length!==t);n=!0);}catch(e){o=!0,a=e}finally{try{n||null==i.return||i.return()}finally{if(o)throw a}}return r}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}function a(e){return function(e){if(Array.isArray(e)){for(var t=0,r=new Array(e.length);t2&&void 0!==arguments[2]?arguments[2]:{miss:function(){return Promise.resolve()}};return Promise.resolve().then((function(){i();var t=JSON.stringify(e);return a()[t]})).then((function(e){return Promise.all([e?e.value:t(),void 0!==e])})).then((function(e){var t=o(e,2),n=t[0],a=t[1];return Promise.all([n,a||r.miss(n)])})).then((function(e){return o(e,1)[0]}))},set:function(e,t){return Promise.resolve().then((function(){var o=a();return o[JSON.stringify(e)]={timestamp:(new Date).getTime(),value:t},n().setItem(r,JSON.stringify(o)),t}))},delete:function(e){return Promise.resolve().then((function(){var t=a();delete t[JSON.stringify(e)],n().setItem(r,JSON.stringify(t))}))},clear:function(){return Promise.resolve().then((function(){n().removeItem(r)}))}}}function i(e){var t=a(e.caches),r=t.shift();return void 0===r?{get:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{miss:function(){return Promise.resolve()}},n=t();return n.then((function(e){return Promise.all([e,r.miss(e)])})).then((function(e){return o(e,1)[0]}))},set:function(e,t){return Promise.resolve(t)},delete:function(e){return Promise.resolve()},clear:function(){return Promise.resolve()}}:{get:function(e,n){var o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{miss:function(){return Promise.resolve()}};return r.get(e,n,o).catch((function(){return i({caches:t}).get(e,n,o)}))},set:function(e,n){return r.set(e,n).catch((function(){return i({caches:t}).set(e,n)}))},delete:function(e){return r.delete(e).catch((function(){return i({caches:t}).delete(e)}))},clear:function(){return r.clear().catch((function(){return i({caches:t}).clear()}))}}}function s(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{serializable:!0},t={};return{get:function(r,n){var o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{miss:function(){return Promise.resolve()}},a=JSON.stringify(r);if(a in t)return Promise.resolve(e.serializable?JSON.parse(t[a]):t[a]);var u=n(),i=o&&o.miss||function(){return Promise.resolve()};return u.then((function(e){return i(e)})).then((function(){return u}))},set:function(r,n){return t[JSON.stringify(r)]=e.serializable?JSON.stringify(n):n,Promise.resolve(n)},delete:function(e){return delete t[JSON.stringify(e)],Promise.resolve()},clear:function(){return t={},Promise.resolve()}}}function c(e){for(var t=e.length-1;t>0;t--){var r=Math.floor(Math.random()*(t+1)),n=e[t];e[t]=e[r],e[r]=n}return e}function l(e,t){return t?(Object.keys(t).forEach((function(r){e[r]=t[r](e)})),e):e}function f(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n0?n:void 0,timeout:r.timeout||t,headers:r.headers||{},queryParameters:r.queryParameters||{},cacheable:r.cacheable}}var d={Read:1,Write:2,Any:3},p=1,v=2,g=3;function y(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:p;return r(r({},e),{},{status:t,lastUpdate:Date.now()})}function b(e){return"string"==typeof e?{protocol:"https",url:e,accept:d.Any}:{protocol:e.protocol||"https",url:e.url,accept:e.accept||d.Any}}var O="GET",P="POST";function q(e,t){return Promise.all(t.map((function(t){return e.get(t,(function(){return Promise.resolve(y(t))}))}))).then((function(e){var r=e.filter((function(e){return function(e){return e.status===p||Date.now()-e.lastUpdate>12e4}(e)})),n=e.filter((function(e){return function(e){return e.status===g&&Date.now()-e.lastUpdate<=12e4}(e)})),o=[].concat(a(r),a(n));return{getTimeout:function(e,t){return(0===n.length&&0===e?1:n.length+3+e)*t},statelessHosts:o.length>0?o.map((function(e){return b(e)})):t}}))}function j(e,t,n,o){var u=[],i=function(e,t){if(e.method===O||void 0===e.data&&void 0===t.data)return;var n=Array.isArray(e.data)?e.data:r(r({},e.data),t.data);return JSON.stringify(n)}(n,o),s=function(e,t){var n=r(r({},e.headers),t.headers),o={};return Object.keys(n).forEach((function(e){var t=n[e];o[e.toLowerCase()]=t})),o}(e,o),c=n.method,l=n.method!==O?{}:r(r({},n.data),o.data),f=r(r(r({"x-algolia-agent":e.userAgent.value},e.queryParameters),l),o.queryParameters),h=0,m=function t(r,a){var l=r.pop();if(void 0===l)throw{name:"RetryError",message:"Unreachable hosts - your application id may be incorrect. If the error persists, please reach out to the Algolia Support team: https://alg.li/support .",transporterStackTrace:A(u)};var m={data:i,headers:s,method:c,url:S(l,n.path,f),connectTimeout:a(h,e.timeouts.connect),responseTimeout:a(h,o.timeout)},d=function(e){var t={request:m,response:e,host:l,triesLeft:r.length};return u.push(t),t},p={onSuccess:function(e){return function(e){try{return JSON.parse(e.content)}catch(t){throw function(e,t){return{name:"DeserializationError",message:e,response:t}}(t.message,e)}}(e)},onRetry:function(n){var o=d(n);return n.isTimedOut&&h++,Promise.all([e.logger.info("Retryable failure",x(o)),e.hostsCache.set(l,y(l,n.isTimedOut?g:v))]).then((function(){return t(r,a)}))},onFail:function(e){throw d(e),function(e,t){var r=e.content,n=e.status,o=r;try{o=JSON.parse(r).message}catch(e){}return function(e,t,r){return{name:"ApiError",message:e,status:t,transporterStackTrace:r}}(o,n,t)}(e,A(u))}};return e.requester.send(m).then((function(e){return function(e,t){return function(e){var t=e.status;return e.isTimedOut||function(e){var t=e.isTimedOut,r=e.status;return!t&&0==~~r}(e)||2!=~~(t/100)&&4!=~~(t/100)}(e)?t.onRetry(e):2==~~(e.status/100)?t.onSuccess(e):t.onFail(e)}(e,p)}))};return q(e.hostsCache,t).then((function(e){return m(a(e.statelessHosts).reverse(),e.getTimeout)}))}function w(e){var t={value:"Algolia for JavaScript (".concat(e,")"),add:function(e){var r="; ".concat(e.segment).concat(void 0!==e.version?" (".concat(e.version,")"):"");return-1===t.value.indexOf(r)&&(t.value="".concat(t.value).concat(r)),t}};return t}function S(e,t,r){var n=T(r),o="".concat(e.protocol,"://").concat(e.url,"/").concat("/"===t.charAt(0)?t.substr(1):t);return n.length&&(o+="?".concat(n)),o}function T(e){return Object.keys(e).map((function(t){return f("%s=%s",t,(r=e[t],"[object Object]"===Object.prototype.toString.call(r)||"[object Array]"===Object.prototype.toString.call(r)?JSON.stringify(e[t]):e[t]));var r})).join("&")}function A(e){return e.map((function(e){return x(e)}))}function x(e){var t=e.request.headers["x-algolia-api-key"]?{"x-algolia-api-key":"*****"}:{};return r(r({},e),{},{request:r(r({},e.request),{},{headers:r(r({},e.request.headers),t)})})}var N=function(e){var t=e.appId,n=function(e,t,r){var n={"x-algolia-api-key":r,"x-algolia-application-id":t};return{headers:function(){return e===h.WithinHeaders?n:{}},queryParameters:function(){return e===h.WithinQueryParameters?n:{}}}}(void 0!==e.authMode?e.authMode:h.WithinHeaders,t,e.apiKey),a=function(e){var t=e.hostsCache,r=e.logger,n=e.requester,a=e.requestsCache,u=e.responsesCache,i=e.timeouts,s=e.userAgent,c=e.hosts,l=e.queryParameters,f={hostsCache:t,logger:r,requester:n,requestsCache:a,responsesCache:u,timeouts:i,userAgent:s,headers:e.headers,queryParameters:l,hosts:c.map((function(e){return b(e)})),read:function(e,t){var r=m(t,f.timeouts.read),n=function(){return j(f,f.hosts.filter((function(e){return 0!=(e.accept&d.Read)})),e,r)};if(!0!==(void 0!==r.cacheable?r.cacheable:e.cacheable))return n();var a={request:e,mappedRequestOptions:r,transporter:{queryParameters:f.queryParameters,headers:f.headers}};return f.responsesCache.get(a,(function(){return f.requestsCache.get(a,(function(){return f.requestsCache.set(a,n()).then((function(e){return Promise.all([f.requestsCache.delete(a),e])}),(function(e){return Promise.all([f.requestsCache.delete(a),Promise.reject(e)])})).then((function(e){var t=o(e,2);t[0];return t[1]}))}))}),{miss:function(e){return f.responsesCache.set(a,e)}})},write:function(e,t){return j(f,f.hosts.filter((function(e){return 0!=(e.accept&d.Write)})),e,m(t,f.timeouts.write))}};return f}(r(r({hosts:[{url:"".concat(t,"-dsn.algolia.net"),accept:d.Read},{url:"".concat(t,".algolia.net"),accept:d.Write}].concat(c([{url:"".concat(t,"-1.algolianet.com")},{url:"".concat(t,"-2.algolianet.com")},{url:"".concat(t,"-3.algolianet.com")}]))},e),{},{headers:r(r(r({},n.headers()),{"content-type":"application/x-www-form-urlencoded"}),e.headers),queryParameters:r(r({},n.queryParameters()),e.queryParameters)}));return l({transporter:a,appId:t,addAlgoliaAgent:function(e,t){a.userAgent.add({segment:e,version:t})},clearCache:function(){return Promise.all([a.requestsCache.clear(),a.responsesCache.clear()]).then((function(){}))}},e.methods)},C=function(e){return function(t,r){return t.method===O?e.transporter.read(t,r):e.transporter.write(t,r)}},E=function(e){return function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n={transporter:e.transporter,appId:e.appId,indexName:t};return l(n,r.methods)}},J=function(e){return function(t,n){var o=t.map((function(e){return r(r({},e),{},{params:T(e.params||{})})}));return e.transporter.read({method:P,path:"1/indexes/*/queries",data:{requests:o},cacheable:!0},n)}},k=function(e){return function(t,o){return Promise.all(t.map((function(t){var a=t.params,u=a.facetName,i=a.facetQuery,s=n(a,["facetName","facetQuery"]);return E(e)(t.indexName,{methods:{searchForFacetValues:F}}).searchForFacetValues(u,i,r(r({},o),s))})))}},I=function(e){return function(t,r,n){return e.transporter.read({method:P,path:f("1/answers/%s/prediction",e.indexName),data:{query:t,queryLanguages:r},cacheable:!0},n)}},R=function(e){return function(t,r){return e.transporter.read({method:P,path:f("1/indexes/%s/query",e.indexName),data:{query:t},cacheable:!0},r)}},F=function(e){return function(t,r,n){return e.transporter.read({method:P,path:f("1/indexes/%s/facets/%s/query",e.indexName,t),data:{facetQuery:r},cacheable:!0},n)}},D=1,W=2,H=3;var Q=function(e){return function(t,n){var o=t.map((function(e){return r(r({},e),{},{threshold:e.threshold||0})}));return e.transporter.read({method:P,path:"1/indexes/*/recommendations",data:{requests:o},cacheable:!0},n)}};function L(e,t,n){var o,a={appId:e,apiKey:t,timeouts:{connect:1,read:2,write:30},requester:{send:function(e){return new Promise((function(t){var r=new XMLHttpRequest;r.open(e.method,e.url,!0),Object.keys(e.headers).forEach((function(t){return r.setRequestHeader(t,e.headers[t])}));var n,o=function(e,n){return setTimeout((function(){r.abort(),t({status:0,content:n,isTimedOut:!0})}),1e3*e)},a=o(e.connectTimeout,"Connection timeout");r.onreadystatechange=function(){r.readyState>r.OPENED&&void 0===n&&(clearTimeout(a),n=o(e.responseTimeout,"Socket timeout"))},r.onerror=function(){0===r.status&&(clearTimeout(a),clearTimeout(n),t({content:r.responseText||"Network request failed",status:r.status,isTimedOut:!1}))},r.onload=function(){clearTimeout(a),clearTimeout(n),t({content:r.responseText,status:r.status,isTimedOut:!1})},r.send(e.data)}))}},logger:(o=H,{debug:function(e,t){return D>=o&&console.debug(e,t),Promise.resolve()},info:function(e,t){return W>=o&&console.info(e,t),Promise.resolve()},error:function(e,t){return console.error(e,t),Promise.resolve()}}),responsesCache:s(),requestsCache:s({serializable:!1}),hostsCache:i({caches:[u({key:"".concat("4.24.0","-").concat(e)}),s()]}),userAgent:w("4.24.0").add({segment:"Browser",version:"lite"}),authMode:h.WithinQueryParameters};return N(r(r(r({},a),n),{},{methods:{search:J,searchForFacetValues:k,multipleQueries:J,multipleSearchForFacetValues:k,customRequest:C,initIndex:function(e){return function(t){return E(e)(t,{methods:{search:R,searchForFacetValues:F,findAnswers:I}})}},getRecommendations:Q}}))}return L.version="4.24.0",L})); diff --git a/scripts/node_modules/algoliasearch/dist/algoliasearch.cjs.js b/scripts/node_modules/algoliasearch/dist/algoliasearch.cjs.js new file mode 100644 index 000000000..a80d6a5a5 --- /dev/null +++ b/scripts/node_modules/algoliasearch/dist/algoliasearch.cjs.js @@ -0,0 +1,164 @@ +'use strict'; + +var cacheCommon = require('@algolia/cache-common'); +var cacheInMemory = require('@algolia/cache-in-memory'); +var clientAnalytics = require('@algolia/client-analytics'); +var clientCommon = require('@algolia/client-common'); +var clientPersonalization = require('@algolia/client-personalization'); +var clientSearch = require('@algolia/client-search'); +var loggerCommon = require('@algolia/logger-common'); +var recommend = require('@algolia/recommend'); +var requesterNodeHttp = require('@algolia/requester-node-http'); +var transporter = require('@algolia/transporter'); + +function algoliasearch(appId, apiKey, options) { + const commonOptions = { + appId, + apiKey, + timeouts: { + connect: 2, + read: 5, + write: 30, + }, + requester: requesterNodeHttp.createNodeHttpRequester(), + logger: loggerCommon.createNullLogger(), + responsesCache: cacheCommon.createNullCache(), + requestsCache: cacheCommon.createNullCache(), + hostsCache: cacheInMemory.createInMemoryCache(), + userAgent: transporter.createUserAgent(clientCommon.version).add({ + segment: 'Node.js', + version: process.versions.node, + }), + }; + const searchClientOptions = { ...commonOptions, ...options }; + const initPersonalization = () => (clientOptions) => { + return clientPersonalization.createPersonalizationClient({ + ...commonOptions, + ...clientOptions, + methods: { + getPersonalizationStrategy: clientPersonalization.getPersonalizationStrategy, + setPersonalizationStrategy: clientPersonalization.setPersonalizationStrategy, + }, + }); + }; + return clientSearch.createSearchClient({ + ...searchClientOptions, + methods: { + search: clientSearch.multipleQueries, + searchForFacetValues: clientSearch.multipleSearchForFacetValues, + multipleBatch: clientSearch.multipleBatch, + multipleGetObjects: clientSearch.multipleGetObjects, + multipleQueries: clientSearch.multipleQueries, + copyIndex: clientSearch.copyIndex, + copySettings: clientSearch.copySettings, + copyRules: clientSearch.copyRules, + copySynonyms: clientSearch.copySynonyms, + moveIndex: clientSearch.moveIndex, + listIndices: clientSearch.listIndices, + getLogs: clientSearch.getLogs, + listClusters: clientSearch.listClusters, + multipleSearchForFacetValues: clientSearch.multipleSearchForFacetValues, + getApiKey: clientSearch.getApiKey, + addApiKey: clientSearch.addApiKey, + listApiKeys: clientSearch.listApiKeys, + updateApiKey: clientSearch.updateApiKey, + deleteApiKey: clientSearch.deleteApiKey, + restoreApiKey: clientSearch.restoreApiKey, + assignUserID: clientSearch.assignUserID, + assignUserIDs: clientSearch.assignUserIDs, + getUserID: clientSearch.getUserID, + searchUserIDs: clientSearch.searchUserIDs, + listUserIDs: clientSearch.listUserIDs, + getTopUserIDs: clientSearch.getTopUserIDs, + removeUserID: clientSearch.removeUserID, + hasPendingMappings: clientSearch.hasPendingMappings, + generateSecuredApiKey: clientSearch.generateSecuredApiKey, + getSecuredApiKeyRemainingValidity: clientSearch.getSecuredApiKeyRemainingValidity, + destroy: clientCommon.destroy, + clearDictionaryEntries: clientSearch.clearDictionaryEntries, + deleteDictionaryEntries: clientSearch.deleteDictionaryEntries, + getDictionarySettings: clientSearch.getDictionarySettings, + getAppTask: clientSearch.getAppTask, + replaceDictionaryEntries: clientSearch.replaceDictionaryEntries, + saveDictionaryEntries: clientSearch.saveDictionaryEntries, + searchDictionaryEntries: clientSearch.searchDictionaryEntries, + setDictionarySettings: clientSearch.setDictionarySettings, + waitAppTask: clientSearch.waitAppTask, + customRequest: clientSearch.customRequest, + initIndex: base => (indexName) => { + return clientSearch.initIndex(base)(indexName, { + methods: { + batch: clientSearch.batch, + delete: clientSearch.deleteIndex, + findAnswers: clientSearch.findAnswers, + getObject: clientSearch.getObject, + getObjects: clientSearch.getObjects, + saveObject: clientSearch.saveObject, + saveObjects: clientSearch.saveObjects, + search: clientSearch.search, + searchForFacetValues: clientSearch.searchForFacetValues, + waitTask: clientSearch.waitTask, + setSettings: clientSearch.setSettings, + getSettings: clientSearch.getSettings, + partialUpdateObject: clientSearch.partialUpdateObject, + partialUpdateObjects: clientSearch.partialUpdateObjects, + deleteObject: clientSearch.deleteObject, + deleteObjects: clientSearch.deleteObjects, + deleteBy: clientSearch.deleteBy, + clearObjects: clientSearch.clearObjects, + browseObjects: clientSearch.browseObjects, + getObjectPosition: clientSearch.getObjectPosition, + findObject: clientSearch.findObject, + exists: clientSearch.exists, + saveSynonym: clientSearch.saveSynonym, + saveSynonyms: clientSearch.saveSynonyms, + getSynonym: clientSearch.getSynonym, + searchSynonyms: clientSearch.searchSynonyms, + browseSynonyms: clientSearch.browseSynonyms, + deleteSynonym: clientSearch.deleteSynonym, + clearSynonyms: clientSearch.clearSynonyms, + replaceAllObjects: clientSearch.replaceAllObjects, + replaceAllSynonyms: clientSearch.replaceAllSynonyms, + searchRules: clientSearch.searchRules, + getRule: clientSearch.getRule, + deleteRule: clientSearch.deleteRule, + saveRule: clientSearch.saveRule, + saveRules: clientSearch.saveRules, + replaceAllRules: clientSearch.replaceAllRules, + browseRules: clientSearch.browseRules, + clearRules: clientSearch.clearRules, + }, + }); + }, + initAnalytics: () => (clientOptions) => { + return clientAnalytics.createAnalyticsClient({ + ...commonOptions, + ...clientOptions, + methods: { + addABTest: clientAnalytics.addABTest, + getABTest: clientAnalytics.getABTest, + getABTests: clientAnalytics.getABTests, + stopABTest: clientAnalytics.stopABTest, + deleteABTest: clientAnalytics.deleteABTest, + }, + }); + }, + initPersonalization, + initRecommendation: () => (clientOptions) => { + searchClientOptions.logger.info('The `initRecommendation` method is deprecated. Use `initPersonalization` instead.'); + return initPersonalization()(clientOptions); + }, + getRecommendations: recommend.getRecommendations, + getFrequentlyBoughtTogether: recommend.getFrequentlyBoughtTogether, + getLookingSimilar: recommend.getLookingSimilar, + getRecommendedForYou: recommend.getRecommendedForYou, + getRelatedProducts: recommend.getRelatedProducts, + getTrendingFacets: recommend.getTrendingFacets, + getTrendingItems: recommend.getTrendingItems, + }, + }); +} +// eslint-disable-next-line functional/immutable-data +algoliasearch.version = clientCommon.version; + +module.exports = algoliasearch; diff --git a/scripts/node_modules/algoliasearch/dist/algoliasearch.d.ts b/scripts/node_modules/algoliasearch/dist/algoliasearch.d.ts new file mode 100644 index 000000000..881ed757c --- /dev/null +++ b/scripts/node_modules/algoliasearch/dist/algoliasearch.d.ts @@ -0,0 +1,255 @@ +import { ABTest } from '@algolia/client-analytics'; +import { AddABTestResponse } from '@algolia/client-analytics'; +import { AddApiKeyOptions } from '@algolia/client-search'; +import { AddApiKeyResponse } from '@algolia/client-search'; +import { AnalyticsClient as AnalyticsClient_2 } from '@algolia/client-analytics'; +import { AnalyticsClientOptions } from '@algolia/client-analytics'; +import { ApiKeyACLType } from '@algolia/client-search'; +import { AssignUserIDResponse } from '@algolia/client-search'; +import { AssignUserIDsResponse } from '@algolia/client-search'; +import { BatchRequest } from '@algolia/client-search'; +import { BatchResponse } from '@algolia/client-search'; +import { BrowseOptions } from '@algolia/client-search'; +import { ChunkedBatchResponse } from '@algolia/client-search'; +import { ChunkOptions } from '@algolia/client-search'; +import { ClearRulesOptions } from '@algolia/client-search'; +import { ClearSynonymsOptions } from '@algolia/client-search'; +import { ClientTransporterOptions } from '@algolia/client-common'; +import { CopyIndexOptions } from '@algolia/client-search'; +import { DeleteABTestResponse } from '@algolia/client-analytics'; +import { DeleteApiKeyResponse } from '@algolia/client-search'; +import { DeleteByFiltersOptions } from '@algolia/client-search'; +import { DeleteResponse } from '@algolia/client-search'; +import { DeleteSynonymOptions } from '@algolia/client-search'; +import { Destroyable } from '@algolia/requester-common'; +import { DictionaryEntriesOptions } from '@algolia/client-search'; +import { DictionaryEntriesResponse } from '@algolia/client-search'; +import { DictionaryEntry } from '@algolia/client-search'; +import { DictionaryName } from '@algolia/client-search'; +import { DictionarySettings } from '@algolia/client-search'; +import { FindAnswersOptions } from '@algolia/client-search'; +import { FindAnswersResponse } from '@algolia/client-search'; +import { FindObjectOptions } from '@algolia/client-search'; +import { FindObjectResponse } from '@algolia/client-search'; +import { GetABTestResponse } from '@algolia/client-analytics'; +import { GetABTestsOptions } from '@algolia/client-analytics'; +import { GetABTestsResponse } from '@algolia/client-analytics'; +import { GetApiKeyResponse } from '@algolia/client-search'; +import { GetDictionarySettingsResponse } from '@algolia/client-search'; +import { GetLogsResponse } from '@algolia/client-search'; +import { GetObjectOptions } from '@algolia/client-search'; +import { GetObjectsOptions } from '@algolia/client-search'; +import { GetObjectsResponse } from '@algolia/client-search'; +import { GetPersonalizationStrategyResponse } from '@algolia/client-personalization'; +import { GetTopUserIDsResponse } from '@algolia/client-search'; +import { HasPendingMappingsOptions } from '@algolia/client-search'; +import { HasPendingMappingsResponse } from '@algolia/client-search'; +import { IndexOperationResponse } from '@algolia/client-search'; +import { ListApiKeysResponse } from '@algolia/client-search'; +import { ListClustersResponse } from '@algolia/client-search'; +import { ListIndicesResponse } from '@algolia/client-search'; +import { ListUserIDsOptions } from '@algolia/client-search'; +import { ListUserIDsResponse } from '@algolia/client-search'; +import { MultipleBatchRequest } from '@algolia/client-search'; +import { MultipleBatchResponse } from '@algolia/client-search'; +import { MultipleGetObject } from '@algolia/client-search'; +import { MultipleGetObjectsResponse } from '@algolia/client-search'; +import { MultipleQueriesOptions } from '@algolia/client-search'; +import { MultipleQueriesQuery } from '@algolia/client-search'; +import { MultipleQueriesResponse } from '@algolia/client-search'; +import { ObjectWithObjectID } from '@algolia/client-search'; +import { PartialUpdateObjectResponse } from '@algolia/client-search'; +import { PartialUpdateObjectsOptions } from '@algolia/client-search'; +import { PersonalizationClient as PersonalizationClient_2 } from '@algolia/client-personalization'; +import { PersonalizationClientOptions } from '@algolia/client-personalization'; +import { PersonalizationStrategy } from '@algolia/client-personalization'; +import { RemoveUserIDResponse } from '@algolia/client-search'; +import { ReplaceAllObjectsOptions } from '@algolia/client-search'; +import { Request as Request_2 } from '@algolia/transporter'; +import { RequestOptions } from '@algolia/transporter'; +import { RestoreApiKeyResponse } from '@algolia/client-search'; +import { Rule } from '@algolia/client-search'; +import { SaveObjectResponse } from '@algolia/client-search'; +import { SaveObjectsOptions } from '@algolia/client-search'; +import { SaveRuleResponse } from '@algolia/client-search'; +import { SaveRulesOptions } from '@algolia/client-search'; +import { SaveRulesResponse } from '@algolia/client-search'; +import { SaveSynonymResponse } from '@algolia/client-search'; +import { SaveSynonymsOptions } from '@algolia/client-search'; +import { SaveSynonymsResponse } from '@algolia/client-search'; +import { SearchClient as SearchClient_2 } from '@algolia/client-search'; +import { SearchClientOptions } from '@algolia/client-search'; +import { SearchDictionaryEntriesResponse } from '@algolia/client-search'; +import { SearchForFacetValuesQueryParams } from '@algolia/client-search'; +import { SearchForFacetValuesResponse } from '@algolia/client-search'; +import { SearchIndex as SearchIndex_2 } from '@algolia/client-search'; +import { SearchOptions } from '@algolia/client-search'; +import { SearchResponse } from '@algolia/client-search'; +import { SearchRulesOptions } from '@algolia/client-search'; +import { SearchSynonymsOptions } from '@algolia/client-search'; +import { SearchSynonymsResponse } from '@algolia/client-search'; +import { SearchUserIDsOptions } from '@algolia/client-search'; +import { SearchUserIDsResponse } from '@algolia/client-search'; +import { SecuredApiKeyRestrictions } from '@algolia/client-search'; +import { SetPersonalizationStrategyResponse } from '@algolia/client-personalization'; +import { SetSettingsResponse } from '@algolia/client-search'; +import { Settings } from '@algolia/client-search'; +import { StopABTestResponse } from '@algolia/client-analytics'; +import { Synonym } from '@algolia/client-search'; +import { TaskStatusResponse } from '@algolia/client-search'; +import { UpdateApiKeyOptions } from '@algolia/client-search'; +import { UpdateApiKeyResponse } from '@algolia/client-search'; +import { UserIDResponse } from '@algolia/client-search'; +import { WaitablePromise } from '@algolia/client-common'; +import { WithRecommendMethods } from '@algolia/recommend'; + +declare function algoliasearch(appId: string, apiKey: string, options?: AlgoliaSearchOptions): SearchClient; + +declare namespace algoliasearch { + var version: string; +} +export default algoliasearch; + +export declare type AlgoliaSearchOptions = Partial & WithoutCredentials; + +export declare type AnalyticsClient = AnalyticsClient_2 & { + readonly addABTest: (abTest: ABTest, requestOptions?: RequestOptions) => Readonly>; + readonly getABTest: (abTestID: number, requestOptions?: RequestOptions) => Readonly>; + readonly getABTests: (requestOptions?: RequestOptions & GetABTestsOptions) => Readonly>; + readonly stopABTest: (abTestID: number, requestOptions?: RequestOptions) => Readonly>; + readonly deleteABTest: (abTestID: number, requestOptions?: RequestOptions) => Readonly>; +}; + +declare type Credentials = { + readonly appId: string; + readonly apiKey: string; +}; + +export declare type InitAnalyticsOptions = Partial & OptionalCredentials; + +export declare type InitPersonalizationOptions = Partial & OptionalCredentials; + +/** + * @deprecated Use `InitPersonalizationOptions` instead. + */ +export declare type InitRecommendationOptions = InitPersonalizationOptions; + +export declare type OptionalCredentials = Omit & Pick, keyof Credentials>; + +export declare type PersonalizationClient = PersonalizationClient_2 & { + readonly getPersonalizationStrategy: (requestOptions?: RequestOptions) => Readonly>; + readonly setPersonalizationStrategy: (personalizationStrategy: PersonalizationStrategy, requestOptions?: RequestOptions) => Readonly>; +}; + +/** + * @deprecated Use `PersonalizationClient` instead. + */ +export declare type RecommendationClient = PersonalizationClient; + +export declare type SearchClient = SearchClient_2 & { + readonly initIndex: (indexName: string) => SearchIndex; + readonly search: (queries: readonly MultipleQueriesQuery[], requestOptions?: RequestOptions & MultipleQueriesOptions) => Readonly>>; + readonly searchForFacetValues: (queries: ReadonlyArray<{ + readonly indexName: string; + readonly params: SearchForFacetValuesQueryParams & SearchOptions; + }>, requestOptions?: RequestOptions) => Readonly>; + readonly multipleBatch: (requests: readonly MultipleBatchRequest[], requestOptions?: RequestOptions) => Readonly>; + readonly multipleGetObjects: (requests: readonly MultipleGetObject[], requestOptions?: RequestOptions) => Readonly>>; + readonly multipleQueries: (queries: readonly MultipleQueriesQuery[], requestOptions?: RequestOptions & MultipleQueriesOptions) => Readonly>>; + readonly copyIndex: (from: string, to: string, requestOptions?: CopyIndexOptions & RequestOptions) => Readonly>; + readonly copySettings: (from: string, to: string, requestOptions?: RequestOptions) => Readonly>; + readonly copyRules: (from: string, to: string, requestOptions?: RequestOptions) => Readonly>; + readonly copySynonyms: (from: string, to: string, requestOptions?: RequestOptions) => Readonly>; + readonly moveIndex: (from: string, to: string, requestOptions?: RequestOptions) => Readonly>; + readonly listIndices: (requestOptions?: RequestOptions) => Readonly>; + readonly getLogs: (requestOptions?: RequestOptions) => Readonly>; + readonly listClusters: (requestOptions?: RequestOptions) => Readonly>; + readonly multipleSearchForFacetValues: (queries: ReadonlyArray<{ + readonly indexName: string; + readonly params: SearchForFacetValuesQueryParams & SearchOptions; + }>, requestOptions?: RequestOptions) => Readonly>; + readonly getApiKey: (apiKey: string, requestOptions?: RequestOptions) => Readonly>; + readonly addApiKey: (acl: readonly ApiKeyACLType[], requestOptions?: AddApiKeyOptions & Pick>) => Readonly>; + readonly listApiKeys: (requestOptions?: RequestOptions) => Readonly>; + readonly updateApiKey: (apiKey: string, requestOptions?: UpdateApiKeyOptions & Pick>) => Readonly>; + readonly deleteApiKey: (apiKey: string, requestOptions?: RequestOptions) => Readonly>; + readonly restoreApiKey: (apiKey: string, requestOptions?: RequestOptions) => Readonly>; + readonly assignUserID: (userID: string, clusterName: string, requestOptions?: RequestOptions) => Readonly>; + readonly assignUserIDs: (userIDs: readonly string[], clusterName: string, requestOptions?: RequestOptions) => Readonly>; + readonly getUserID: (userID: string, requestOptions?: RequestOptions) => Readonly>; + readonly searchUserIDs: (query: string, requestOptions?: SearchUserIDsOptions & RequestOptions) => Readonly>; + readonly listUserIDs: (requestOptions?: ListUserIDsOptions & RequestOptions) => Readonly>; + readonly getTopUserIDs: (requestOptions?: RequestOptions) => Readonly>; + readonly removeUserID: (userID: string, requestOptions?: RequestOptions) => Readonly>; + readonly hasPendingMappings: (requestOptions?: HasPendingMappingsOptions & RequestOptions) => Readonly>; + readonly generateSecuredApiKey: (parentApiKey: string, restrictions: SecuredApiKeyRestrictions) => string; + readonly getSecuredApiKeyRemainingValidity: (securedApiKey: string) => number; + readonly clearDictionaryEntries: (dictionary: DictionaryName, requestOptions?: RequestOptions & DictionaryEntriesOptions) => Readonly>; + readonly deleteDictionaryEntries: (dictionary: DictionaryName, objectIDs: readonly string[], requestOptions?: RequestOptions & DictionaryEntriesOptions) => Readonly>; + readonly replaceDictionaryEntries: (dictionary: DictionaryName, entries: readonly DictionaryEntry[], requestOptions?: RequestOptions & DictionaryEntriesOptions) => Readonly>; + readonly saveDictionaryEntries: (dictionary: DictionaryName, entries: readonly DictionaryEntry[], requestOptions?: RequestOptions & DictionaryEntriesOptions) => Readonly>; + readonly searchDictionaryEntries: (dictionary: DictionaryName, query: string, requestOptions?: RequestOptions) => Readonly>; + readonly getDictionarySettings: (requestOptions?: RequestOptions) => Readonly>; + readonly setDictionarySettings: (settings: DictionarySettings, requestOptions?: RequestOptions) => Readonly>; + readonly getAppTask: (taskID: number, requestOptions?: RequestOptions) => Readonly>; + readonly customRequest: (request: Request_2, requestOptions?: RequestOptions) => Readonly>; + readonly initAnalytics: (options?: InitAnalyticsOptions) => AnalyticsClient; + readonly initPersonalization: (options?: InitPersonalizationOptions) => PersonalizationClient; + /** + * @deprecated Use `initPersonalization` instead. + */ + readonly initRecommendation: (options?: InitPersonalizationOptions) => PersonalizationClient; + readonly getRecommendations: WithRecommendMethods['getRecommendations']; + readonly getFrequentlyBoughtTogether: WithRecommendMethods['getFrequentlyBoughtTogether']; + readonly getLookingSimilar: WithRecommendMethods['getLookingSimilar']; + readonly getRecommendedForYou: WithRecommendMethods['getRecommendedForYou']; + readonly getRelatedProducts: WithRecommendMethods['getRelatedProducts']; + readonly getTrendingFacets: WithRecommendMethods['getTrendingFacets']; + readonly getTrendingItems: WithRecommendMethods['getTrendingItems']; +} & Destroyable; + +export declare type SearchIndex = SearchIndex_2 & { + readonly search: (query: string, requestOptions?: RequestOptions & SearchOptions) => Readonly>>; + readonly searchForFacetValues: (facetName: string, facetQuery: string, requestOptions?: RequestOptions & SearchOptions) => Readonly>; + readonly findAnswers: (query: string, queryLanguages: readonly string[], requestOptions?: RequestOptions & FindAnswersOptions) => Readonly>>; + readonly batch: (requests: readonly BatchRequest[], requestOptions?: RequestOptions) => Readonly>; + readonly delete: (requestOptions?: RequestOptions) => Readonly>; + readonly getObject: (objectID: string, requestOptions?: RequestOptions & GetObjectOptions) => Readonly>; + readonly getObjects: (objectIDs: readonly string[], requestOptions?: RequestOptions & GetObjectsOptions) => Readonly>>; + readonly saveObject: (object: Readonly>, requestOptions?: RequestOptions & ChunkOptions & SaveObjectsOptions) => Readonly>; + readonly saveObjects: (objects: ReadonlyArray>>, requestOptions?: RequestOptions & ChunkOptions & SaveObjectsOptions) => Readonly>; + readonly waitTask: (taskID: number, requestOptions?: RequestOptions) => Readonly>; + readonly setSettings: (settings: Settings, requestOptions?: RequestOptions) => Readonly>; + readonly getSettings: (requestOptions?: RequestOptions) => Readonly>; + readonly partialUpdateObject: (object: Record, requestOptions?: RequestOptions & ChunkOptions & PartialUpdateObjectsOptions) => Readonly>; + readonly partialUpdateObjects: (objects: ReadonlyArray>, requestOptions?: RequestOptions & ChunkOptions & PartialUpdateObjectsOptions) => Readonly>; + readonly deleteObject: (objectID: string, requestOptions?: RequestOptions) => Readonly>; + readonly deleteObjects: (objectIDs: readonly string[], requestOptions?: RequestOptions & ChunkOptions) => Readonly>; + readonly deleteBy: (filters: DeleteByFiltersOptions, requestOptions?: RequestOptions) => Readonly>; + readonly clearObjects: (requestOptions?: RequestOptions) => Readonly>; + readonly browseObjects: (requestOptions?: SearchOptions & BrowseOptions & RequestOptions) => Readonly>; + readonly getObjectPosition: (searchResponse: SearchResponse<{}>, objectID: string) => number; + readonly findObject: (callback: (object: TObject & ObjectWithObjectID) => boolean, requestOptions?: FindObjectOptions & RequestOptions) => Readonly>>; + readonly exists: (requestOptions?: RequestOptions) => Readonly>; + readonly saveSynonym: (synonym: Synonym, requestOptions?: RequestOptions & SaveSynonymsOptions) => Readonly>; + readonly saveSynonyms: (synonyms: readonly Synonym[], requestOptions?: SaveSynonymsOptions & RequestOptions) => Readonly>; + readonly getSynonym: (objectID: string, requestOptions?: RequestOptions) => Readonly>; + readonly searchSynonyms: (query: string, requestOptions?: SearchSynonymsOptions & RequestOptions) => Readonly>; + readonly browseSynonyms: (requestOptions?: SearchSynonymsOptions & BrowseOptions & RequestOptions) => Readonly>; + readonly deleteSynonym: (objectID: string, requestOptions?: DeleteSynonymOptions & RequestOptions) => Readonly>; + readonly clearSynonyms: (requestOptions?: ClearSynonymsOptions & RequestOptions) => Readonly>; + readonly replaceAllObjects: (objects: ReadonlyArray>>, requestOptions?: ReplaceAllObjectsOptions & ChunkOptions & SaveObjectsOptions & RequestOptions) => Readonly>; + readonly replaceAllSynonyms: (synonyms: readonly Synonym[], requestOptions?: RequestOptions & Pick>) => Readonly>; + readonly searchRules: (query: string, requestOptions?: RequestOptions & SearchRulesOptions) => Readonly>>; + readonly getRule: (objectID: string, requestOptions?: RequestOptions) => Readonly>; + readonly deleteRule: (objectID: string, requestOptions?: RequestOptions) => Readonly>; + readonly saveRule: (rule: Rule, requestOptions?: RequestOptions & SaveRulesOptions) => Readonly>; + readonly saveRules: (rules: readonly Rule[], requestOptions?: RequestOptions & SaveRulesOptions) => Readonly>; + readonly replaceAllRules: (rules: readonly Rule[], requestOptions?: RequestOptions & SaveRulesOptions) => Readonly>; + readonly browseRules: (requestOptions?: SearchRulesOptions & BrowseOptions & RequestOptions) => Readonly>; + readonly clearRules: (requestOptions?: RequestOptions & ClearRulesOptions) => Readonly>; +}; + +export declare type WithoutCredentials = Omit; + +export { } diff --git a/scripts/node_modules/algoliasearch/dist/algoliasearch.esm.browser.js b/scripts/node_modules/algoliasearch/dist/algoliasearch.esm.browser.js new file mode 100644 index 000000000..ec903ed0d --- /dev/null +++ b/scripts/node_modules/algoliasearch/dist/algoliasearch.esm.browser.js @@ -0,0 +1,2371 @@ +function createBrowserLocalStorageCache(options) { + const namespaceKey = `algoliasearch-client-js-${options.key}`; + // eslint-disable-next-line functional/no-let + let storage; + const getStorage = () => { + if (storage === undefined) { + storage = options.localStorage || window.localStorage; + } + return storage; + }; + const getNamespace = () => { + return JSON.parse(getStorage().getItem(namespaceKey) || '{}'); + }; + const setNamespace = (namespace) => { + getStorage().setItem(namespaceKey, JSON.stringify(namespace)); + }; + const removeOutdatedCacheItems = () => { + const timeToLive = options.timeToLive ? options.timeToLive * 1000 : null; + const namespace = getNamespace(); + const filteredNamespaceWithoutOldFormattedCacheItems = Object.fromEntries(Object.entries(namespace).filter(([, cacheItem]) => { + return cacheItem.timestamp !== undefined; + })); + setNamespace(filteredNamespaceWithoutOldFormattedCacheItems); + if (!timeToLive) + return; + const filteredNamespaceWithoutExpiredItems = Object.fromEntries(Object.entries(filteredNamespaceWithoutOldFormattedCacheItems).filter(([, cacheItem]) => { + const currentTimestamp = new Date().getTime(); + const isExpired = cacheItem.timestamp + timeToLive < currentTimestamp; + return !isExpired; + })); + setNamespace(filteredNamespaceWithoutExpiredItems); + }; + return { + get(key, defaultValue, events = { + miss: () => Promise.resolve(), + }) { + return Promise.resolve() + .then(() => { + removeOutdatedCacheItems(); + const keyAsString = JSON.stringify(key); + return getNamespace()[keyAsString]; + }) + .then(value => { + return Promise.all([value ? value.value : defaultValue(), value !== undefined]); + }) + .then(([value, exists]) => { + return Promise.all([value, exists || events.miss(value)]); + }) + .then(([value]) => value); + }, + set(key, value) { + return Promise.resolve().then(() => { + const namespace = getNamespace(); + // eslint-disable-next-line functional/immutable-data + namespace[JSON.stringify(key)] = { + timestamp: new Date().getTime(), + value, + }; + getStorage().setItem(namespaceKey, JSON.stringify(namespace)); + return value; + }); + }, + delete(key) { + return Promise.resolve().then(() => { + const namespace = getNamespace(); + // eslint-disable-next-line functional/immutable-data + delete namespace[JSON.stringify(key)]; + getStorage().setItem(namespaceKey, JSON.stringify(namespace)); + }); + }, + clear() { + return Promise.resolve().then(() => { + getStorage().removeItem(namespaceKey); + }); + }, + }; +} + +// @todo Add logger on options to debug when caches go wrong. +function createFallbackableCache(options) { + const caches = [...options.caches]; + const current = caches.shift(); // eslint-disable-line functional/immutable-data + if (current === undefined) { + return createNullCache(); + } + return { + get(key, defaultValue, events = { + miss: () => Promise.resolve(), + }) { + return current.get(key, defaultValue, events).catch(() => { + return createFallbackableCache({ caches }).get(key, defaultValue, events); + }); + }, + set(key, value) { + return current.set(key, value).catch(() => { + return createFallbackableCache({ caches }).set(key, value); + }); + }, + delete(key) { + return current.delete(key).catch(() => { + return createFallbackableCache({ caches }).delete(key); + }); + }, + clear() { + return current.clear().catch(() => { + return createFallbackableCache({ caches }).clear(); + }); + }, + }; +} + +function createNullCache() { + return { + get(_key, defaultValue, events = { + miss: () => Promise.resolve(), + }) { + const value = defaultValue(); + return value + .then(result => Promise.all([result, events.miss(result)])) + .then(([result]) => result); + }, + set(_key, value) { + return Promise.resolve(value); + }, + delete(_key) { + return Promise.resolve(); + }, + clear() { + return Promise.resolve(); + }, + }; +} + +function createInMemoryCache(options = { serializable: true }) { + // eslint-disable-next-line functional/no-let + let cache = {}; + return { + get(key, defaultValue, events = { + miss: () => Promise.resolve(), + }) { + const keyAsString = JSON.stringify(key); + if (keyAsString in cache) { + return Promise.resolve(options.serializable ? JSON.parse(cache[keyAsString]) : cache[keyAsString]); + } + const promise = defaultValue(); + const miss = (events && events.miss) || (() => Promise.resolve()); + return promise.then((value) => miss(value)).then(() => promise); + }, + set(key, value) { + // eslint-disable-next-line functional/immutable-data + cache[JSON.stringify(key)] = options.serializable ? JSON.stringify(value) : value; + return Promise.resolve(value); + }, + delete(key) { + // eslint-disable-next-line functional/immutable-data + delete cache[JSON.stringify(key)]; + return Promise.resolve(); + }, + clear() { + cache = {}; + return Promise.resolve(); + }, + }; +} + +function createAuth(authMode, appId, apiKey) { + const credentials = { + 'x-algolia-api-key': apiKey, + 'x-algolia-application-id': appId, + }; + return { + headers() { + return authMode === AuthMode.WithinHeaders ? credentials : {}; + }, + queryParameters() { + return authMode === AuthMode.WithinQueryParameters ? credentials : {}; + }, + }; +} + +function createRetryablePromise(callback) { + let retriesCount = 0; // eslint-disable-line functional/no-let + const retry = () => { + retriesCount++; + return new Promise((resolve) => { + setTimeout(() => { + resolve(callback(retry)); + }, Math.min(100 * retriesCount, 1000)); + }); + }; + return callback(retry); +} + +function createWaitablePromise(promise, wait = (_response, _requestOptions) => { + return Promise.resolve(); +}) { + // eslint-disable-next-line functional/immutable-data + return Object.assign(promise, { + wait(requestOptions) { + return createWaitablePromise(promise + .then(response => Promise.all([wait(response, requestOptions), response])) + .then(promiseResults => promiseResults[1])); + }, + }); +} + +// eslint-disable-next-line functional/prefer-readonly-type +function shuffle(array) { + let c = array.length - 1; // eslint-disable-line functional/no-let + // eslint-disable-next-line functional/no-loop-statement + for (c; c > 0; c--) { + const b = Math.floor(Math.random() * (c + 1)); + const a = array[c]; + array[c] = array[b]; // eslint-disable-line functional/immutable-data, no-param-reassign + array[b] = a; // eslint-disable-line functional/immutable-data, no-param-reassign + } + return array; +} +function addMethods(base, methods) { + if (!methods) { + return base; + } + Object.keys(methods).forEach(key => { + // eslint-disable-next-line functional/immutable-data, no-param-reassign + base[key] = methods[key](base); + }); + return base; +} +function encode(format, ...args) { + // eslint-disable-next-line functional/no-let + let i = 0; + return format.replace(/%s/g, () => encodeURIComponent(args[i++])); +} + +const version = '4.24.0'; + +const AuthMode = { + /** + * If auth credentials should be in query parameters. + */ + WithinQueryParameters: 0, + /** + * If auth credentials should be in headers. + */ + WithinHeaders: 1, +}; + +function createMappedRequestOptions(requestOptions, timeout) { + const options = requestOptions || {}; + const data = options.data || {}; + Object.keys(options).forEach(key => { + if (['timeout', 'headers', 'queryParameters', 'data', 'cacheable'].indexOf(key) === -1) { + data[key] = options[key]; // eslint-disable-line functional/immutable-data + } + }); + return { + data: Object.entries(data).length > 0 ? data : undefined, + timeout: options.timeout || timeout, + headers: options.headers || {}, + queryParameters: options.queryParameters || {}, + cacheable: options.cacheable, + }; +} + +const CallEnum = { + /** + * If the host is read only. + */ + Read: 1, + /** + * If the host is write only. + */ + Write: 2, + /** + * If the host is both read and write. + */ + Any: 3, +}; + +const HostStatusEnum = { + Up: 1, + Down: 2, + Timeouted: 3, +}; + +// By default, API Clients at Algolia have expiration delay +// of 5 mins. In the JavaScript client, we have 2 mins. +const EXPIRATION_DELAY = 2 * 60 * 1000; +function createStatefulHost(host, status = HostStatusEnum.Up) { + return { + ...host, + status, + lastUpdate: Date.now(), + }; +} +function isStatefulHostUp(host) { + return host.status === HostStatusEnum.Up || Date.now() - host.lastUpdate > EXPIRATION_DELAY; +} +function isStatefulHostTimeouted(host) { + return (host.status === HostStatusEnum.Timeouted && Date.now() - host.lastUpdate <= EXPIRATION_DELAY); +} + +function createStatelessHost(options) { + if (typeof options === 'string') { + return { + protocol: 'https', + url: options, + accept: CallEnum.Any, + }; + } + return { + protocol: options.protocol || 'https', + url: options.url, + accept: options.accept || CallEnum.Any, + }; +} + +const MethodEnum = { + Delete: 'DELETE', + Get: 'GET', + Post: 'POST', + Put: 'PUT', +}; + +function createRetryableOptions(hostsCache, statelessHosts) { + return Promise.all(statelessHosts.map(statelessHost => { + return hostsCache.get(statelessHost, () => { + return Promise.resolve(createStatefulHost(statelessHost)); + }); + })).then(statefulHosts => { + const hostsUp = statefulHosts.filter(host => isStatefulHostUp(host)); + const hostsTimeouted = statefulHosts.filter(host => isStatefulHostTimeouted(host)); + /** + * Note, we put the hosts that previously timeouted on the end of the list. + */ + const hostsAvailable = [...hostsUp, ...hostsTimeouted]; + const statelessHostsAvailable = hostsAvailable.length > 0 + ? hostsAvailable.map(host => createStatelessHost(host)) + : statelessHosts; + return { + getTimeout(timeoutsCount, baseTimeout) { + /** + * Imagine that you have 4 hosts, if timeouts will increase + * on the following way: 1 (timeouted) > 4 (timeouted) > 5 (200) + * + * Note that, the very next request, we start from the previous timeout + * + * 5 (timeouted) > 6 (timeouted) > 7 ... + * + * This strategy may need to be reviewed, but is the strategy on the our + * current v3 version. + */ + const timeoutMultiplier = hostsTimeouted.length === 0 && timeoutsCount === 0 + ? 1 + : hostsTimeouted.length + 3 + timeoutsCount; + return timeoutMultiplier * baseTimeout; + }, + statelessHosts: statelessHostsAvailable, + }; + }); +} + +const isNetworkError = ({ isTimedOut, status }) => { + return !isTimedOut && ~~status === 0; +}; +const isRetryable = (response) => { + const status = response.status; + const isTimedOut = response.isTimedOut; + return (isTimedOut || isNetworkError(response) || (~~(status / 100) !== 2 && ~~(status / 100) !== 4)); +}; +const isSuccess = ({ status }) => { + return ~~(status / 100) === 2; +}; +const retryDecision = (response, outcomes) => { + if (isRetryable(response)) { + return outcomes.onRetry(response); + } + if (isSuccess(response)) { + return outcomes.onSuccess(response); + } + return outcomes.onFail(response); +}; + +function retryableRequest(transporter, statelessHosts, request, requestOptions) { + const stackTrace = []; // eslint-disable-line functional/prefer-readonly-type + /** + * First we prepare the payload that do not depend from hosts. + */ + const data = serializeData(request, requestOptions); + const headers = serializeHeaders(transporter, requestOptions); + const method = request.method; + // On `GET`, the data is proxied to query parameters. + const dataQueryParameters = request.method !== MethodEnum.Get + ? {} + : { + ...request.data, + ...requestOptions.data, + }; + const queryParameters = { + 'x-algolia-agent': transporter.userAgent.value, + ...transporter.queryParameters, + ...dataQueryParameters, + ...requestOptions.queryParameters, + }; + let timeoutsCount = 0; // eslint-disable-line functional/no-let + const retry = (hosts, // eslint-disable-line functional/prefer-readonly-type + getTimeout) => { + /** + * We iterate on each host, until there is no host left. + */ + const host = hosts.pop(); // eslint-disable-line functional/immutable-data + if (host === undefined) { + throw createRetryError(stackTraceWithoutCredentials(stackTrace)); + } + const payload = { + data, + headers, + method, + url: serializeUrl(host, request.path, queryParameters), + connectTimeout: getTimeout(timeoutsCount, transporter.timeouts.connect), + responseTimeout: getTimeout(timeoutsCount, requestOptions.timeout), + }; + /** + * The stackFrame is pushed to the stackTrace so we + * can have information about onRetry and onFailure + * decisions. + */ + const pushToStackTrace = (response) => { + const stackFrame = { + request: payload, + response, + host, + triesLeft: hosts.length, + }; + // eslint-disable-next-line functional/immutable-data + stackTrace.push(stackFrame); + return stackFrame; + }; + const decisions = { + onSuccess: response => deserializeSuccess(response), + onRetry(response) { + const stackFrame = pushToStackTrace(response); + /** + * If response is a timeout, we increaset the number of + * timeouts so we can increase the timeout later. + */ + if (response.isTimedOut) { + timeoutsCount++; + } + return Promise.all([ + /** + * Failures are individually send the logger, allowing + * the end user to debug / store stack frames even + * when a retry error does not happen. + */ + transporter.logger.info('Retryable failure', stackFrameWithoutCredentials(stackFrame)), + /** + * We also store the state of the host in failure cases. If the host, is + * down it will remain down for the next 2 minutes. In a timeout situation, + * this host will be added end of the list of hosts on the next request. + */ + transporter.hostsCache.set(host, createStatefulHost(host, response.isTimedOut ? HostStatusEnum.Timeouted : HostStatusEnum.Down)), + ]).then(() => retry(hosts, getTimeout)); + }, + onFail(response) { + pushToStackTrace(response); + throw deserializeFailure(response, stackTraceWithoutCredentials(stackTrace)); + }, + }; + return transporter.requester.send(payload).then(response => { + return retryDecision(response, decisions); + }); + }; + /** + * Finally, for each retryable host perform request until we got a non + * retryable response. Some notes here: + * + * 1. The reverse here is applied so we can apply a `pop` later on => more performant. + * 2. We also get from the retryable options a timeout multiplier that is tailored + * for the current context. + */ + return createRetryableOptions(transporter.hostsCache, statelessHosts).then(options => { + return retry([...options.statelessHosts].reverse(), options.getTimeout); + }); +} + +function createTransporter(options) { + const { hostsCache, logger, requester, requestsCache, responsesCache, timeouts, userAgent, hosts, queryParameters, headers, } = options; + const transporter = { + hostsCache, + logger, + requester, + requestsCache, + responsesCache, + timeouts, + userAgent, + headers, + queryParameters, + hosts: hosts.map(host => createStatelessHost(host)), + read(request, requestOptions) { + /** + * First, we compute the user request options. Now, keep in mind, + * that using request options the user is able to modified the intire + * payload of the request. Such as headers, query parameters, and others. + */ + const mappedRequestOptions = createMappedRequestOptions(requestOptions, transporter.timeouts.read); + const createRetryableRequest = () => { + /** + * Then, we prepare a function factory that contains the construction of + * the retryable request. At this point, we may *not* perform the actual + * request. But we want to have the function factory ready. + */ + return retryableRequest(transporter, transporter.hosts.filter(host => (host.accept & CallEnum.Read) !== 0), request, mappedRequestOptions); + }; + /** + * Once we have the function factory ready, we need to determine of the + * request is "cacheable" - should be cached. Note that, once again, + * the user can force this option. + */ + const cacheable = mappedRequestOptions.cacheable !== undefined + ? mappedRequestOptions.cacheable + : request.cacheable; + /** + * If is not "cacheable", we immediatly trigger the retryable request, no + * need to check cache implementations. + */ + if (cacheable !== true) { + return createRetryableRequest(); + } + /** + * If the request is "cacheable", we need to first compute the key to ask + * the cache implementations if this request is on progress or if the + * response already exists on the cache. + */ + const key = { + request, + mappedRequestOptions, + transporter: { + queryParameters: transporter.queryParameters, + headers: transporter.headers, + }, + }; + /** + * With the computed key, we first ask the responses cache + * implemention if this request was been resolved before. + */ + return transporter.responsesCache.get(key, () => { + /** + * If the request has never resolved before, we actually ask if there + * is a current request with the same key on progress. + */ + return transporter.requestsCache.get(key, () => { + return (transporter.requestsCache + /** + * Finally, if there is no request in progress with the same key, + * this `createRetryableRequest()` will actually trigger the + * retryable request. + */ + .set(key, createRetryableRequest()) + .then(response => Promise.all([transporter.requestsCache.delete(key), response]), err => Promise.all([transporter.requestsCache.delete(key), Promise.reject(err)])) + .then(([_, response]) => response)); + }); + }, { + /** + * Of course, once we get this response back from the server, we + * tell response cache to actually store the received response + * to be used later. + */ + miss: response => transporter.responsesCache.set(key, response), + }); + }, + write(request, requestOptions) { + /** + * On write requests, no cache mechanisms are applied, and we + * proxy the request immediately to the requester. + */ + return retryableRequest(transporter, transporter.hosts.filter(host => (host.accept & CallEnum.Write) !== 0), request, createMappedRequestOptions(requestOptions, transporter.timeouts.write)); + }, + }; + return transporter; +} + +function createUserAgent(version) { + const userAgent = { + value: `Algolia for JavaScript (${version})`, + add(options) { + const addedUserAgent = `; ${options.segment}${options.version !== undefined ? ` (${options.version})` : ''}`; + if (userAgent.value.indexOf(addedUserAgent) === -1) { + // eslint-disable-next-line functional/immutable-data + userAgent.value = `${userAgent.value}${addedUserAgent}`; + } + return userAgent; + }, + }; + return userAgent; +} + +function deserializeSuccess(response) { + // eslint-disable-next-line functional/no-try-statement + try { + return JSON.parse(response.content); + } + catch (e) { + throw createDeserializationError(e.message, response); + } +} +function deserializeFailure({ content, status }, stackFrame) { + // eslint-disable-next-line functional/no-let + let message = content; + // eslint-disable-next-line functional/no-try-statement + try { + message = JSON.parse(content).message; + } + catch (e) { + // .. + } + return createApiError(message, status, stackFrame); +} + +function serializeUrl(host, path, queryParameters) { + const queryParametersAsString = serializeQueryParameters(queryParameters); + // eslint-disable-next-line functional/no-let + let url = `${host.protocol}://${host.url}/${path.charAt(0) === '/' ? path.substr(1) : path}`; + if (queryParametersAsString.length) { + url += `?${queryParametersAsString}`; + } + return url; +} +function serializeQueryParameters(parameters) { + const isObjectOrArray = (value) => Object.prototype.toString.call(value) === '[object Object]' || + Object.prototype.toString.call(value) === '[object Array]'; + return Object.keys(parameters) + .map(key => encode('%s=%s', key, isObjectOrArray(parameters[key]) ? JSON.stringify(parameters[key]) : parameters[key])) + .join('&'); +} +function serializeData(request, requestOptions) { + if (request.method === MethodEnum.Get || + (request.data === undefined && requestOptions.data === undefined)) { + return undefined; + } + const data = Array.isArray(request.data) + ? request.data + : { ...request.data, ...requestOptions.data }; + return JSON.stringify(data); +} +function serializeHeaders(transporter, requestOptions) { + const headers = { + ...transporter.headers, + ...requestOptions.headers, + }; + const serializedHeaders = {}; + Object.keys(headers).forEach(header => { + const value = headers[header]; + // @ts-ignore + // eslint-disable-next-line functional/immutable-data + serializedHeaders[header.toLowerCase()] = value; + }); + return serializedHeaders; +} + +function stackTraceWithoutCredentials(stackTrace) { + return stackTrace.map(stackFrame => stackFrameWithoutCredentials(stackFrame)); +} +function stackFrameWithoutCredentials(stackFrame) { + const modifiedHeaders = stackFrame.request.headers['x-algolia-api-key'] + ? { 'x-algolia-api-key': '*****' } + : {}; + return { + ...stackFrame, + request: { + ...stackFrame.request, + headers: { + ...stackFrame.request.headers, + ...modifiedHeaders, + }, + }, + }; +} + +function createApiError(message, status, transporterStackTrace) { + return { + name: 'ApiError', + message, + status, + transporterStackTrace, + }; +} + +function createDeserializationError(message, response) { + return { + name: 'DeserializationError', + message, + response, + }; +} + +function createRetryError(transporterStackTrace) { + return { + name: 'RetryError', + message: 'Unreachable hosts - your application id may be incorrect. If the error persists, please reach out to the Algolia Support team: https://alg.li/support .', + transporterStackTrace, + }; +} + +const createAnalyticsClient = options => { + const region = options.region || 'us'; + const auth = createAuth(AuthMode.WithinHeaders, options.appId, options.apiKey); + const transporter = createTransporter({ + hosts: [{ url: `analytics.${region}.algolia.com` }], + ...options, + headers: { + ...auth.headers(), + ...{ 'content-type': 'application/json' }, + ...options.headers, + }, + queryParameters: { + ...auth.queryParameters(), + ...options.queryParameters, + }, + }); + const appId = options.appId; + return addMethods({ appId, transporter }, options.methods); +}; + +const addABTest = (base) => { + return (abTest, requestOptions) => { + return base.transporter.write({ + method: MethodEnum.Post, + path: '2/abtests', + data: abTest, + }, requestOptions); + }; +}; + +const deleteABTest = (base) => { + return (abTestID, requestOptions) => { + return base.transporter.write({ + method: MethodEnum.Delete, + path: encode('2/abtests/%s', abTestID), + }, requestOptions); + }; +}; + +const getABTest = (base) => { + return (abTestID, requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Get, + path: encode('2/abtests/%s', abTestID), + }, requestOptions); + }; +}; + +const getABTests = (base) => { + return (requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Get, + path: '2/abtests', + }, requestOptions); + }; +}; + +const stopABTest = (base) => { + return (abTestID, requestOptions) => { + return base.transporter.write({ + method: MethodEnum.Post, + path: encode('2/abtests/%s/stop', abTestID), + }, requestOptions); + }; +}; + +const createPersonalizationClient = options => { + const region = options.region || 'us'; + const auth = createAuth(AuthMode.WithinHeaders, options.appId, options.apiKey); + const transporter = createTransporter({ + hosts: [{ url: `personalization.${region}.algolia.com` }], + ...options, + headers: { + ...auth.headers(), + ...{ 'content-type': 'application/json' }, + ...options.headers, + }, + queryParameters: { + ...auth.queryParameters(), + ...options.queryParameters, + }, + }); + return addMethods({ appId: options.appId, transporter }, options.methods); +}; + +const getPersonalizationStrategy = (base) => { + return (requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Get, + path: '1/strategies/personalization', + }, requestOptions); + }; +}; + +const setPersonalizationStrategy = (base) => { + return (personalizationStrategy, requestOptions) => { + return base.transporter.write({ + method: MethodEnum.Post, + path: '1/strategies/personalization', + data: personalizationStrategy, + }, requestOptions); + }; +}; + +function createBrowsablePromise(options) { + const browse = (data) => { + return options.request(data).then(response => { + /** + * First we send to the developer the + * batch retrieved from the API. + */ + if (options.batch !== undefined) { + options.batch(response.hits); + } + /** + * Then, we ask to the browse concrete implementation + * if we should stop browsing. As example, the `browseObjects` + * method will stop if the cursor is not present on the response. + */ + if (options.shouldStop(response)) { + return undefined; + } + /** + * Finally, if the response contains a cursor, we browse to the next + * batch using that same cursor. Otherwise, we just use the traditional + * browsing using the page element. + */ + if (response.cursor) { + return browse({ + cursor: response.cursor, + }); + } + return browse({ + page: (data.page || 0) + 1, + }); + }); + }; + return browse({}); +} + +const createSearchClient = options => { + const appId = options.appId; + const auth = createAuth(options.authMode !== undefined ? options.authMode : AuthMode.WithinHeaders, appId, options.apiKey); + const transporter = createTransporter({ + hosts: [ + { url: `${appId}-dsn.algolia.net`, accept: CallEnum.Read }, + { url: `${appId}.algolia.net`, accept: CallEnum.Write }, + ].concat(shuffle([ + { url: `${appId}-1.algolianet.com` }, + { url: `${appId}-2.algolianet.com` }, + { url: `${appId}-3.algolianet.com` }, + ])), + ...options, + headers: { + ...auth.headers(), + ...{ 'content-type': 'application/x-www-form-urlencoded' }, + ...options.headers, + }, + queryParameters: { + ...auth.queryParameters(), + ...options.queryParameters, + }, + }); + const base = { + transporter, + appId, + addAlgoliaAgent(segment, version) { + transporter.userAgent.add({ segment, version }); + }, + clearCache() { + return Promise.all([ + transporter.requestsCache.clear(), + transporter.responsesCache.clear(), + ]).then(() => undefined); + }, + }; + return addMethods(base, options.methods); +}; + +function createMissingObjectIDError() { + return { + name: 'MissingObjectIDError', + message: 'All objects must have an unique objectID ' + + '(like a primary key) to be valid. ' + + 'Algolia is also able to generate objectIDs ' + + "automatically but *it's not recommended*. " + + "To do it, use the `{'autoGenerateObjectIDIfNotExist': true}` option.", + }; +} + +function createObjectNotFoundError() { + return { + name: 'ObjectNotFoundError', + message: 'Object not found.', + }; +} + +const addApiKey = (base) => { + return (acl, requestOptions) => { + const { queryParameters, ...options } = requestOptions || {}; + const data = { + acl, + ...(queryParameters !== undefined ? { queryParameters } : {}), + }; + const wait = (response, waitRequestOptions) => { + return createRetryablePromise(retry => { + return getApiKey(base)(response.key, waitRequestOptions).catch((apiError) => { + if (apiError.status !== 404) { + throw apiError; + } + return retry(); + }); + }); + }; + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Post, + path: '1/keys', + data, + }, options), wait); + }; +}; + +const assignUserID = (base) => { + return (userID, clusterName, requestOptions) => { + const mappedRequestOptions = createMappedRequestOptions(requestOptions); + // eslint-disable-next-line functional/immutable-data + mappedRequestOptions.queryParameters['X-Algolia-User-ID'] = userID; + return base.transporter.write({ + method: MethodEnum.Post, + path: '1/clusters/mapping', + data: { cluster: clusterName }, + }, mappedRequestOptions); + }; +}; + +const assignUserIDs = (base) => { + return (userIDs, clusterName, requestOptions) => { + return base.transporter.write({ + method: MethodEnum.Post, + path: '1/clusters/mapping/batch', + data: { + users: userIDs, + cluster: clusterName, + }, + }, requestOptions); + }; +}; + +const clearDictionaryEntries = (base) => { + return (dictionary, requestOptions) => { + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Post, + path: encode('/1/dictionaries/%s/batch', dictionary), + data: { + clearExistingDictionaryEntries: true, + requests: { action: 'addEntry', body: [] }, + }, + }, requestOptions), (response, waitRequestOptions) => waitAppTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const copyIndex = (base) => { + return (from, to, requestOptions) => { + const wait = (response, waitRequestOptions) => { + return initIndex(base)(from, { + methods: { waitTask }, + }).waitTask(response.taskID, waitRequestOptions); + }; + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Post, + path: encode('1/indexes/%s/operation', from), + data: { + operation: 'copy', + destination: to, + }, + }, requestOptions), wait); + }; +}; + +const copyRules = (base) => { + return (from, to, requestOptions) => { + return copyIndex(base)(from, to, { + ...requestOptions, + scope: [ScopeEnum.Rules], + }); + }; +}; + +const copySettings = (base) => { + return (from, to, requestOptions) => { + return copyIndex(base)(from, to, { + ...requestOptions, + scope: [ScopeEnum.Settings], + }); + }; +}; + +const copySynonyms = (base) => { + return (from, to, requestOptions) => { + return copyIndex(base)(from, to, { + ...requestOptions, + scope: [ScopeEnum.Synonyms], + }); + }; +}; + +const customRequest = (base) => { + return (request, requestOptions) => { + if (request.method === MethodEnum.Get) { + return base.transporter.read(request, requestOptions); + } + return base.transporter.write(request, requestOptions); + }; +}; + +const deleteApiKey = (base) => { + return (apiKey, requestOptions) => { + const wait = (_, waitRequestOptions) => { + return createRetryablePromise(retry => { + return getApiKey(base)(apiKey, waitRequestOptions) + .then(retry) + .catch((apiError) => { + if (apiError.status !== 404) { + throw apiError; + } + }); + }); + }; + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Delete, + path: encode('1/keys/%s', apiKey), + }, requestOptions), wait); + }; +}; + +const deleteDictionaryEntries = (base) => { + return (dictionary, objectIDs, requestOptions) => { + const requests = objectIDs.map(objectID => ({ + action: 'deleteEntry', + body: { objectID }, + })); + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Post, + path: encode('/1/dictionaries/%s/batch', dictionary), + data: { clearExistingDictionaryEntries: false, requests }, + }, requestOptions), (response, waitRequestOptions) => waitAppTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const getApiKey = (base) => { + return (apiKey, requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Get, + path: encode('1/keys/%s', apiKey), + }, requestOptions); + }; +}; + +const getAppTask = (base) => { + return (taskID, requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Get, + path: encode('1/task/%s', taskID.toString()), + }, requestOptions); + }; +}; + +const getDictionarySettings = (base) => { + return (requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Get, + path: '/1/dictionaries/*/settings', + }, requestOptions); + }; +}; + +const getLogs = (base) => { + return (requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Get, + path: '1/logs', + }, requestOptions); + }; +}; + +const getTopUserIDs = (base) => { + return (requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Get, + path: '1/clusters/mapping/top', + }, requestOptions); + }; +}; + +const getUserID = (base) => { + return (userID, requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Get, + path: encode('1/clusters/mapping/%s', userID), + }, requestOptions); + }; +}; + +const hasPendingMappings = (base) => { + return (requestOptions) => { + const { retrieveMappings, ...options } = requestOptions || {}; + if (retrieveMappings === true) { + // eslint-disable-next-line functional/immutable-data + options.getClusters = true; + } + return base.transporter.read({ + method: MethodEnum.Get, + path: '1/clusters/mapping/pending', + }, options); + }; +}; + +const initIndex = (base) => { + return (indexName, options = {}) => { + const searchIndex = { + transporter: base.transporter, + appId: base.appId, + indexName, + }; + return addMethods(searchIndex, options.methods); + }; +}; + +const listApiKeys = (base) => { + return (requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Get, + path: '1/keys', + }, requestOptions); + }; +}; + +const listClusters = (base) => { + return (requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Get, + path: '1/clusters', + }, requestOptions); + }; +}; + +const listIndices = (base) => { + return (requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Get, + path: '1/indexes', + }, requestOptions); + }; +}; + +const listUserIDs = (base) => { + return (requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Get, + path: '1/clusters/mapping', + }, requestOptions); + }; +}; + +const moveIndex = (base) => { + return (from, to, requestOptions) => { + const wait = (response, waitRequestOptions) => { + return initIndex(base)(from, { + methods: { waitTask }, + }).waitTask(response.taskID, waitRequestOptions); + }; + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Post, + path: encode('1/indexes/%s/operation', from), + data: { + operation: 'move', + destination: to, + }, + }, requestOptions), wait); + }; +}; + +const multipleBatch = (base) => { + return (requests, requestOptions) => { + const wait = (response, waitRequestOptions) => { + return Promise.all(Object.keys(response.taskID).map(indexName => { + return initIndex(base)(indexName, { + methods: { waitTask }, + }).waitTask(response.taskID[indexName], waitRequestOptions); + })); + }; + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Post, + path: '1/indexes/*/batch', + data: { + requests, + }, + }, requestOptions), wait); + }; +}; + +const multipleGetObjects = (base) => { + return (requests, requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Post, + path: '1/indexes/*/objects', + data: { + requests, + }, + }, requestOptions); + }; +}; + +const multipleQueries = (base) => { + return (queries, requestOptions) => { + const requests = queries.map(query => { + return { + ...query, + params: serializeQueryParameters(query.params || {}), + }; + }); + return base.transporter.read({ + method: MethodEnum.Post, + path: '1/indexes/*/queries', + data: { + requests, + }, + cacheable: true, + }, requestOptions); + }; +}; + +const multipleSearchForFacetValues = (base) => { + return (queries, requestOptions) => { + return Promise.all(queries.map(query => { + const { facetName, facetQuery, ...params } = query.params; + return initIndex(base)(query.indexName, { + methods: { searchForFacetValues }, + }).searchForFacetValues(facetName, facetQuery, { + ...requestOptions, + ...params, + }); + })); + }; +}; + +const removeUserID = (base) => { + return (userID, requestOptions) => { + const mappedRequestOptions = createMappedRequestOptions(requestOptions); + // eslint-disable-next-line functional/immutable-data + mappedRequestOptions.queryParameters['X-Algolia-User-ID'] = userID; + return base.transporter.write({ + method: MethodEnum.Delete, + path: '1/clusters/mapping', + }, mappedRequestOptions); + }; +}; + +const replaceDictionaryEntries = (base) => { + return (dictionary, entries, requestOptions) => { + const requests = entries.map(entry => ({ + action: 'addEntry', + body: entry, + })); + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Post, + path: encode('/1/dictionaries/%s/batch', dictionary), + data: { clearExistingDictionaryEntries: true, requests }, + }, requestOptions), (response, waitRequestOptions) => waitAppTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const restoreApiKey = (base) => { + return (apiKey, requestOptions) => { + const wait = (_, waitRequestOptions) => { + return createRetryablePromise(retry => { + return getApiKey(base)(apiKey, waitRequestOptions).catch((apiError) => { + if (apiError.status !== 404) { + throw apiError; + } + return retry(); + }); + }); + }; + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Post, + path: encode('1/keys/%s/restore', apiKey), + }, requestOptions), wait); + }; +}; + +const saveDictionaryEntries = (base) => { + return (dictionary, entries, requestOptions) => { + const requests = entries.map(entry => ({ + action: 'addEntry', + body: entry, + })); + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Post, + path: encode('/1/dictionaries/%s/batch', dictionary), + data: { clearExistingDictionaryEntries: false, requests }, + }, requestOptions), (response, waitRequestOptions) => waitAppTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const searchDictionaryEntries = (base) => { + return (dictionary, query, requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Post, + path: encode('/1/dictionaries/%s/search', dictionary), + data: { + query, + }, + cacheable: true, + }, requestOptions); + }; +}; + +const searchUserIDs = (base) => { + return (query, requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Post, + path: '1/clusters/mapping/search', + data: { + query, + }, + }, requestOptions); + }; +}; + +const setDictionarySettings = (base) => { + return (settings, requestOptions) => { + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Put, + path: '/1/dictionaries/*/settings', + data: settings, + }, requestOptions), (response, waitRequestOptions) => waitAppTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const updateApiKey = (base) => { + return (apiKey, requestOptions) => { + const updatedFields = Object.assign({}, requestOptions); + const { queryParameters, ...options } = requestOptions || {}; + const data = queryParameters ? { queryParameters } : {}; + const apiKeyFields = [ + 'acl', + 'indexes', + 'referers', + 'restrictSources', + 'queryParameters', + 'description', + 'maxQueriesPerIPPerHour', + 'maxHitsPerQuery', + ]; + // Check that all the fields retrieved through getApiKey are the same as the ones we wanted to update + const hasChanged = (getApiKeyResponse) => { + return Object.keys(updatedFields) + .filter((updatedField) => apiKeyFields.indexOf(updatedField) !== -1) + .every(updatedField => { + // If the field is an array, we need to check that they are the same length and that all the values are the same + if (Array.isArray(getApiKeyResponse[updatedField]) && + Array.isArray(updatedFields[updatedField])) { + const getApiKeyResponseArray = getApiKeyResponse[updatedField]; + return (getApiKeyResponseArray.length === updatedFields[updatedField].length && + getApiKeyResponseArray.every((value, index) => value === updatedFields[updatedField][index])); + } + else { + return getApiKeyResponse[updatedField] === updatedFields[updatedField]; + } + }); + }; + const wait = (_, waitRequestOptions) => createRetryablePromise(retry => { + return getApiKey(base)(apiKey, waitRequestOptions).then(getApiKeyResponse => { + return hasChanged(getApiKeyResponse) ? Promise.resolve() : retry(); + }); + }); + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Put, + path: encode('1/keys/%s', apiKey), + data, + }, options), wait); + }; +}; + +const waitAppTask = (base) => { + return (taskID, requestOptions) => { + return createRetryablePromise(retry => { + return getAppTask(base)(taskID, requestOptions).then(response => { + return response.status !== 'published' ? retry() : undefined; + }); + }); + }; +}; + +const batch = (base) => { + return (requests, requestOptions) => { + const wait = (response, waitRequestOptions) => { + return waitTask(base)(response.taskID, waitRequestOptions); + }; + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Post, + path: encode('1/indexes/%s/batch', base.indexName), + data: { + requests, + }, + }, requestOptions), wait); + }; +}; + +const browseObjects = (base) => { + return (requestOptions) => { + return createBrowsablePromise({ + shouldStop: response => response.cursor === undefined, + ...requestOptions, + request: (data) => base.transporter.read({ + method: MethodEnum.Post, + path: encode('1/indexes/%s/browse', base.indexName), + data, + }, requestOptions), + }); + }; +}; + +const browseRules = (base) => { + return (requestOptions) => { + const options = { + hitsPerPage: 1000, + ...requestOptions, + }; + return createBrowsablePromise({ + shouldStop: response => response.hits.length < options.hitsPerPage, + ...options, + request(data) { + return searchRules(base)('', { ...options, ...data }).then((response) => { + return { + ...response, + hits: response.hits.map(rule => { + // eslint-disable-next-line functional/immutable-data,no-param-reassign + delete rule._highlightResult; + return rule; + }), + }; + }); + }, + }); + }; +}; + +const browseSynonyms = (base) => { + return (requestOptions) => { + const options = { + hitsPerPage: 1000, + ...requestOptions, + }; + return createBrowsablePromise({ + shouldStop: response => response.hits.length < options.hitsPerPage, + ...options, + request(data) { + return searchSynonyms(base)('', { ...options, ...data }).then((response) => { + return { + ...response, + hits: response.hits.map(synonym => { + // eslint-disable-next-line functional/immutable-data,no-param-reassign + delete synonym._highlightResult; + return synonym; + }), + }; + }); + }, + }); + }; +}; + +const chunkedBatch = (base) => { + return (bodies, action, requestOptions) => { + const { batchSize, ...options } = requestOptions || {}; + const response = { + taskIDs: [], + objectIDs: [], + }; + const forEachBatch = (lastIndex = 0) => { + // eslint-disable-next-line functional/prefer-readonly-type + const bodiesChunk = []; + // eslint-disable-next-line functional/no-let + let index; + /* eslint-disable-next-line functional/no-loop-statement */ + for (index = lastIndex; index < bodies.length; index++) { + // eslint-disable-next-line functional/immutable-data + bodiesChunk.push(bodies[index]); + if (bodiesChunk.length === (batchSize || 1000)) { + break; + } + } + if (bodiesChunk.length === 0) { + return Promise.resolve(response); + } + return batch(base)(bodiesChunk.map(body => { + return { + action, + body, + }; + }), options).then(res => { + response.objectIDs = response.objectIDs.concat(res.objectIDs); // eslint-disable-line functional/immutable-data + response.taskIDs.push(res.taskID); // eslint-disable-line functional/immutable-data + index++; + return forEachBatch(index); + }); + }; + return createWaitablePromise(forEachBatch(), (chunkedBatchResponse, waitRequestOptions) => { + return Promise.all(chunkedBatchResponse.taskIDs.map(taskID => { + return waitTask(base)(taskID, waitRequestOptions); + })); + }); + }; +}; + +const clearObjects = (base) => { + return (requestOptions) => { + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Post, + path: encode('1/indexes/%s/clear', base.indexName), + }, requestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const clearRules = (base) => { + return (requestOptions) => { + const { forwardToReplicas, ...options } = requestOptions || {}; + const mappedRequestOptions = createMappedRequestOptions(options); + if (forwardToReplicas) { + mappedRequestOptions.queryParameters.forwardToReplicas = 1; // eslint-disable-line functional/immutable-data + } + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Post, + path: encode('1/indexes/%s/rules/clear', base.indexName), + }, mappedRequestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const clearSynonyms = (base) => { + return (requestOptions) => { + const { forwardToReplicas, ...options } = requestOptions || {}; + const mappedRequestOptions = createMappedRequestOptions(options); + if (forwardToReplicas) { + mappedRequestOptions.queryParameters.forwardToReplicas = 1; // eslint-disable-line functional/immutable-data + } + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Post, + path: encode('1/indexes/%s/synonyms/clear', base.indexName), + }, mappedRequestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const deleteBy = (base) => { + return (filters, requestOptions) => { + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Post, + path: encode('1/indexes/%s/deleteByQuery', base.indexName), + data: filters, + }, requestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const deleteIndex = (base) => { + return (requestOptions) => { + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Delete, + path: encode('1/indexes/%s', base.indexName), + }, requestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const deleteObject = (base) => { + return (objectID, requestOptions) => { + return createWaitablePromise(deleteObjects(base)([objectID], requestOptions).then(response => { + return { taskID: response.taskIDs[0] }; + }), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const deleteObjects = (base) => { + return (objectIDs, requestOptions) => { + const objects = objectIDs.map(objectID => { + return { objectID }; + }); + return chunkedBatch(base)(objects, BatchActionEnum.DeleteObject, requestOptions); + }; +}; + +const deleteRule = (base) => { + return (objectID, requestOptions) => { + const { forwardToReplicas, ...options } = requestOptions || {}; + const mappedRequestOptions = createMappedRequestOptions(options); + if (forwardToReplicas) { + mappedRequestOptions.queryParameters.forwardToReplicas = 1; // eslint-disable-line functional/immutable-data + } + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Delete, + path: encode('1/indexes/%s/rules/%s', base.indexName, objectID), + }, mappedRequestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const deleteSynonym = (base) => { + return (objectID, requestOptions) => { + const { forwardToReplicas, ...options } = requestOptions || {}; + const mappedRequestOptions = createMappedRequestOptions(options); + if (forwardToReplicas) { + mappedRequestOptions.queryParameters.forwardToReplicas = 1; // eslint-disable-line functional/immutable-data + } + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Delete, + path: encode('1/indexes/%s/synonyms/%s', base.indexName, objectID), + }, mappedRequestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const exists = (base) => { + return (requestOptions) => { + return getSettings(base)(requestOptions) + .then(() => true) + .catch(error => { + if (error.status !== 404) { + throw error; + } + return false; + }); + }; +}; + +const findAnswers = (base) => { + return (query, queryLanguages, requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Post, + path: encode('1/answers/%s/prediction', base.indexName), + data: { + query, + queryLanguages, + }, + cacheable: true, + }, requestOptions); + }; +}; + +const findObject = (base) => { + return (callback, requestOptions) => { + const { query, paginate, ...options } = requestOptions || {}; + // eslint-disable-next-line functional/no-let + let page = 0; + const forEachPage = () => { + return search(base)(query || '', { ...options, page }).then(result => { + // eslint-disable-next-line functional/no-loop-statement + for (const [position, hit] of Object.entries(result.hits)) { + // eslint-disable-next-line promise/no-callback-in-promise + if (callback(hit)) { + return { + object: hit, + position: parseInt(position, 10), + page, + }; + } + } + page++; + // paginate if option was set and has next page + if (paginate === false || page >= result.nbPages) { + throw createObjectNotFoundError(); + } + return forEachPage(); + }); + }; + return forEachPage(); + }; +}; + +const getObject = (base) => { + return (objectID, requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Get, + path: encode('1/indexes/%s/%s', base.indexName, objectID), + }, requestOptions); + }; +}; + +const getObjectPosition = () => { + return (searchResponse, objectID) => { + // eslint-disable-next-line functional/no-loop-statement + for (const [position, hit] of Object.entries(searchResponse.hits)) { + if (hit.objectID === objectID) { + return parseInt(position, 10); + } + } + return -1; + }; +}; + +const getObjects = (base) => { + return (objectIDs, requestOptions) => { + const { attributesToRetrieve, ...options } = requestOptions || {}; + const requests = objectIDs.map(objectID => { + return { + indexName: base.indexName, + objectID, + ...(attributesToRetrieve ? { attributesToRetrieve } : {}), + }; + }); + return base.transporter.read({ + method: MethodEnum.Post, + path: '1/indexes/*/objects', + data: { + requests, + }, + }, options); + }; +}; + +const getRule = (base) => { + return (objectID, requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Get, + path: encode('1/indexes/%s/rules/%s', base.indexName, objectID), + }, requestOptions); + }; +}; + +const getSettings = (base) => { + return (requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Get, + path: encode('1/indexes/%s/settings', base.indexName), + data: { + getVersion: 2, + }, + }, requestOptions); + }; +}; + +const getSynonym = (base) => { + return (objectID, requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Get, + path: encode(`1/indexes/%s/synonyms/%s`, base.indexName, objectID), + }, requestOptions); + }; +}; + +const getTask = (base) => { + return (taskID, requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Get, + path: encode('1/indexes/%s/task/%s', base.indexName, taskID.toString()), + }, requestOptions); + }; +}; + +const partialUpdateObject = (base) => { + return (object, requestOptions) => { + return createWaitablePromise(partialUpdateObjects(base)([object], requestOptions).then(response => { + return { + objectID: response.objectIDs[0], + taskID: response.taskIDs[0], + }; + }), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const partialUpdateObjects = (base) => { + return (objects, requestOptions) => { + const { createIfNotExists, ...options } = requestOptions || {}; + const action = createIfNotExists + ? BatchActionEnum.PartialUpdateObject + : BatchActionEnum.PartialUpdateObjectNoCreate; + return chunkedBatch(base)(objects, action, options); + }; +}; + +const replaceAllObjects = (base) => { + return (objects, requestOptions) => { + const { safe, autoGenerateObjectIDIfNotExist, batchSize, ...options } = requestOptions || {}; + const operation = (from, to, type, operationRequestOptions) => { + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Post, + path: encode('1/indexes/%s/operation', from), + data: { + operation: type, + destination: to, + }, + }, operationRequestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; + const randomSuffix = Math.random() + .toString(36) + .substring(7); + const temporaryIndexName = `${base.indexName}_tmp_${randomSuffix}`; + const saveObjectsInTemporary = saveObjects({ + appId: base.appId, + transporter: base.transporter, + indexName: temporaryIndexName, + }); + // @ts-ignore + // eslint-disable-next-line prefer-const, functional/no-let, functional/prefer-readonly-type + let responses = []; + const copyWaitablePromise = operation(base.indexName, temporaryIndexName, 'copy', { + ...options, + scope: ['settings', 'synonyms', 'rules'], + }); + // eslint-disable-next-line functional/immutable-data + responses.push(copyWaitablePromise); + const result = (safe + ? copyWaitablePromise.wait(options) + : copyWaitablePromise) + .then(() => { + const saveObjectsWaitablePromise = saveObjectsInTemporary(objects, { + ...options, + autoGenerateObjectIDIfNotExist, + batchSize, + }); + // eslint-disable-next-line functional/immutable-data + responses.push(saveObjectsWaitablePromise); + return safe ? saveObjectsWaitablePromise.wait(options) : saveObjectsWaitablePromise; + }) + .then(() => { + const moveWaitablePromise = operation(temporaryIndexName, base.indexName, 'move', options); + // eslint-disable-next-line functional/immutable-data + responses.push(moveWaitablePromise); + return safe ? moveWaitablePromise.wait(options) : moveWaitablePromise; + }) + .then(() => Promise.all(responses)) + .then(([copyResponse, saveObjectsResponse, moveResponse]) => { + return { + objectIDs: saveObjectsResponse.objectIDs, + taskIDs: [copyResponse.taskID, ...saveObjectsResponse.taskIDs, moveResponse.taskID], + }; + }); + return createWaitablePromise(result, (_, waitRequestOptions) => { + return Promise.all(responses.map(response => response.wait(waitRequestOptions))); + }); + }; +}; + +const replaceAllRules = (base) => { + return (rules, requestOptions) => { + return saveRules(base)(rules, { + ...requestOptions, + clearExistingRules: true, + }); + }; +}; + +const replaceAllSynonyms = (base) => { + return (synonyms, requestOptions) => { + return saveSynonyms(base)(synonyms, { + ...requestOptions, + clearExistingSynonyms: true, + }); + }; +}; + +const saveObject = (base) => { + return (object, requestOptions) => { + return createWaitablePromise(saveObjects(base)([object], requestOptions).then(response => { + return { + objectID: response.objectIDs[0], + taskID: response.taskIDs[0], + }; + }), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const saveObjects = (base) => { + return (objects, requestOptions) => { + const { autoGenerateObjectIDIfNotExist, ...options } = requestOptions || {}; + const action = autoGenerateObjectIDIfNotExist + ? BatchActionEnum.AddObject + : BatchActionEnum.UpdateObject; + if (action === BatchActionEnum.UpdateObject) { + // eslint-disable-next-line functional/no-loop-statement + for (const object of objects) { + if (object.objectID === undefined) { + return createWaitablePromise(Promise.reject(createMissingObjectIDError())); + } + } + } + return chunkedBatch(base)(objects, action, options); + }; +}; + +const saveRule = (base) => { + return (rule, requestOptions) => { + return saveRules(base)([rule], requestOptions); + }; +}; + +const saveRules = (base) => { + return (rules, requestOptions) => { + const { forwardToReplicas, clearExistingRules, ...options } = requestOptions || {}; + const mappedRequestOptions = createMappedRequestOptions(options); + if (forwardToReplicas) { + mappedRequestOptions.queryParameters.forwardToReplicas = 1; // eslint-disable-line functional/immutable-data + } + if (clearExistingRules) { + mappedRequestOptions.queryParameters.clearExistingRules = 1; // eslint-disable-line functional/immutable-data + } + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Post, + path: encode('1/indexes/%s/rules/batch', base.indexName), + data: rules, + }, mappedRequestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const saveSynonym = (base) => { + return (synonym, requestOptions) => { + return saveSynonyms(base)([synonym], requestOptions); + }; +}; + +const saveSynonyms = (base) => { + return (synonyms, requestOptions) => { + const { forwardToReplicas, clearExistingSynonyms, replaceExistingSynonyms, ...options } = requestOptions || {}; + const mappedRequestOptions = createMappedRequestOptions(options); + if (forwardToReplicas) { + mappedRequestOptions.queryParameters.forwardToReplicas = 1; // eslint-disable-line functional/immutable-data + } + if (replaceExistingSynonyms || clearExistingSynonyms) { + mappedRequestOptions.queryParameters.replaceExistingSynonyms = 1; // eslint-disable-line functional/immutable-data + } + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Post, + path: encode('1/indexes/%s/synonyms/batch', base.indexName), + data: synonyms, + }, mappedRequestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const search = (base) => { + return (query, requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Post, + path: encode('1/indexes/%s/query', base.indexName), + data: { + query, + }, + cacheable: true, + }, requestOptions); + }; +}; + +const searchForFacetValues = (base) => { + return (facetName, facetQuery, requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Post, + path: encode('1/indexes/%s/facets/%s/query', base.indexName, facetName), + data: { + facetQuery, + }, + cacheable: true, + }, requestOptions); + }; +}; + +const searchRules = (base) => { + return (query, requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Post, + path: encode('1/indexes/%s/rules/search', base.indexName), + data: { + query, + }, + }, requestOptions); + }; +}; + +const searchSynonyms = (base) => { + return (query, requestOptions) => { + return base.transporter.read({ + method: MethodEnum.Post, + path: encode('1/indexes/%s/synonyms/search', base.indexName), + data: { + query, + }, + }, requestOptions); + }; +}; + +const setSettings = (base) => { + return (settings, requestOptions) => { + const { forwardToReplicas, ...options } = requestOptions || {}; + const mappedRequestOptions = createMappedRequestOptions(options); + if (forwardToReplicas) { + mappedRequestOptions.queryParameters.forwardToReplicas = 1; // eslint-disable-line functional/immutable-data + } + return createWaitablePromise(base.transporter.write({ + method: MethodEnum.Put, + path: encode('1/indexes/%s/settings', base.indexName), + data: settings, + }, mappedRequestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); + }; +}; + +const waitTask = (base) => { + return (taskID, requestOptions) => { + return createRetryablePromise(retry => { + return getTask(base)(taskID, requestOptions).then(response => { + return response.status !== 'published' ? retry() : undefined; + }); + }); + }; +}; + +const BatchActionEnum = { + AddObject: 'addObject', + UpdateObject: 'updateObject', + PartialUpdateObject: 'partialUpdateObject', + PartialUpdateObjectNoCreate: 'partialUpdateObjectNoCreate', + DeleteObject: 'deleteObject', + DeleteIndex: 'delete', + ClearIndex: 'clear', +}; + +const ScopeEnum = { + Settings: 'settings', + Synonyms: 'synonyms', + Rules: 'rules', +}; + +const LogLevelEnum = { + Debug: 1, + Info: 2, + Error: 3, +}; + +/* eslint no-console: 0 */ +function createConsoleLogger(logLevel) { + return { + debug(message, args) { + if (LogLevelEnum.Debug >= logLevel) { + console.debug(message, args); + } + return Promise.resolve(); + }, + info(message, args) { + if (LogLevelEnum.Info >= logLevel) { + console.info(message, args); + } + return Promise.resolve(); + }, + error(message, args) { + console.error(message, args); + return Promise.resolve(); + }, + }; +} + +const getRecommendations = base => { + return (queries, requestOptions) => { + const requests = queries.map(query => ({ + ...query, + // The `threshold` param is required by the endpoint to make it easier + // to provide a default value later, so we default it in the client + // so that users don't have to provide a value. + threshold: query.threshold || 0, + })); + return base.transporter.read({ + method: MethodEnum.Post, + path: '1/indexes/*/recommendations', + data: { + requests, + }, + cacheable: true, + }, requestOptions); + }; +}; + +const getFrequentlyBoughtTogether = base => { + return (queries, requestOptions) => { + return getRecommendations(base)(queries.map(query => ({ + ...query, + fallbackParameters: {}, + model: 'bought-together', + })), requestOptions); + }; +}; + +const getRelatedProducts = base => { + return (queries, requestOptions) => { + return getRecommendations(base)(queries.map(query => ({ + ...query, + model: 'related-products', + })), requestOptions); + }; +}; + +const getTrendingFacets = base => { + return (queries, requestOptions) => { + const requests = queries.map(query => ({ + ...query, + model: 'trending-facets', + // The `threshold` param is required by the endpoint to make it easier + // to provide a default value later, so we default it in the client + // so that users don't have to provide a value. + threshold: query.threshold || 0, + })); + return base.transporter.read({ + method: MethodEnum.Post, + path: '1/indexes/*/recommendations', + data: { + requests, + }, + cacheable: true, + }, requestOptions); + }; +}; + +const getTrendingItems = base => { + return (queries, requestOptions) => { + const requests = queries.map(query => ({ + ...query, + model: 'trending-items', + // The `threshold` param is required by the endpoint to make it easier + // to provide a default value later, so we default it in the client + // so that users don't have to provide a value. + threshold: query.threshold || 0, + })); + return base.transporter.read({ + method: MethodEnum.Post, + path: '1/indexes/*/recommendations', + data: { + requests, + }, + cacheable: true, + }, requestOptions); + }; +}; + +const getLookingSimilar = base => { + return (queries, requestOptions) => { + return getRecommendations(base)(queries.map(query => ({ + ...query, + model: 'looking-similar', + })), requestOptions); + }; +}; + +const getRecommendedForYou = base => { + return (queries, requestOptions) => { + const requests = queries.map(query => ({ + ...query, + model: 'recommended-for-you', + threshold: query.threshold || 0, + })); + return base.transporter.read({ + method: MethodEnum.Post, + path: '1/indexes/*/recommendations', + data: { + requests, + }, + cacheable: true, + }, requestOptions); + }; +}; + +function createBrowserXhrRequester() { + return { + send(request) { + return new Promise((resolve) => { + const baseRequester = new XMLHttpRequest(); + baseRequester.open(request.method, request.url, true); + Object.keys(request.headers).forEach(key => baseRequester.setRequestHeader(key, request.headers[key])); + const createTimeout = (timeout, content) => { + return setTimeout(() => { + baseRequester.abort(); + resolve({ + status: 0, + content, + isTimedOut: true, + }); + }, timeout * 1000); + }; + const connectTimeout = createTimeout(request.connectTimeout, 'Connection timeout'); + // eslint-disable-next-line functional/no-let + let responseTimeout; + // eslint-disable-next-line functional/immutable-data + baseRequester.onreadystatechange = () => { + if (baseRequester.readyState > baseRequester.OPENED && responseTimeout === undefined) { + clearTimeout(connectTimeout); + responseTimeout = createTimeout(request.responseTimeout, 'Socket timeout'); + } + }; + // eslint-disable-next-line functional/immutable-data + baseRequester.onerror = () => { + // istanbul ignore next + if (baseRequester.status === 0) { + clearTimeout(connectTimeout); + clearTimeout(responseTimeout); + resolve({ + content: baseRequester.responseText || 'Network request failed', + status: baseRequester.status, + isTimedOut: false, + }); + } + }; + // eslint-disable-next-line functional/immutable-data + baseRequester.onload = () => { + clearTimeout(connectTimeout); + clearTimeout(responseTimeout); + resolve({ + content: baseRequester.responseText, + status: baseRequester.status, + isTimedOut: false, + }); + }; + baseRequester.send(request.data); + }); + }, + }; +} + +function algoliasearch(appId, apiKey, options) { + const commonOptions = { + appId, + apiKey, + timeouts: { + connect: 1, + read: 2, + write: 30, + }, + requester: createBrowserXhrRequester(), + logger: createConsoleLogger(LogLevelEnum.Error), + responsesCache: createInMemoryCache(), + requestsCache: createInMemoryCache({ serializable: false }), + hostsCache: createFallbackableCache({ + caches: [ + createBrowserLocalStorageCache({ key: `${version}-${appId}` }), + createInMemoryCache(), + ], + }), + userAgent: createUserAgent(version).add({ segment: 'Browser' }), + }; + const searchClientOptions = { ...commonOptions, ...options }; + const initPersonalization = () => (clientOptions) => { + return createPersonalizationClient({ + ...commonOptions, + ...clientOptions, + methods: { + getPersonalizationStrategy, + setPersonalizationStrategy, + }, + }); + }; + return createSearchClient({ + ...searchClientOptions, + methods: { + search: multipleQueries, + searchForFacetValues: multipleSearchForFacetValues, + multipleBatch, + multipleGetObjects, + multipleQueries, + copyIndex, + copySettings, + copySynonyms, + copyRules, + moveIndex, + listIndices, + getLogs, + listClusters, + multipleSearchForFacetValues, + getApiKey, + addApiKey, + listApiKeys, + updateApiKey, + deleteApiKey, + restoreApiKey, + assignUserID, + assignUserIDs, + getUserID, + searchUserIDs, + listUserIDs, + getTopUserIDs, + removeUserID, + hasPendingMappings, + clearDictionaryEntries, + deleteDictionaryEntries, + getDictionarySettings, + getAppTask, + replaceDictionaryEntries, + saveDictionaryEntries, + searchDictionaryEntries, + setDictionarySettings, + waitAppTask, + customRequest, + initIndex: base => (indexName) => { + return initIndex(base)(indexName, { + methods: { + batch, + delete: deleteIndex, + findAnswers, + getObject, + getObjects, + saveObject, + saveObjects, + search, + searchForFacetValues, + waitTask, + setSettings, + getSettings, + partialUpdateObject, + partialUpdateObjects, + deleteObject, + deleteObjects, + deleteBy, + clearObjects, + browseObjects, + getObjectPosition, + findObject, + exists, + saveSynonym, + saveSynonyms, + getSynonym, + searchSynonyms, + browseSynonyms, + deleteSynonym, + clearSynonyms, + replaceAllObjects, + replaceAllSynonyms, + searchRules, + getRule, + deleteRule, + saveRule, + saveRules, + replaceAllRules, + browseRules, + clearRules, + }, + }); + }, + initAnalytics: () => (clientOptions) => { + return createAnalyticsClient({ + ...commonOptions, + ...clientOptions, + methods: { + addABTest, + getABTest, + getABTests, + stopABTest, + deleteABTest, + }, + }); + }, + initPersonalization, + initRecommendation: () => (clientOptions) => { + searchClientOptions.logger.info('The `initRecommendation` method is deprecated. Use `initPersonalization` instead.'); + return initPersonalization()(clientOptions); + }, + getRecommendations, + getFrequentlyBoughtTogether, + getLookingSimilar, + getRecommendedForYou, + getRelatedProducts, + getTrendingFacets, + getTrendingItems, + }, + }); +} +// eslint-disable-next-line functional/immutable-data +algoliasearch.version = version; + +export default algoliasearch; diff --git a/scripts/node_modules/algoliasearch/dist/algoliasearch.umd.js b/scripts/node_modules/algoliasearch/dist/algoliasearch.umd.js new file mode 100644 index 000000000..897e9e628 --- /dev/null +++ b/scripts/node_modules/algoliasearch/dist/algoliasearch.umd.js @@ -0,0 +1,2 @@ +/*! algoliasearch.umd.js | 4.24.0 | © Algolia, inc. | https://github.com/algolia/algoliasearch-client-javascript */ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).algoliasearch=e()}(this,(function(){"use strict";function t(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function e(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),r.push.apply(r,n)}return r}function r(r){for(var n=1;n=0||(a[r]=t[r]);return a}(t,e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);for(n=0;n=0||Object.prototype.propertyIsEnumerable.call(t,r)&&(a[r]=t[r])}return a}function a(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){if(!(Symbol.iterator in Object(t)||"[object Arguments]"===Object.prototype.toString.call(t)))return;var r=[],n=!0,a=!1,o=void 0;try{for(var i,u=t[Symbol.iterator]();!(n=(i=u.next()).done)&&(r.push(i.value),!e||r.length!==e);n=!0);}catch(t){a=!0,o=t}finally{try{n||null==u.return||u.return()}finally{if(a)throw o}}return r}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}function o(t){return function(t){if(Array.isArray(t)){for(var e=0,r=new Array(t.length);e2&&void 0!==arguments[2]?arguments[2]:{miss:function(){return Promise.resolve()}};return Promise.resolve().then((function(){u();var e=JSON.stringify(t);return o()[e]})).then((function(t){return Promise.all([t?t.value:e(),void 0!==t])})).then((function(t){var e=a(t,2),n=e[0],o=e[1];return Promise.all([n,o||r.miss(n)])})).then((function(t){return a(t,1)[0]}))},set:function(t,e){return Promise.resolve().then((function(){var a=o();return a[JSON.stringify(t)]={timestamp:(new Date).getTime(),value:e},n().setItem(r,JSON.stringify(a)),e}))},delete:function(t){return Promise.resolve().then((function(){var e=o();delete e[JSON.stringify(t)],n().setItem(r,JSON.stringify(e))}))},clear:function(){return Promise.resolve().then((function(){n().removeItem(r)}))}}}function u(t){var e=o(t.caches),r=e.shift();return void 0===r?{get:function(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{miss:function(){return Promise.resolve()}},n=e();return n.then((function(t){return Promise.all([t,r.miss(t)])})).then((function(t){return a(t,1)[0]}))},set:function(t,e){return Promise.resolve(e)},delete:function(t){return Promise.resolve()},clear:function(){return Promise.resolve()}}:{get:function(t,n){var a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{miss:function(){return Promise.resolve()}};return r.get(t,n,a).catch((function(){return u({caches:e}).get(t,n,a)}))},set:function(t,n){return r.set(t,n).catch((function(){return u({caches:e}).set(t,n)}))},delete:function(t){return r.delete(t).catch((function(){return u({caches:e}).delete(t)}))},clear:function(){return r.clear().catch((function(){return u({caches:e}).clear()}))}}}function s(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{serializable:!0},e={};return{get:function(r,n){var a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{miss:function(){return Promise.resolve()}},o=JSON.stringify(r);if(o in e)return Promise.resolve(t.serializable?JSON.parse(e[o]):e[o]);var i=n(),u=a&&a.miss||function(){return Promise.resolve()};return i.then((function(t){return u(t)})).then((function(){return i}))},set:function(r,n){return e[JSON.stringify(r)]=t.serializable?JSON.stringify(n):n,Promise.resolve(n)},delete:function(t){return delete e[JSON.stringify(t)],Promise.resolve()},clear:function(){return e={},Promise.resolve()}}}function c(t,e,r){var n={"x-algolia-api-key":r,"x-algolia-application-id":e};return{headers:function(){return t===m.WithinHeaders?n:{}},queryParameters:function(){return t===m.WithinQueryParameters?n:{}}}}function f(t){var e=0;return t((function r(){return e++,new Promise((function(n){setTimeout((function(){n(t(r))}),Math.min(100*e,1e3))}))}))}function d(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(t,e){return Promise.resolve()};return Object.assign(t,{wait:function(r){return d(t.then((function(t){return Promise.all([e(t,r),t])})).then((function(t){return t[1]})))}})}function l(t){for(var e=t.length-1;e>0;e--){var r=Math.floor(Math.random()*(e+1)),n=t[e];t[e]=t[r],t[r]=n}return t}function h(t,e){return e?(Object.keys(e).forEach((function(r){t[r]=e[r](t)})),t):t}function p(t){for(var e=arguments.length,r=new Array(e>1?e-1:0),n=1;n0?n:void 0,timeout:r.timeout||e,headers:r.headers||{},queryParameters:r.queryParameters||{},cacheable:r.cacheable}}var g={Read:1,Write:2,Any:3},v=1,b=2,P=3;function O(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:v;return r(r({},t),{},{status:e,lastUpdate:Date.now()})}function w(t){return"string"==typeof t?{protocol:"https",url:t,accept:g.Any}:{protocol:t.protocol||"https",url:t.url,accept:t.accept||g.Any}}var I="DELETE",x="GET",j="POST",D="PUT";function q(t,e){return Promise.all(e.map((function(e){return t.get(e,(function(){return Promise.resolve(O(e))}))}))).then((function(t){var r=t.filter((function(t){return function(t){return t.status===v||Date.now()-t.lastUpdate>12e4}(t)})),n=t.filter((function(t){return function(t){return t.status===P&&Date.now()-t.lastUpdate<=12e4}(t)})),a=[].concat(o(r),o(n));return{getTimeout:function(t,e){return(0===n.length&&0===t?1:n.length+3+t)*e},statelessHosts:a.length>0?a.map((function(t){return w(t)})):e}}))}function S(t,e,n,a){var i=[],u=function(t,e){if(t.method===x||void 0===t.data&&void 0===e.data)return;var n=Array.isArray(t.data)?t.data:r(r({},t.data),e.data);return JSON.stringify(n)}(n,a),s=function(t,e){var n=r(r({},t.headers),e.headers),a={};return Object.keys(n).forEach((function(t){var e=n[t];a[t.toLowerCase()]=e})),a}(t,a),c=n.method,f=n.method!==x?{}:r(r({},n.data),a.data),d=r(r(r({"x-algolia-agent":t.userAgent.value},t.queryParameters),f),a.queryParameters),l=0,h=function e(r,o){var f=r.pop();if(void 0===f)throw{name:"RetryError",message:"Unreachable hosts - your application id may be incorrect. If the error persists, please reach out to the Algolia Support team: https://alg.li/support .",transporterStackTrace:E(i)};var h={data:u,headers:s,method:c,url:N(f,n.path,d),connectTimeout:o(l,t.timeouts.connect),responseTimeout:o(l,a.timeout)},p=function(t){var e={request:h,response:t,host:f,triesLeft:r.length};return i.push(e),e},m={onSuccess:function(t){return function(t){try{return JSON.parse(t.content)}catch(e){throw function(t,e){return{name:"DeserializationError",message:t,response:e}}(e.message,t)}}(t)},onRetry:function(n){var a=p(n);return n.isTimedOut&&l++,Promise.all([t.logger.info("Retryable failure",A(a)),t.hostsCache.set(f,O(f,n.isTimedOut?P:b))]).then((function(){return e(r,o)}))},onFail:function(t){throw p(t),function(t,e){var r=t.content,n=t.status,a=r;try{a=JSON.parse(r).message}catch(t){}return function(t,e,r){return{name:"ApiError",message:t,status:e,transporterStackTrace:r}}(a,n,e)}(t,E(i))}};return t.requester.send(h).then((function(t){return function(t,e){return function(t){var e=t.status;return t.isTimedOut||function(t){var e=t.isTimedOut,r=t.status;return!e&&0==~~r}(t)||2!=~~(e/100)&&4!=~~(e/100)}(t)?e.onRetry(t):2==~~(t.status/100)?e.onSuccess(t):e.onFail(t)}(t,m)}))};return q(t.hostsCache,e).then((function(t){return h(o(t.statelessHosts).reverse(),t.getTimeout)}))}function k(t){var e=t.hostsCache,r=t.logger,n=t.requester,o=t.requestsCache,i=t.responsesCache,u=t.timeouts,s=t.userAgent,c=t.hosts,f=t.queryParameters,d={hostsCache:e,logger:r,requester:n,requestsCache:o,responsesCache:i,timeouts:u,userAgent:s,headers:t.headers,queryParameters:f,hosts:c.map((function(t){return w(t)})),read:function(t,e){var r=y(e,d.timeouts.read),n=function(){return S(d,d.hosts.filter((function(t){return 0!=(t.accept&g.Read)})),t,r)};if(!0!==(void 0!==r.cacheable?r.cacheable:t.cacheable))return n();var o={request:t,mappedRequestOptions:r,transporter:{queryParameters:d.queryParameters,headers:d.headers}};return d.responsesCache.get(o,(function(){return d.requestsCache.get(o,(function(){return d.requestsCache.set(o,n()).then((function(t){return Promise.all([d.requestsCache.delete(o),t])}),(function(t){return Promise.all([d.requestsCache.delete(o),Promise.reject(t)])})).then((function(t){var e=a(t,2);e[0];return e[1]}))}))}),{miss:function(t){return d.responsesCache.set(o,t)}})},write:function(t,e){return S(d,d.hosts.filter((function(t){return 0!=(t.accept&g.Write)})),t,y(e,d.timeouts.write))}};return d}function T(t){var e={value:"Algolia for JavaScript (".concat(t,")"),add:function(t){var r="; ".concat(t.segment).concat(void 0!==t.version?" (".concat(t.version,")"):"");return-1===e.value.indexOf(r)&&(e.value="".concat(e.value).concat(r)),e}};return e}function N(t,e,r){var n=R(r),a="".concat(t.protocol,"://").concat(t.url,"/").concat("/"===e.charAt(0)?e.substr(1):e);return n.length&&(a+="?".concat(n)),a}function R(t){return Object.keys(t).map((function(e){return p("%s=%s",e,(r=t[e],"[object Object]"===Object.prototype.toString.call(r)||"[object Array]"===Object.prototype.toString.call(r)?JSON.stringify(t[e]):t[e]));var r})).join("&")}function E(t){return t.map((function(t){return A(t)}))}function A(t){var e=t.request.headers["x-algolia-api-key"]?{"x-algolia-api-key":"*****"}:{};return r(r({},t),{},{request:r(r({},t.request),{},{headers:r(r({},t.request.headers),e)})})}var C=function(t){return function(e,r){return t.transporter.write({method:j,path:"2/abtests",data:e},r)}},U=function(t){return function(e,r){return t.transporter.write({method:I,path:p("2/abtests/%s",e)},r)}},z=function(t){return function(e,r){return t.transporter.read({method:x,path:p("2/abtests/%s",e)},r)}},J=function(t){return function(e){return t.transporter.read({method:x,path:"2/abtests"},e)}},F=function(t){return function(e,r){return t.transporter.write({method:j,path:p("2/abtests/%s/stop",e)},r)}},H=function(t){return function(e){return t.transporter.read({method:x,path:"1/strategies/personalization"},e)}},M=function(t){return function(e,r){return t.transporter.write({method:j,path:"1/strategies/personalization",data:e},r)}};function B(t){return function e(r){return t.request(r).then((function(n){if(void 0!==t.batch&&t.batch(n.hits),!t.shouldStop(n))return n.cursor?e({cursor:n.cursor}):e({page:(r.page||0)+1})}))}({})}var K=function(t){return function(e,a){var o=a||{},i=o.queryParameters,u=n(o,["queryParameters"]),s=r({acl:e},void 0!==i?{queryParameters:i}:{});return d(t.transporter.write({method:j,path:"1/keys",data:s},u),(function(e,r){return f((function(n){return tt(t)(e.key,r).catch((function(t){if(404!==t.status)throw t;return n()}))}))}))}},W=function(t){return function(e,r,n){var a=y(n);return a.queryParameters["X-Algolia-User-ID"]=e,t.transporter.write({method:j,path:"1/clusters/mapping",data:{cluster:r}},a)}},L=function(t){return function(e,r,n){return t.transporter.write({method:j,path:"1/clusters/mapping/batch",data:{users:e,cluster:r}},n)}},Q=function(t){return function(e,r){return d(t.transporter.write({method:j,path:p("/1/dictionaries/%s/batch",e),data:{clearExistingDictionaryEntries:!0,requests:{action:"addEntry",body:[]}}},r),(function(e,r){return jt(t)(e.taskID,r)}))}},G=function(t){return function(e,r,n){return d(t.transporter.write({method:j,path:p("1/indexes/%s/operation",e),data:{operation:"copy",destination:r}},n),(function(r,n){return ut(t)(e,{methods:{waitTask:de}}).waitTask(r.taskID,n)}))}},V=function(t){return function(e,n,a){return G(t)(e,n,r(r({},a),{},{scope:[he.Rules]}))}},_=function(t){return function(e,n,a){return G(t)(e,n,r(r({},a),{},{scope:[he.Settings]}))}},X=function(t){return function(e,n,a){return G(t)(e,n,r(r({},a),{},{scope:[he.Synonyms]}))}},Y=function(t){return function(e,r){return e.method===x?t.transporter.read(e,r):t.transporter.write(e,r)}},Z=function(t){return function(e,r){return d(t.transporter.write({method:I,path:p("1/keys/%s",e)},r),(function(r,n){return f((function(r){return tt(t)(e,n).then(r).catch((function(t){if(404!==t.status)throw t}))}))}))}},$=function(t){return function(e,r,n){var a=r.map((function(t){return{action:"deleteEntry",body:{objectID:t}}}));return d(t.transporter.write({method:j,path:p("/1/dictionaries/%s/batch",e),data:{clearExistingDictionaryEntries:!1,requests:a}},n),(function(e,r){return jt(t)(e.taskID,r)}))}},tt=function(t){return function(e,r){return t.transporter.read({method:x,path:p("1/keys/%s",e)},r)}},et=function(t){return function(e,r){return t.transporter.read({method:x,path:p("1/task/%s",e.toString())},r)}},rt=function(t){return function(e){return t.transporter.read({method:x,path:"/1/dictionaries/*/settings"},e)}},nt=function(t){return function(e){return t.transporter.read({method:x,path:"1/logs"},e)}},at=function(t){return function(e){return t.transporter.read({method:x,path:"1/clusters/mapping/top"},e)}},ot=function(t){return function(e,r){return t.transporter.read({method:x,path:p("1/clusters/mapping/%s",e)},r)}},it=function(t){return function(e){var r=e||{},a=r.retrieveMappings,o=n(r,["retrieveMappings"]);return!0===a&&(o.getClusters=!0),t.transporter.read({method:x,path:"1/clusters/mapping/pending"},o)}},ut=function(t){return function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n={transporter:t.transporter,appId:t.appId,indexName:e};return h(n,r.methods)}},st=function(t){return function(e){return t.transporter.read({method:x,path:"1/keys"},e)}},ct=function(t){return function(e){return t.transporter.read({method:x,path:"1/clusters"},e)}},ft=function(t){return function(e){return t.transporter.read({method:x,path:"1/indexes"},e)}},dt=function(t){return function(e){return t.transporter.read({method:x,path:"1/clusters/mapping"},e)}},lt=function(t){return function(e,r,n){return d(t.transporter.write({method:j,path:p("1/indexes/%s/operation",e),data:{operation:"move",destination:r}},n),(function(r,n){return ut(t)(e,{methods:{waitTask:de}}).waitTask(r.taskID,n)}))}},ht=function(t){return function(e,r){return d(t.transporter.write({method:j,path:"1/indexes/*/batch",data:{requests:e}},r),(function(e,r){return Promise.all(Object.keys(e.taskID).map((function(n){return ut(t)(n,{methods:{waitTask:de}}).waitTask(e.taskID[n],r)})))}))}},pt=function(t){return function(e,r){return t.transporter.read({method:j,path:"1/indexes/*/objects",data:{requests:e}},r)}},mt=function(t){return function(e,n){var a=e.map((function(t){return r(r({},t),{},{params:R(t.params||{})})}));return t.transporter.read({method:j,path:"1/indexes/*/queries",data:{requests:a},cacheable:!0},n)}},yt=function(t){return function(e,a){return Promise.all(e.map((function(e){var o=e.params,i=o.facetName,u=o.facetQuery,s=n(o,["facetName","facetQuery"]);return ut(t)(e.indexName,{methods:{searchForFacetValues:ue}}).searchForFacetValues(i,u,r(r({},a),s))})))}},gt=function(t){return function(e,r){var n=y(r);return n.queryParameters["X-Algolia-User-ID"]=e,t.transporter.write({method:I,path:"1/clusters/mapping"},n)}},vt=function(t){return function(e,r,n){var a=r.map((function(t){return{action:"addEntry",body:t}}));return d(t.transporter.write({method:j,path:p("/1/dictionaries/%s/batch",e),data:{clearExistingDictionaryEntries:!0,requests:a}},n),(function(e,r){return jt(t)(e.taskID,r)}))}},bt=function(t){return function(e,r){return d(t.transporter.write({method:j,path:p("1/keys/%s/restore",e)},r),(function(r,n){return f((function(r){return tt(t)(e,n).catch((function(t){if(404!==t.status)throw t;return r()}))}))}))}},Pt=function(t){return function(e,r,n){var a=r.map((function(t){return{action:"addEntry",body:t}}));return d(t.transporter.write({method:j,path:p("/1/dictionaries/%s/batch",e),data:{clearExistingDictionaryEntries:!1,requests:a}},n),(function(e,r){return jt(t)(e.taskID,r)}))}},Ot=function(t){return function(e,r,n){return t.transporter.read({method:j,path:p("/1/dictionaries/%s/search",e),data:{query:r},cacheable:!0},n)}},wt=function(t){return function(e,r){return t.transporter.read({method:j,path:"1/clusters/mapping/search",data:{query:e}},r)}},It=function(t){return function(e,r){return d(t.transporter.write({method:D,path:"/1/dictionaries/*/settings",data:e},r),(function(e,r){return jt(t)(e.taskID,r)}))}},xt=function(t){return function(e,r){var a=Object.assign({},r),o=r||{},i=o.queryParameters,u=n(o,["queryParameters"]),s=i?{queryParameters:i}:{},c=["acl","indexes","referers","restrictSources","queryParameters","description","maxQueriesPerIPPerHour","maxHitsPerQuery"];return d(t.transporter.write({method:D,path:p("1/keys/%s",e),data:s},u),(function(r,n){return f((function(r){return tt(t)(e,n).then((function(t){return function(t){return Object.keys(a).filter((function(t){return-1!==c.indexOf(t)})).every((function(e){if(Array.isArray(t[e])&&Array.isArray(a[e])){var r=t[e];return r.length===a[e].length&&r.every((function(t,r){return t===a[e][r]}))}return t[e]===a[e]}))}(t)?Promise.resolve():r()}))}))}))}},jt=function(t){return function(e,r){return f((function(n){return et(t)(e,r).then((function(t){return"published"!==t.status?n():void 0}))}))}},Dt=function(t){return function(e,r){return d(t.transporter.write({method:j,path:p("1/indexes/%s/batch",t.indexName),data:{requests:e}},r),(function(e,r){return de(t)(e.taskID,r)}))}},qt=function(t){return function(e){return B(r(r({shouldStop:function(t){return void 0===t.cursor}},e),{},{request:function(r){return t.transporter.read({method:j,path:p("1/indexes/%s/browse",t.indexName),data:r},e)}}))}},St=function(t){return function(e){var n=r({hitsPerPage:1e3},e);return B(r(r({shouldStop:function(t){return t.hits.length0&&void 0!==arguments[0]?arguments[0]:0,c=[];for(a=o;a=t.nbPages)throw{name:"ObjectNotFoundError",message:"Object not found."};return n()}))}()}},Kt=function(t){return function(e,r){return t.transporter.read({method:x,path:p("1/indexes/%s/%s",t.indexName,e)},r)}},Wt=function(){return function(t,e){for(var r=0,n=Object.entries(t.hits);rr.OPENED&&void 0===n&&(clearTimeout(o),n=a(t.responseTimeout,"Socket timeout"))},r.onerror=function(){0===r.status&&(clearTimeout(o),clearTimeout(n),e({content:r.responseText||"Network request failed",status:r.status,isTimedOut:!1}))},r.onload=function(){clearTimeout(o),clearTimeout(n),e({content:r.responseText,status:r.status,isTimedOut:!1})},r.send(t.data)}))}},logger:(a=ye,{debug:function(t,e){return pe>=a&&console.debug(t,e),Promise.resolve()},info:function(t,e){return me>=a&&console.info(t,e),Promise.resolve()},error:function(t,e){return console.error(t,e),Promise.resolve()}}),responsesCache:s(),requestsCache:s({serializable:!1}),hostsCache:u({caches:[i({key:"".concat("4.24.0","-").concat(t)}),s()]}),userAgent:T("4.24.0").add({segment:"Browser"})},f=r(r({},o),n),d=function(){return function(t){return function(t){var e=t.region||"us",n=c(m.WithinHeaders,t.appId,t.apiKey),a=k(r(r({hosts:[{url:"personalization.".concat(e,".algolia.com")}]},t),{},{headers:r(r(r({},n.headers()),{"content-type":"application/json"}),t.headers),queryParameters:r(r({},n.queryParameters()),t.queryParameters)}));return h({appId:t.appId,transporter:a},t.methods)}(r(r(r({},o),t),{},{methods:{getPersonalizationStrategy:H,setPersonalizationStrategy:M}}))}};return function(t){var e=t.appId,n=c(void 0!==t.authMode?t.authMode:m.WithinHeaders,e,t.apiKey),a=k(r(r({hosts:[{url:"".concat(e,"-dsn.algolia.net"),accept:g.Read},{url:"".concat(e,".algolia.net"),accept:g.Write}].concat(l([{url:"".concat(e,"-1.algolianet.com")},{url:"".concat(e,"-2.algolianet.com")},{url:"".concat(e,"-3.algolianet.com")}]))},t),{},{headers:r(r(r({},n.headers()),{"content-type":"application/x-www-form-urlencoded"}),t.headers),queryParameters:r(r({},n.queryParameters()),t.queryParameters)}));return h({transporter:a,appId:e,addAlgoliaAgent:function(t,e){a.userAgent.add({segment:t,version:e})},clearCache:function(){return Promise.all([a.requestsCache.clear(),a.responsesCache.clear()]).then((function(){}))}},t.methods)}(r(r({},f),{},{methods:{search:mt,searchForFacetValues:yt,multipleBatch:ht,multipleGetObjects:pt,multipleQueries:mt,copyIndex:G,copySettings:_,copySynonyms:X,copyRules:V,moveIndex:lt,listIndices:ft,getLogs:nt,listClusters:ct,multipleSearchForFacetValues:yt,getApiKey:tt,addApiKey:K,listApiKeys:st,updateApiKey:xt,deleteApiKey:Z,restoreApiKey:bt,assignUserID:W,assignUserIDs:L,getUserID:ot,searchUserIDs:wt,listUserIDs:dt,getTopUserIDs:at,removeUserID:gt,hasPendingMappings:it,clearDictionaryEntries:Q,deleteDictionaryEntries:$,getDictionarySettings:rt,getAppTask:et,replaceDictionaryEntries:vt,saveDictionaryEntries:Pt,searchDictionaryEntries:Ot,setDictionarySettings:It,waitAppTask:jt,customRequest:Y,initIndex:function(t){return function(e){return ut(t)(e,{methods:{batch:Dt,delete:Ct,findAnswers:Mt,getObject:Kt,getObjects:Lt,saveObject:te,saveObjects:ee,search:ie,searchForFacetValues:ue,waitTask:de,setSettings:fe,getSettings:Gt,partialUpdateObject:_t,partialUpdateObjects:Xt,deleteObject:Ut,deleteObjects:zt,deleteBy:At,clearObjects:Nt,browseObjects:qt,getObjectPosition:Wt,findObject:Bt,exists:Ht,saveSynonym:ae,saveSynonyms:oe,getSynonym:Vt,searchSynonyms:ce,browseSynonyms:kt,deleteSynonym:Ft,clearSynonyms:Et,replaceAllObjects:Yt,replaceAllSynonyms:$t,searchRules:se,getRule:Qt,deleteRule:Jt,saveRule:re,saveRules:ne,replaceAllRules:Zt,browseRules:St,clearRules:Rt}})}},initAnalytics:function(){return function(t){return function(t){var e=t.region||"us",n=c(m.WithinHeaders,t.appId,t.apiKey),a=k(r(r({hosts:[{url:"analytics.".concat(e,".algolia.com")}]},t),{},{headers:r(r(r({},n.headers()),{"content-type":"application/json"}),t.headers),queryParameters:r(r({},n.queryParameters()),t.queryParameters)}));return h({appId:t.appId,transporter:a},t.methods)}(r(r(r({},o),t),{},{methods:{addABTest:C,getABTest:z,getABTests:J,stopABTest:F,deleteABTest:U}}))}},initPersonalization:d,initRecommendation:function(){return function(t){return f.logger.info("The `initRecommendation` method is deprecated. Use `initPersonalization` instead."),d()(t)}},getRecommendations:ge,getFrequentlyBoughtTogether:ve,getLookingSimilar:we,getRecommendedForYou:Ie,getRelatedProducts:be,getTrendingFacets:Pe,getTrendingItems:Oe}}))}return xe.version="4.24.0",xe})); diff --git a/scripts/node_modules/algoliasearch/index.d.ts b/scripts/node_modules/algoliasearch/index.d.ts new file mode 100644 index 000000000..f3e17624b --- /dev/null +++ b/scripts/node_modules/algoliasearch/index.d.ts @@ -0,0 +1,3 @@ +/* eslint-disable import/no-unresolved*/ +export * from './dist/algoliasearch'; +export { default } from './dist/algoliasearch'; diff --git a/scripts/node_modules/algoliasearch/index.js b/scripts/node_modules/algoliasearch/index.js new file mode 100644 index 000000000..14ca1ec18 --- /dev/null +++ b/scripts/node_modules/algoliasearch/index.js @@ -0,0 +1,15 @@ +/* eslint-disable functional/immutable-data, import/no-commonjs */ +const algoliasearch = require('./dist/algoliasearch.cjs.js'); + +/** + * The Common JS build is the default entry point for the Node environment. Keep in + * in mind, that for the browser environment, we hint the bundler to use the UMD + * build instead as specified on the key `browser` of our `package.json` file. + */ +module.exports = algoliasearch; + +/** + * In addition, we also set explicitly the default export below making + * this Common JS module in compliance with es6 modules specification. + */ +module.exports.default = algoliasearch; diff --git a/scripts/node_modules/algoliasearch/lite.d.ts b/scripts/node_modules/algoliasearch/lite.d.ts new file mode 100644 index 000000000..41a19612f --- /dev/null +++ b/scripts/node_modules/algoliasearch/lite.d.ts @@ -0,0 +1,3 @@ +/* eslint-disable import/no-unresolved*/ +export * from './dist/algoliasearch-lite'; +export { default } from './dist/algoliasearch-lite'; diff --git a/scripts/node_modules/algoliasearch/lite.js b/scripts/node_modules/algoliasearch/lite.js new file mode 100644 index 000000000..cdbfa358a --- /dev/null +++ b/scripts/node_modules/algoliasearch/lite.js @@ -0,0 +1,2 @@ +// eslint-disable-next-line functional/immutable-data, import/no-commonjs +module.exports = require('./index'); diff --git a/scripts/node_modules/algoliasearch/package.json b/scripts/node_modules/algoliasearch/package.json new file mode 100644 index 000000000..f32ebacd9 --- /dev/null +++ b/scripts/node_modules/algoliasearch/package.json @@ -0,0 +1,47 @@ +{ + "name": "algoliasearch", + "version": "4.24.0", + "private": false, + "description": "A fully-featured and blazing-fast JavaScript API client to interact with Algolia API.", + "repository": { + "type": "git", + "url": "git://github.com/algolia/algoliasearch-client-javascript.git" + }, + "license": "MIT", + "sideEffects": false, + "main": "index.js", + "jsdelivr": "./dist/algoliasearch.umd.js", + "unpkg": "./dist/algoliasearch.umd.js", + "browser": { + "./index.js": "./dist/algoliasearch.umd.js", + "./lite.js": "./dist/algoliasearch-lite.umd.js" + }, + "types": "index.d.ts", + "files": [ + "dist", + "index.js", + "index.d.ts", + "lite.js", + "lite.d.ts" + ], + "scripts": { + "test:exports": "node --experimental-modules test/module/is-es-module.mjs && node test/module/is-cjs-module.cjs" + }, + "dependencies": { + "@algolia/cache-browser-local-storage": "4.24.0", + "@algolia/cache-common": "4.24.0", + "@algolia/cache-in-memory": "4.24.0", + "@algolia/client-account": "4.24.0", + "@algolia/client-analytics": "4.24.0", + "@algolia/client-common": "4.24.0", + "@algolia/client-personalization": "4.24.0", + "@algolia/client-search": "4.24.0", + "@algolia/logger-common": "4.24.0", + "@algolia/logger-console": "4.24.0", + "@algolia/recommend": "4.24.0", + "@algolia/requester-browser-xhr": "4.24.0", + "@algolia/requester-common": "4.24.0", + "@algolia/requester-node-http": "4.24.0", + "@algolia/transporter": "4.24.0" + } +} diff --git a/scripts/node_modules/argparse/CHANGELOG.md b/scripts/node_modules/argparse/CHANGELOG.md new file mode 100644 index 000000000..a43c628cc --- /dev/null +++ b/scripts/node_modules/argparse/CHANGELOG.md @@ -0,0 +1,185 @@ +1.0.10 / 2018-02-15 +------------------ + +- Use .concat instead of + for arrays, #122. + + +1.0.9 / 2016-09-29 +------------------ + +- Rerelease after 1.0.8 - deps cleanup. + + +1.0.8 / 2016-09-29 +------------------ + +- Maintenance (deps bump, fix node 6.5+ tests, coverage report). + + +1.0.7 / 2016-03-17 +------------------ + +- Teach `addArgument` to accept string arg names. #97, @tomxtobin. + + +1.0.6 / 2016-02-06 +------------------ + +- Maintenance: moved to eslint & updated CS. + + +1.0.5 / 2016-02-05 +------------------ + +- Removed lodash dependency to significantly reduce install size. + Thanks to @mourner. + + +1.0.4 / 2016-01-17 +------------------ + +- Maintenance: lodash update to 4.0.0. + + +1.0.3 / 2015-10-27 +------------------ + +- Fix parse `=` in args: `--examplepath="C:\myfolder\env=x64"`. #84, @CatWithApple. + + +1.0.2 / 2015-03-22 +------------------ + +- Relaxed lodash version dependency. + + +1.0.1 / 2015-02-20 +------------------ + +- Changed dependencies to be compatible with ancient nodejs. + + +1.0.0 / 2015-02-19 +------------------ + +- Maintenance release. +- Replaced `underscore` with `lodash`. +- Bumped version to 1.0.0 to better reflect semver meaning. +- HISTORY.md -> CHANGELOG.md + + +0.1.16 / 2013-12-01 +------------------- + +- Maintenance release. Updated dependencies and docs. + + +0.1.15 / 2013-05-13 +------------------- + +- Fixed #55, @trebor89 + + +0.1.14 / 2013-05-12 +------------------- + +- Fixed #62, @maxtaco + + +0.1.13 / 2013-04-08 +------------------- + +- Added `.npmignore` to reduce package size + + +0.1.12 / 2013-02-10 +------------------- + +- Fixed conflictHandler (#46), @hpaulj + + +0.1.11 / 2013-02-07 +------------------- + +- Multiple bugfixes, @hpaulj +- Added 70+ tests (ported from python), @hpaulj +- Added conflictHandler, @applepicke +- Added fromfilePrefixChar, @hpaulj + + +0.1.10 / 2012-12-30 +------------------- + +- Added [mutual exclusion](http://docs.python.org/dev/library/argparse.html#mutual-exclusion) + support, thanks to @hpaulj +- Fixed options check for `storeConst` & `appendConst` actions, thanks to @hpaulj + + +0.1.9 / 2012-12-27 +------------------ + +- Fixed option dest interferens with other options (issue #23), thanks to @hpaulj +- Fixed default value behavior with `*` positionals, thanks to @hpaulj +- Improve `getDefault()` behavior, thanks to @hpaulj +- Imrove negative argument parsing, thanks to @hpaulj + + +0.1.8 / 2012-12-01 +------------------ + +- Fixed parser parents (issue #19), thanks to @hpaulj +- Fixed negative argument parse (issue #20), thanks to @hpaulj + + +0.1.7 / 2012-10-14 +------------------ + +- Fixed 'choices' argument parse (issue #16) +- Fixed stderr output (issue #15) + + +0.1.6 / 2012-09-09 +------------------ + +- Fixed check for conflict of options (thanks to @tomxtobin) + + +0.1.5 / 2012-09-03 +------------------ + +- Fix parser #setDefaults method (thanks to @tomxtobin) + + +0.1.4 / 2012-07-30 +------------------ + +- Fixed pseudo-argument support (thanks to @CGamesPlay) +- Fixed addHelp default (should be true), if not set (thanks to @benblank) + + +0.1.3 / 2012-06-27 +------------------ + +- Fixed formatter api name: Formatter -> HelpFormatter + + +0.1.2 / 2012-05-29 +------------------ + +- Added basic tests +- Removed excess whitespace in help +- Fixed error reporting, when parcer with subcommands + called with empty arguments + + +0.1.1 / 2012-05-23 +------------------ + +- Fixed line wrapping in help formatter +- Added better error reporting on invalid arguments + + +0.1.0 / 2012-05-16 +------------------ + +- First release. diff --git a/scripts/node_modules/argparse/LICENSE b/scripts/node_modules/argparse/LICENSE new file mode 100644 index 000000000..1afdae558 --- /dev/null +++ b/scripts/node_modules/argparse/LICENSE @@ -0,0 +1,21 @@ +(The MIT License) + +Copyright (C) 2012 by Vitaly Puzrin + +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/scripts/node_modules/argparse/README.md b/scripts/node_modules/argparse/README.md new file mode 100644 index 000000000..7fa6c4050 --- /dev/null +++ b/scripts/node_modules/argparse/README.md @@ -0,0 +1,257 @@ +argparse +======== + +[![Build Status](https://secure.travis-ci.org/nodeca/argparse.svg?branch=master)](http://travis-ci.org/nodeca/argparse) +[![NPM version](https://img.shields.io/npm/v/argparse.svg)](https://www.npmjs.org/package/argparse) + +CLI arguments parser for node.js. Javascript port of python's +[argparse](http://docs.python.org/dev/library/argparse.html) module +(original version 3.2). That's a full port, except some very rare options, +recorded in issue tracker. + +**NB. Difference with original.** + +- Method names changed to camelCase. See [generated docs](http://nodeca.github.com/argparse/). +- Use `defaultValue` instead of `default`. +- Use `argparse.Const.REMAINDER` instead of `argparse.REMAINDER`, and + similarly for constant values `OPTIONAL`, `ZERO_OR_MORE`, and `ONE_OR_MORE` + (aliases for `nargs` values `'?'`, `'*'`, `'+'`, respectively), and + `SUPPRESS`. + + +Example +======= + +test.js file: + +```javascript +#!/usr/bin/env node +'use strict'; + +var ArgumentParser = require('../lib/argparse').ArgumentParser; +var parser = new ArgumentParser({ + version: '0.0.1', + addHelp:true, + description: 'Argparse example' +}); +parser.addArgument( + [ '-f', '--foo' ], + { + help: 'foo bar' + } +); +parser.addArgument( + [ '-b', '--bar' ], + { + help: 'bar foo' + } +); +parser.addArgument( + '--baz', + { + help: 'baz bar' + } +); +var args = parser.parseArgs(); +console.dir(args); +``` + +Display help: + +``` +$ ./test.js -h +usage: example.js [-h] [-v] [-f FOO] [-b BAR] [--baz BAZ] + +Argparse example + +Optional arguments: + -h, --help Show this help message and exit. + -v, --version Show program's version number and exit. + -f FOO, --foo FOO foo bar + -b BAR, --bar BAR bar foo + --baz BAZ baz bar +``` + +Parse arguments: + +``` +$ ./test.js -f=3 --bar=4 --baz 5 +{ foo: '3', bar: '4', baz: '5' } +``` + +More [examples](https://github.com/nodeca/argparse/tree/master/examples). + + +ArgumentParser objects +====================== + +``` +new ArgumentParser({parameters hash}); +``` + +Creates a new ArgumentParser object. + +**Supported params:** + +- ```description``` - Text to display before the argument help. +- ```epilog``` - Text to display after the argument help. +- ```addHelp``` - Add a -h/–help option to the parser. (default: true) +- ```argumentDefault``` - Set the global default value for arguments. (default: null) +- ```parents``` - A list of ArgumentParser objects whose arguments should also be included. +- ```prefixChars``` - The set of characters that prefix optional arguments. (default: ‘-‘) +- ```formatterClass``` - A class for customizing the help output. +- ```prog``` - The name of the program (default: `path.basename(process.argv[1])`) +- ```usage``` - The string describing the program usage (default: generated) +- ```conflictHandler``` - Usually unnecessary, defines strategy for resolving conflicting optionals. + +**Not supported yet** + +- ```fromfilePrefixChars``` - The set of characters that prefix files from which additional arguments should be read. + + +Details in [original ArgumentParser guide](http://docs.python.org/dev/library/argparse.html#argumentparser-objects) + + +addArgument() method +==================== + +``` +ArgumentParser.addArgument(name or flag or [name] or [flags...], {options}) +``` + +Defines how a single command-line argument should be parsed. + +- ```name or flag or [name] or [flags...]``` - Either a positional name + (e.g., `'foo'`), a single option (e.g., `'-f'` or `'--foo'`), an array + of a single positional name (e.g., `['foo']`), or an array of options + (e.g., `['-f', '--foo']`). + +Options: + +- ```action``` - The basic type of action to be taken when this argument is encountered at the command line. +- ```nargs```- The number of command-line arguments that should be consumed. +- ```constant``` - A constant value required by some action and nargs selections. +- ```defaultValue``` - The value produced if the argument is absent from the command line. +- ```type``` - The type to which the command-line argument should be converted. +- ```choices``` - A container of the allowable values for the argument. +- ```required``` - Whether or not the command-line option may be omitted (optionals only). +- ```help``` - A brief description of what the argument does. +- ```metavar``` - A name for the argument in usage messages. +- ```dest``` - The name of the attribute to be added to the object returned by parseArgs(). + +Details in [original add_argument guide](http://docs.python.org/dev/library/argparse.html#the-add-argument-method) + + +Action (some details) +================ + +ArgumentParser objects associate command-line arguments with actions. +These actions can do just about anything with the command-line arguments associated +with them, though most actions simply add an attribute to the object returned by +parseArgs(). The action keyword argument specifies how the command-line arguments +should be handled. The supported actions are: + +- ```store``` - Just stores the argument’s value. This is the default action. +- ```storeConst``` - Stores value, specified by the const keyword argument. + (Note that the const keyword argument defaults to the rather unhelpful None.) + The 'storeConst' action is most commonly used with optional arguments, that + specify some sort of flag. +- ```storeTrue``` and ```storeFalse``` - Stores values True and False + respectively. These are special cases of 'storeConst'. +- ```append``` - Stores a list, and appends each argument value to the list. + This is useful to allow an option to be specified multiple times. +- ```appendConst``` - Stores a list, and appends value, specified by the + const keyword argument to the list. (Note, that the const keyword argument defaults + is None.) The 'appendConst' action is typically used when multiple arguments need + to store constants to the same list. +- ```count``` - Counts the number of times a keyword argument occurs. For example, + used for increasing verbosity levels. +- ```help``` - Prints a complete help message for all the options in the current + parser and then exits. By default a help action is automatically added to the parser. + See ArgumentParser for details of how the output is created. +- ```version``` - Prints version information and exit. Expects a `version=` + keyword argument in the addArgument() call. + +Details in [original action guide](http://docs.python.org/dev/library/argparse.html#action) + + +Sub-commands +============ + +ArgumentParser.addSubparsers() + +Many programs split their functionality into a number of sub-commands, for +example, the svn program can invoke sub-commands like `svn checkout`, `svn update`, +and `svn commit`. Splitting up functionality this way can be a particularly good +idea when a program performs several different functions which require different +kinds of command-line arguments. `ArgumentParser` supports creation of such +sub-commands with `addSubparsers()` method. The `addSubparsers()` method is +normally called with no arguments and returns an special action object. +This object has a single method `addParser()`, which takes a command name and +any `ArgumentParser` constructor arguments, and returns an `ArgumentParser` object +that can be modified as usual. + +Example: + +sub_commands.js +```javascript +#!/usr/bin/env node +'use strict'; + +var ArgumentParser = require('../lib/argparse').ArgumentParser; +var parser = new ArgumentParser({ + version: '0.0.1', + addHelp:true, + description: 'Argparse examples: sub-commands', +}); + +var subparsers = parser.addSubparsers({ + title:'subcommands', + dest:"subcommand_name" +}); + +var bar = subparsers.addParser('c1', {addHelp:true}); +bar.addArgument( + [ '-f', '--foo' ], + { + action: 'store', + help: 'foo3 bar3' + } +); +var bar = subparsers.addParser( + 'c2', + {aliases:['co'], addHelp:true} +); +bar.addArgument( + [ '-b', '--bar' ], + { + action: 'store', + type: 'int', + help: 'foo3 bar3' + } +); + +var args = parser.parseArgs(); +console.dir(args); + +``` + +Details in [original sub-commands guide](http://docs.python.org/dev/library/argparse.html#sub-commands) + + +Contributors +============ + +- [Eugene Shkuropat](https://github.com/shkuropat) +- [Paul Jacobson](https://github.com/hpaulj) + +[others](https://github.com/nodeca/argparse/graphs/contributors) + +License +======= + +Copyright (c) 2012 [Vitaly Puzrin](https://github.com/puzrin). +Released under the MIT license. See +[LICENSE](https://github.com/nodeca/argparse/blob/master/LICENSE) for details. + + diff --git a/scripts/node_modules/argparse/index.js b/scripts/node_modules/argparse/index.js new file mode 100644 index 000000000..3bbc14320 --- /dev/null +++ b/scripts/node_modules/argparse/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./lib/argparse'); diff --git a/scripts/node_modules/argparse/lib/action.js b/scripts/node_modules/argparse/lib/action.js new file mode 100644 index 000000000..1483c79ff --- /dev/null +++ b/scripts/node_modules/argparse/lib/action.js @@ -0,0 +1,146 @@ +/** + * class Action + * + * Base class for all actions + * Do not call in your code, use this class only for inherits your own action + * + * Information about how to convert command line strings to Javascript objects. + * Action objects are used by an ArgumentParser to represent the information + * needed to parse a single argument from one or more strings from the command + * line. The keyword arguments to the Action constructor are also all attributes + * of Action instances. + * + * ##### Allowed keywords: + * + * - `store` + * - `storeConstant` + * - `storeTrue` + * - `storeFalse` + * - `append` + * - `appendConstant` + * - `count` + * - `help` + * - `version` + * + * Information about action options see [[Action.new]] + * + * See also [original guide](http://docs.python.org/dev/library/argparse.html#action) + * + **/ + +'use strict'; + + +// Constants +var c = require('./const'); + + +/** + * new Action(options) + * + * Base class for all actions. Used only for inherits + * + * + * ##### Options: + * + * - `optionStrings` A list of command-line option strings for the action. + * - `dest` Attribute to hold the created object(s) + * - `nargs` The number of command-line arguments that should be consumed. + * By default, one argument will be consumed and a single value will be + * produced. + * - `constant` Default value for an action with no value. + * - `defaultValue` The value to be produced if the option is not specified. + * - `type` Cast to 'string'|'int'|'float'|'complex'|function (string). If + * None, 'string'. + * - `choices` The choices available. + * - `required` True if the action must always be specified at the command + * line. + * - `help` The help describing the argument. + * - `metavar` The name to be used for the option's argument with the help + * string. If None, the 'dest' value will be used as the name. + * + * ##### nargs supported values: + * + * - `N` (an integer) consumes N arguments (and produces a list) + * - `?` consumes zero or one arguments + * - `*` consumes zero or more arguments (and produces a list) + * - `+` consumes one or more arguments (and produces a list) + * + * Note: that the difference between the default and nargs=1 is that with the + * default, a single value will be produced, while with nargs=1, a list + * containing a single value will be produced. + **/ +var Action = module.exports = function Action(options) { + options = options || {}; + this.optionStrings = options.optionStrings || []; + this.dest = options.dest; + this.nargs = typeof options.nargs !== 'undefined' ? options.nargs : null; + this.constant = typeof options.constant !== 'undefined' ? options.constant : null; + this.defaultValue = options.defaultValue; + this.type = typeof options.type !== 'undefined' ? options.type : null; + this.choices = typeof options.choices !== 'undefined' ? options.choices : null; + this.required = typeof options.required !== 'undefined' ? options.required : false; + this.help = typeof options.help !== 'undefined' ? options.help : null; + this.metavar = typeof options.metavar !== 'undefined' ? options.metavar : null; + + if (!(this.optionStrings instanceof Array)) { + throw new Error('optionStrings should be an array'); + } + if (typeof this.required !== 'undefined' && typeof this.required !== 'boolean') { + throw new Error('required should be a boolean'); + } +}; + +/** + * Action#getName -> String + * + * Tells action name + **/ +Action.prototype.getName = function () { + if (this.optionStrings.length > 0) { + return this.optionStrings.join('/'); + } else if (this.metavar !== null && this.metavar !== c.SUPPRESS) { + return this.metavar; + } else if (typeof this.dest !== 'undefined' && this.dest !== c.SUPPRESS) { + return this.dest; + } + return null; +}; + +/** + * Action#isOptional -> Boolean + * + * Return true if optional + **/ +Action.prototype.isOptional = function () { + return !this.isPositional(); +}; + +/** + * Action#isPositional -> Boolean + * + * Return true if positional + **/ +Action.prototype.isPositional = function () { + return (this.optionStrings.length === 0); +}; + +/** + * Action#call(parser, namespace, values, optionString) -> Void + * - parser (ArgumentParser): current parser + * - namespace (Namespace): namespace for output data + * - values (Array): parsed values + * - optionString (Array): input option string(not parsed) + * + * Call the action. Should be implemented in inherited classes + * + * ##### Example + * + * ActionCount.prototype.call = function (parser, namespace, values, optionString) { + * namespace.set(this.dest, (namespace[this.dest] || 0) + 1); + * }; + * + **/ +Action.prototype.call = function () { + throw new Error('.call() not defined');// Not Implemented error +}; diff --git a/scripts/node_modules/argparse/lib/action/append.js b/scripts/node_modules/argparse/lib/action/append.js new file mode 100644 index 000000000..b5da0de23 --- /dev/null +++ b/scripts/node_modules/argparse/lib/action/append.js @@ -0,0 +1,53 @@ +/*:nodoc:* + * class ActionAppend + * + * This action stores a list, and appends each argument value to the list. + * This is useful to allow an option to be specified multiple times. + * This class inherided from [[Action]] + * + **/ + +'use strict'; + +var util = require('util'); + +var Action = require('../action'); + +// Constants +var c = require('../const'); + +/*:nodoc:* + * new ActionAppend(options) + * - options (object): options hash see [[Action.new]] + * + * Note: options.nargs should be optional for constants + * and more then zero for other + **/ +var ActionAppend = module.exports = function ActionAppend(options) { + options = options || {}; + if (this.nargs <= 0) { + throw new Error('nargs for append actions must be > 0; if arg ' + + 'strings are not supplying the value to append, ' + + 'the append const action may be more appropriate'); + } + if (!!this.constant && this.nargs !== c.OPTIONAL) { + throw new Error('nargs must be OPTIONAL to supply const'); + } + Action.call(this, options); +}; +util.inherits(ActionAppend, Action); + +/*:nodoc:* + * ActionAppend#call(parser, namespace, values, optionString) -> Void + * - parser (ArgumentParser): current parser + * - namespace (Namespace): namespace for output data + * - values (Array): parsed values + * - optionString (Array): input option string(not parsed) + * + * Call the action. Save result in namespace object + **/ +ActionAppend.prototype.call = function (parser, namespace, values) { + var items = (namespace[this.dest] || []).slice(); + items.push(values); + namespace.set(this.dest, items); +}; diff --git a/scripts/node_modules/argparse/lib/action/append/constant.js b/scripts/node_modules/argparse/lib/action/append/constant.js new file mode 100644 index 000000000..313f5d2ef --- /dev/null +++ b/scripts/node_modules/argparse/lib/action/append/constant.js @@ -0,0 +1,47 @@ +/*:nodoc:* + * class ActionAppendConstant + * + * This stores a list, and appends the value specified by + * the const keyword argument to the list. + * (Note that the const keyword argument defaults to null.) + * The 'appendConst' action is typically useful when multiple + * arguments need to store constants to the same list. + * + * This class inherited from [[Action]] + **/ + +'use strict'; + +var util = require('util'); + +var Action = require('../../action'); + +/*:nodoc:* + * new ActionAppendConstant(options) + * - options (object): options hash see [[Action.new]] + * + **/ +var ActionAppendConstant = module.exports = function ActionAppendConstant(options) { + options = options || {}; + options.nargs = 0; + if (typeof options.constant === 'undefined') { + throw new Error('constant option is required for appendAction'); + } + Action.call(this, options); +}; +util.inherits(ActionAppendConstant, Action); + +/*:nodoc:* + * ActionAppendConstant#call(parser, namespace, values, optionString) -> Void + * - parser (ArgumentParser): current parser + * - namespace (Namespace): namespace for output data + * - values (Array): parsed values + * - optionString (Array): input option string(not parsed) + * + * Call the action. Save result in namespace object + **/ +ActionAppendConstant.prototype.call = function (parser, namespace) { + var items = [].concat(namespace[this.dest] || []); + items.push(this.constant); + namespace.set(this.dest, items); +}; diff --git a/scripts/node_modules/argparse/lib/action/count.js b/scripts/node_modules/argparse/lib/action/count.js new file mode 100644 index 000000000..d6a5899d0 --- /dev/null +++ b/scripts/node_modules/argparse/lib/action/count.js @@ -0,0 +1,40 @@ +/*:nodoc:* + * class ActionCount + * + * This counts the number of times a keyword argument occurs. + * For example, this is useful for increasing verbosity levels + * + * This class inherided from [[Action]] + * + **/ +'use strict'; + +var util = require('util'); + +var Action = require('../action'); + +/*:nodoc:* + * new ActionCount(options) + * - options (object): options hash see [[Action.new]] + * + **/ +var ActionCount = module.exports = function ActionCount(options) { + options = options || {}; + options.nargs = 0; + + Action.call(this, options); +}; +util.inherits(ActionCount, Action); + +/*:nodoc:* + * ActionCount#call(parser, namespace, values, optionString) -> Void + * - parser (ArgumentParser): current parser + * - namespace (Namespace): namespace for output data + * - values (Array): parsed values + * - optionString (Array): input option string(not parsed) + * + * Call the action. Save result in namespace object + **/ +ActionCount.prototype.call = function (parser, namespace) { + namespace.set(this.dest, (namespace[this.dest] || 0) + 1); +}; diff --git a/scripts/node_modules/argparse/lib/action/help.js b/scripts/node_modules/argparse/lib/action/help.js new file mode 100644 index 000000000..b40e05a6f --- /dev/null +++ b/scripts/node_modules/argparse/lib/action/help.js @@ -0,0 +1,47 @@ +/*:nodoc:* + * class ActionHelp + * + * Support action for printing help + * This class inherided from [[Action]] + **/ +'use strict'; + +var util = require('util'); + +var Action = require('../action'); + +// Constants +var c = require('../const'); + +/*:nodoc:* + * new ActionHelp(options) + * - options (object): options hash see [[Action.new]] + * + **/ +var ActionHelp = module.exports = function ActionHelp(options) { + options = options || {}; + if (options.defaultValue !== null) { + options.defaultValue = options.defaultValue; + } else { + options.defaultValue = c.SUPPRESS; + } + options.dest = (options.dest !== null ? options.dest : c.SUPPRESS); + options.nargs = 0; + Action.call(this, options); + +}; +util.inherits(ActionHelp, Action); + +/*:nodoc:* + * ActionHelp#call(parser, namespace, values, optionString) + * - parser (ArgumentParser): current parser + * - namespace (Namespace): namespace for output data + * - values (Array): parsed values + * - optionString (Array): input option string(not parsed) + * + * Print help and exit + **/ +ActionHelp.prototype.call = function (parser) { + parser.printHelp(); + parser.exit(); +}; diff --git a/scripts/node_modules/argparse/lib/action/store.js b/scripts/node_modules/argparse/lib/action/store.js new file mode 100644 index 000000000..283b86092 --- /dev/null +++ b/scripts/node_modules/argparse/lib/action/store.js @@ -0,0 +1,50 @@ +/*:nodoc:* + * class ActionStore + * + * This action just stores the argument’s value. This is the default action. + * + * This class inherited from [[Action]] + * + **/ +'use strict'; + +var util = require('util'); + +var Action = require('../action'); + +// Constants +var c = require('../const'); + + +/*:nodoc:* + * new ActionStore(options) + * - options (object): options hash see [[Action.new]] + * + **/ +var ActionStore = module.exports = function ActionStore(options) { + options = options || {}; + if (this.nargs <= 0) { + throw new Error('nargs for store actions must be > 0; if you ' + + 'have nothing to store, actions such as store ' + + 'true or store const may be more appropriate'); + + } + if (typeof this.constant !== 'undefined' && this.nargs !== c.OPTIONAL) { + throw new Error('nargs must be OPTIONAL to supply const'); + } + Action.call(this, options); +}; +util.inherits(ActionStore, Action); + +/*:nodoc:* + * ActionStore#call(parser, namespace, values, optionString) -> Void + * - parser (ArgumentParser): current parser + * - namespace (Namespace): namespace for output data + * - values (Array): parsed values + * - optionString (Array): input option string(not parsed) + * + * Call the action. Save result in namespace object + **/ +ActionStore.prototype.call = function (parser, namespace, values) { + namespace.set(this.dest, values); +}; diff --git a/scripts/node_modules/argparse/lib/action/store/constant.js b/scripts/node_modules/argparse/lib/action/store/constant.js new file mode 100644 index 000000000..23caa897b --- /dev/null +++ b/scripts/node_modules/argparse/lib/action/store/constant.js @@ -0,0 +1,43 @@ +/*:nodoc:* + * class ActionStoreConstant + * + * This action stores the value specified by the const keyword argument. + * (Note that the const keyword argument defaults to the rather unhelpful null.) + * The 'store_const' action is most commonly used with optional + * arguments that specify some sort of flag. + * + * This class inherited from [[Action]] + **/ +'use strict'; + +var util = require('util'); + +var Action = require('../../action'); + +/*:nodoc:* + * new ActionStoreConstant(options) + * - options (object): options hash see [[Action.new]] + * + **/ +var ActionStoreConstant = module.exports = function ActionStoreConstant(options) { + options = options || {}; + options.nargs = 0; + if (typeof options.constant === 'undefined') { + throw new Error('constant option is required for storeAction'); + } + Action.call(this, options); +}; +util.inherits(ActionStoreConstant, Action); + +/*:nodoc:* + * ActionStoreConstant#call(parser, namespace, values, optionString) -> Void + * - parser (ArgumentParser): current parser + * - namespace (Namespace): namespace for output data + * - values (Array): parsed values + * - optionString (Array): input option string(not parsed) + * + * Call the action. Save result in namespace object + **/ +ActionStoreConstant.prototype.call = function (parser, namespace) { + namespace.set(this.dest, this.constant); +}; diff --git a/scripts/node_modules/argparse/lib/action/store/false.js b/scripts/node_modules/argparse/lib/action/store/false.js new file mode 100644 index 000000000..9924f461d --- /dev/null +++ b/scripts/node_modules/argparse/lib/action/store/false.js @@ -0,0 +1,27 @@ +/*:nodoc:* + * class ActionStoreFalse + * + * This action store the values False respectively. + * This is special cases of 'storeConst' + * + * This class inherited from [[Action]] + **/ + +'use strict'; + +var util = require('util'); + +var ActionStoreConstant = require('./constant'); + +/*:nodoc:* + * new ActionStoreFalse(options) + * - options (object): hash of options see [[Action.new]] + * + **/ +var ActionStoreFalse = module.exports = function ActionStoreFalse(options) { + options = options || {}; + options.constant = false; + options.defaultValue = options.defaultValue !== null ? options.defaultValue : true; + ActionStoreConstant.call(this, options); +}; +util.inherits(ActionStoreFalse, ActionStoreConstant); diff --git a/scripts/node_modules/argparse/lib/action/store/true.js b/scripts/node_modules/argparse/lib/action/store/true.js new file mode 100644 index 000000000..9e22f7d44 --- /dev/null +++ b/scripts/node_modules/argparse/lib/action/store/true.js @@ -0,0 +1,26 @@ +/*:nodoc:* + * class ActionStoreTrue + * + * This action store the values True respectively. + * This isspecial cases of 'storeConst' + * + * This class inherited from [[Action]] + **/ +'use strict'; + +var util = require('util'); + +var ActionStoreConstant = require('./constant'); + +/*:nodoc:* + * new ActionStoreTrue(options) + * - options (object): options hash see [[Action.new]] + * + **/ +var ActionStoreTrue = module.exports = function ActionStoreTrue(options) { + options = options || {}; + options.constant = true; + options.defaultValue = options.defaultValue !== null ? options.defaultValue : false; + ActionStoreConstant.call(this, options); +}; +util.inherits(ActionStoreTrue, ActionStoreConstant); diff --git a/scripts/node_modules/argparse/lib/action/subparsers.js b/scripts/node_modules/argparse/lib/action/subparsers.js new file mode 100644 index 000000000..99dfedd0f --- /dev/null +++ b/scripts/node_modules/argparse/lib/action/subparsers.js @@ -0,0 +1,149 @@ +/** internal + * class ActionSubparsers + * + * Support the creation of such sub-commands with the addSubparsers() + * + * This class inherited from [[Action]] + **/ +'use strict'; + +var util = require('util'); +var format = require('util').format; + + +var Action = require('../action'); + +// Constants +var c = require('../const'); + +// Errors +var argumentErrorHelper = require('../argument/error'); + + +/*:nodoc:* + * new ChoicesPseudoAction(name, help) + * + * Create pseudo action for correct help text + * + **/ +function ChoicesPseudoAction(name, help) { + var options = { + optionStrings: [], + dest: name, + help: help + }; + + Action.call(this, options); +} + +util.inherits(ChoicesPseudoAction, Action); + +/** + * new ActionSubparsers(options) + * - options (object): options hash see [[Action.new]] + * + **/ +function ActionSubparsers(options) { + options = options || {}; + options.dest = options.dest || c.SUPPRESS; + options.nargs = c.PARSER; + + this.debug = (options.debug === true); + + this._progPrefix = options.prog; + this._parserClass = options.parserClass; + this._nameParserMap = {}; + this._choicesActions = []; + + options.choices = this._nameParserMap; + Action.call(this, options); +} + +util.inherits(ActionSubparsers, Action); + +/*:nodoc:* + * ActionSubparsers#addParser(name, options) -> ArgumentParser + * - name (string): sub-command name + * - options (object): see [[ArgumentParser.new]] + * + * Note: + * addParser supports an additional aliases option, + * which allows multiple strings to refer to the same subparser. + * This example, like svn, aliases co as a shorthand for checkout + * + **/ +ActionSubparsers.prototype.addParser = function (name, options) { + var parser; + + var self = this; + + options = options || {}; + + options.debug = (this.debug === true); + + // set program from the existing prefix + if (!options.prog) { + options.prog = this._progPrefix + ' ' + name; + } + + var aliases = options.aliases || []; + + // create a pseudo-action to hold the choice help + if (!!options.help || typeof options.help === 'string') { + var help = options.help; + delete options.help; + + var choiceAction = new ChoicesPseudoAction(name, help); + this._choicesActions.push(choiceAction); + } + + // create the parser and add it to the map + parser = new this._parserClass(options); + this._nameParserMap[name] = parser; + + // make parser available under aliases also + aliases.forEach(function (alias) { + self._nameParserMap[alias] = parser; + }); + + return parser; +}; + +ActionSubparsers.prototype._getSubactions = function () { + return this._choicesActions; +}; + +/*:nodoc:* + * ActionSubparsers#call(parser, namespace, values, optionString) -> Void + * - parser (ArgumentParser): current parser + * - namespace (Namespace): namespace for output data + * - values (Array): parsed values + * - optionString (Array): input option string(not parsed) + * + * Call the action. Parse input aguments + **/ +ActionSubparsers.prototype.call = function (parser, namespace, values) { + var parserName = values[0]; + var argStrings = values.slice(1); + + // set the parser name if requested + if (this.dest !== c.SUPPRESS) { + namespace[this.dest] = parserName; + } + + // select the parser + if (this._nameParserMap[parserName]) { + parser = this._nameParserMap[parserName]; + } else { + throw argumentErrorHelper(format( + 'Unknown parser "%s" (choices: [%s]).', + parserName, + Object.keys(this._nameParserMap).join(', ') + )); + } + + // parse all the remaining options into the namespace + parser.parseArgs(argStrings, namespace); +}; + +module.exports = ActionSubparsers; diff --git a/scripts/node_modules/argparse/lib/action/version.js b/scripts/node_modules/argparse/lib/action/version.js new file mode 100644 index 000000000..8053328cd --- /dev/null +++ b/scripts/node_modules/argparse/lib/action/version.js @@ -0,0 +1,47 @@ +/*:nodoc:* + * class ActionVersion + * + * Support action for printing program version + * This class inherited from [[Action]] + **/ +'use strict'; + +var util = require('util'); + +var Action = require('../action'); + +// +// Constants +// +var c = require('../const'); + +/*:nodoc:* + * new ActionVersion(options) + * - options (object): options hash see [[Action.new]] + * + **/ +var ActionVersion = module.exports = function ActionVersion(options) { + options = options || {}; + options.defaultValue = (options.defaultValue ? options.defaultValue : c.SUPPRESS); + options.dest = (options.dest || c.SUPPRESS); + options.nargs = 0; + this.version = options.version; + Action.call(this, options); +}; +util.inherits(ActionVersion, Action); + +/*:nodoc:* + * ActionVersion#call(parser, namespace, values, optionString) -> Void + * - parser (ArgumentParser): current parser + * - namespace (Namespace): namespace for output data + * - values (Array): parsed values + * - optionString (Array): input option string(not parsed) + * + * Print version and exit + **/ +ActionVersion.prototype.call = function (parser) { + var version = this.version || parser.version; + var formatter = parser._getFormatter(); + formatter.addText(version); + parser.exit(0, formatter.formatHelp()); +}; diff --git a/scripts/node_modules/argparse/lib/action_container.js b/scripts/node_modules/argparse/lib/action_container.js new file mode 100644 index 000000000..6f1237bea --- /dev/null +++ b/scripts/node_modules/argparse/lib/action_container.js @@ -0,0 +1,482 @@ +/** internal + * class ActionContainer + * + * Action container. Parent for [[ArgumentParser]] and [[ArgumentGroup]] + **/ + +'use strict'; + +var format = require('util').format; + +// Constants +var c = require('./const'); + +var $$ = require('./utils'); + +//Actions +var ActionHelp = require('./action/help'); +var ActionAppend = require('./action/append'); +var ActionAppendConstant = require('./action/append/constant'); +var ActionCount = require('./action/count'); +var ActionStore = require('./action/store'); +var ActionStoreConstant = require('./action/store/constant'); +var ActionStoreTrue = require('./action/store/true'); +var ActionStoreFalse = require('./action/store/false'); +var ActionVersion = require('./action/version'); +var ActionSubparsers = require('./action/subparsers'); + +// Errors +var argumentErrorHelper = require('./argument/error'); + +/** + * new ActionContainer(options) + * + * Action container. Parent for [[ArgumentParser]] and [[ArgumentGroup]] + * + * ##### Options: + * + * - `description` -- A description of what the program does + * - `prefixChars` -- Characters that prefix optional arguments + * - `argumentDefault` -- The default value for all arguments + * - `conflictHandler` -- The conflict handler to use for duplicate arguments + **/ +var ActionContainer = module.exports = function ActionContainer(options) { + options = options || {}; + + this.description = options.description; + this.argumentDefault = options.argumentDefault; + this.prefixChars = options.prefixChars || ''; + this.conflictHandler = options.conflictHandler; + + // set up registries + this._registries = {}; + + // register actions + this.register('action', null, ActionStore); + this.register('action', 'store', ActionStore); + this.register('action', 'storeConst', ActionStoreConstant); + this.register('action', 'storeTrue', ActionStoreTrue); + this.register('action', 'storeFalse', ActionStoreFalse); + this.register('action', 'append', ActionAppend); + this.register('action', 'appendConst', ActionAppendConstant); + this.register('action', 'count', ActionCount); + this.register('action', 'help', ActionHelp); + this.register('action', 'version', ActionVersion); + this.register('action', 'parsers', ActionSubparsers); + + // raise an exception if the conflict handler is invalid + this._getHandler(); + + // action storage + this._actions = []; + this._optionStringActions = {}; + + // groups + this._actionGroups = []; + this._mutuallyExclusiveGroups = []; + + // defaults storage + this._defaults = {}; + + // determines whether an "option" looks like a negative number + // -1, -1.5 -5e+4 + this._regexpNegativeNumber = new RegExp('^[-]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$'); + + // whether or not there are any optionals that look like negative + // numbers -- uses a list so it can be shared and edited + this._hasNegativeNumberOptionals = []; +}; + +// Groups must be required, then ActionContainer already defined +var ArgumentGroup = require('./argument/group'); +var MutuallyExclusiveGroup = require('./argument/exclusive'); + +// +// Registration methods +// + +/** + * ActionContainer#register(registryName, value, object) -> Void + * - registryName (String) : object type action|type + * - value (string) : keyword + * - object (Object|Function) : handler + * + * Register handlers + **/ +ActionContainer.prototype.register = function (registryName, value, object) { + this._registries[registryName] = this._registries[registryName] || {}; + this._registries[registryName][value] = object; +}; + +ActionContainer.prototype._registryGet = function (registryName, value, defaultValue) { + if (arguments.length < 3) { + defaultValue = null; + } + return this._registries[registryName][value] || defaultValue; +}; + +// +// Namespace default accessor methods +// + +/** + * ActionContainer#setDefaults(options) -> Void + * - options (object):hash of options see [[Action.new]] + * + * Set defaults + **/ +ActionContainer.prototype.setDefaults = function (options) { + options = options || {}; + for (var property in options) { + if ($$.has(options, property)) { + this._defaults[property] = options[property]; + } + } + + // if these defaults match any existing arguments, replace the previous + // default on the object with the new one + this._actions.forEach(function (action) { + if ($$.has(options, action.dest)) { + action.defaultValue = options[action.dest]; + } + }); +}; + +/** + * ActionContainer#getDefault(dest) -> Mixed + * - dest (string): action destination + * + * Return action default value + **/ +ActionContainer.prototype.getDefault = function (dest) { + var result = $$.has(this._defaults, dest) ? this._defaults[dest] : null; + + this._actions.forEach(function (action) { + if (action.dest === dest && $$.has(action, 'defaultValue')) { + result = action.defaultValue; + } + }); + + return result; +}; +// +// Adding argument actions +// + +/** + * ActionContainer#addArgument(args, options) -> Object + * - args (String|Array): argument key, or array of argument keys + * - options (Object): action objects see [[Action.new]] + * + * #### Examples + * - addArgument([ '-f', '--foo' ], { action: 'store', defaultValue: 1, ... }) + * - addArgument([ 'bar' ], { action: 'store', nargs: 1, ... }) + * - addArgument('--baz', { action: 'store', nargs: 1, ... }) + **/ +ActionContainer.prototype.addArgument = function (args, options) { + args = args; + options = options || {}; + + if (typeof args === 'string') { + args = [ args ]; + } + if (!Array.isArray(args)) { + throw new TypeError('addArgument first argument should be a string or an array'); + } + if (typeof options !== 'object' || Array.isArray(options)) { + throw new TypeError('addArgument second argument should be a hash'); + } + + // if no positional args are supplied or only one is supplied and + // it doesn't look like an option string, parse a positional argument + if (!args || args.length === 1 && this.prefixChars.indexOf(args[0][0]) < 0) { + if (args && !!options.dest) { + throw new Error('dest supplied twice for positional argument'); + } + options = this._getPositional(args, options); + + // otherwise, we're adding an optional argument + } else { + options = this._getOptional(args, options); + } + + // if no default was supplied, use the parser-level default + if (typeof options.defaultValue === 'undefined') { + var dest = options.dest; + if ($$.has(this._defaults, dest)) { + options.defaultValue = this._defaults[dest]; + } else if (typeof this.argumentDefault !== 'undefined') { + options.defaultValue = this.argumentDefault; + } + } + + // create the action object, and add it to the parser + var ActionClass = this._popActionClass(options); + if (typeof ActionClass !== 'function') { + throw new Error(format('Unknown action "%s".', ActionClass)); + } + var action = new ActionClass(options); + + // throw an error if the action type is not callable + var typeFunction = this._registryGet('type', action.type, action.type); + if (typeof typeFunction !== 'function') { + throw new Error(format('"%s" is not callable', typeFunction)); + } + + return this._addAction(action); +}; + +/** + * ActionContainer#addArgumentGroup(options) -> ArgumentGroup + * - options (Object): hash of options see [[ArgumentGroup.new]] + * + * Create new arguments groups + **/ +ActionContainer.prototype.addArgumentGroup = function (options) { + var group = new ArgumentGroup(this, options); + this._actionGroups.push(group); + return group; +}; + +/** + * ActionContainer#addMutuallyExclusiveGroup(options) -> ArgumentGroup + * - options (Object): {required: false} + * + * Create new mutual exclusive groups + **/ +ActionContainer.prototype.addMutuallyExclusiveGroup = function (options) { + var group = new MutuallyExclusiveGroup(this, options); + this._mutuallyExclusiveGroups.push(group); + return group; +}; + +ActionContainer.prototype._addAction = function (action) { + var self = this; + + // resolve any conflicts + this._checkConflict(action); + + // add to actions list + this._actions.push(action); + action.container = this; + + // index the action by any option strings it has + action.optionStrings.forEach(function (optionString) { + self._optionStringActions[optionString] = action; + }); + + // set the flag if any option strings look like negative numbers + action.optionStrings.forEach(function (optionString) { + if (optionString.match(self._regexpNegativeNumber)) { + if (!self._hasNegativeNumberOptionals.some(Boolean)) { + self._hasNegativeNumberOptionals.push(true); + } + } + }); + + // return the created action + return action; +}; + +ActionContainer.prototype._removeAction = function (action) { + var actionIndex = this._actions.indexOf(action); + if (actionIndex >= 0) { + this._actions.splice(actionIndex, 1); + } +}; + +ActionContainer.prototype._addContainerActions = function (container) { + // collect groups by titles + var titleGroupMap = {}; + this._actionGroups.forEach(function (group) { + if (titleGroupMap[group.title]) { + throw new Error(format('Cannot merge actions - two groups are named "%s".', group.title)); + } + titleGroupMap[group.title] = group; + }); + + // map each action to its group + var groupMap = {}; + function actionHash(action) { + // unique (hopefully?) string suitable as dictionary key + return action.getName(); + } + container._actionGroups.forEach(function (group) { + // if a group with the title exists, use that, otherwise + // create a new group matching the container's group + if (!titleGroupMap[group.title]) { + titleGroupMap[group.title] = this.addArgumentGroup({ + title: group.title, + description: group.description + }); + } + + // map the actions to their new group + group._groupActions.forEach(function (action) { + groupMap[actionHash(action)] = titleGroupMap[group.title]; + }); + }, this); + + // add container's mutually exclusive groups + // NOTE: if add_mutually_exclusive_group ever gains title= and + // description= then this code will need to be expanded as above + var mutexGroup; + container._mutuallyExclusiveGroups.forEach(function (group) { + mutexGroup = this.addMutuallyExclusiveGroup({ + required: group.required + }); + // map the actions to their new mutex group + group._groupActions.forEach(function (action) { + groupMap[actionHash(action)] = mutexGroup; + }); + }, this); // forEach takes a 'this' argument + + // add all actions to this container or their group + container._actions.forEach(function (action) { + var key = actionHash(action); + if (groupMap[key]) { + groupMap[key]._addAction(action); + } else { + this._addAction(action); + } + }); +}; + +ActionContainer.prototype._getPositional = function (dest, options) { + if (Array.isArray(dest)) { + dest = dest[0]; + } + // make sure required is not specified + if (options.required) { + throw new Error('"required" is an invalid argument for positionals.'); + } + + // mark positional arguments as required if at least one is + // always required + if (options.nargs !== c.OPTIONAL && options.nargs !== c.ZERO_OR_MORE) { + options.required = true; + } + if (options.nargs === c.ZERO_OR_MORE && typeof options.defaultValue === 'undefined') { + options.required = true; + } + + // return the keyword arguments with no option strings + options.dest = dest; + options.optionStrings = []; + return options; +}; + +ActionContainer.prototype._getOptional = function (args, options) { + var prefixChars = this.prefixChars; + var optionStrings = []; + var optionStringsLong = []; + + // determine short and long option strings + args.forEach(function (optionString) { + // error on strings that don't start with an appropriate prefix + if (prefixChars.indexOf(optionString[0]) < 0) { + throw new Error(format('Invalid option string "%s": must start with a "%s".', + optionString, + prefixChars + )); + } + + // strings starting with two prefix characters are long options + optionStrings.push(optionString); + if (optionString.length > 1 && prefixChars.indexOf(optionString[1]) >= 0) { + optionStringsLong.push(optionString); + } + }); + + // infer dest, '--foo-bar' -> 'foo_bar' and '-x' -> 'x' + var dest = options.dest || null; + delete options.dest; + + if (!dest) { + var optionStringDest = optionStringsLong.length ? optionStringsLong[0] : optionStrings[0]; + dest = $$.trimChars(optionStringDest, this.prefixChars); + + if (dest.length === 0) { + throw new Error( + format('dest= is required for options like "%s"', optionStrings.join(', ')) + ); + } + dest = dest.replace(/-/g, '_'); + } + + // return the updated keyword arguments + options.dest = dest; + options.optionStrings = optionStrings; + + return options; +}; + +ActionContainer.prototype._popActionClass = function (options, defaultValue) { + defaultValue = defaultValue || null; + + var action = (options.action || defaultValue); + delete options.action; + + var actionClass = this._registryGet('action', action, action); + return actionClass; +}; + +ActionContainer.prototype._getHandler = function () { + var handlerString = this.conflictHandler; + var handlerFuncName = '_handleConflict' + $$.capitalize(handlerString); + var func = this[handlerFuncName]; + if (typeof func === 'undefined') { + var msg = 'invalid conflict resolution value: ' + handlerString; + throw new Error(msg); + } else { + return func; + } +}; + +ActionContainer.prototype._checkConflict = function (action) { + var optionStringActions = this._optionStringActions; + var conflictOptionals = []; + + // find all options that conflict with this option + // collect pairs, the string, and an existing action that it conflicts with + action.optionStrings.forEach(function (optionString) { + var conflOptional = optionStringActions[optionString]; + if (typeof conflOptional !== 'undefined') { + conflictOptionals.push([ optionString, conflOptional ]); + } + }); + + if (conflictOptionals.length > 0) { + var conflictHandler = this._getHandler(); + conflictHandler.call(this, action, conflictOptionals); + } +}; + +ActionContainer.prototype._handleConflictError = function (action, conflOptionals) { + var conflicts = conflOptionals.map(function (pair) { return pair[0]; }); + conflicts = conflicts.join(', '); + throw argumentErrorHelper( + action, + format('Conflicting option string(s): %s', conflicts) + ); +}; + +ActionContainer.prototype._handleConflictResolve = function (action, conflOptionals) { + // remove all conflicting options + var self = this; + conflOptionals.forEach(function (pair) { + var optionString = pair[0]; + var conflictingAction = pair[1]; + // remove the conflicting option string + var i = conflictingAction.optionStrings.indexOf(optionString); + if (i >= 0) { + conflictingAction.optionStrings.splice(i, 1); + } + delete self._optionStringActions[optionString]; + // if the option now has no option string, remove it from the + // container holding it + if (conflictingAction.optionStrings.length === 0) { + conflictingAction.container._removeAction(conflictingAction); + } + }); +}; diff --git a/scripts/node_modules/argparse/lib/argparse.js b/scripts/node_modules/argparse/lib/argparse.js new file mode 100644 index 000000000..f2a2c51d9 --- /dev/null +++ b/scripts/node_modules/argparse/lib/argparse.js @@ -0,0 +1,14 @@ +'use strict'; + +module.exports.ArgumentParser = require('./argument_parser.js'); +module.exports.Namespace = require('./namespace'); +module.exports.Action = require('./action'); +module.exports.HelpFormatter = require('./help/formatter.js'); +module.exports.Const = require('./const.js'); + +module.exports.ArgumentDefaultsHelpFormatter = + require('./help/added_formatters.js').ArgumentDefaultsHelpFormatter; +module.exports.RawDescriptionHelpFormatter = + require('./help/added_formatters.js').RawDescriptionHelpFormatter; +module.exports.RawTextHelpFormatter = + require('./help/added_formatters.js').RawTextHelpFormatter; diff --git a/scripts/node_modules/argparse/lib/argument/error.js b/scripts/node_modules/argparse/lib/argument/error.js new file mode 100644 index 000000000..c8a02a08b --- /dev/null +++ b/scripts/node_modules/argparse/lib/argument/error.js @@ -0,0 +1,50 @@ +'use strict'; + + +var format = require('util').format; + + +var ERR_CODE = 'ARGError'; + +/*:nodoc:* + * argumentError(argument, message) -> TypeError + * - argument (Object): action with broken argument + * - message (String): error message + * + * Error format helper. An error from creating or using an argument + * (optional or positional). The string value of this exception + * is the message, augmented with information + * about the argument that caused it. + * + * #####Example + * + * var argumentErrorHelper = require('./argument/error'); + * if (conflictOptionals.length > 0) { + * throw argumentErrorHelper( + * action, + * format('Conflicting option string(s): %s', conflictOptionals.join(', ')) + * ); + * } + * + **/ +module.exports = function (argument, message) { + var argumentName = null; + var errMessage; + var err; + + if (argument.getName) { + argumentName = argument.getName(); + } else { + argumentName = '' + argument; + } + + if (!argumentName) { + errMessage = message; + } else { + errMessage = format('argument "%s": %s', argumentName, message); + } + + err = new TypeError(errMessage); + err.code = ERR_CODE; + return err; +}; diff --git a/scripts/node_modules/argparse/lib/argument/exclusive.js b/scripts/node_modules/argparse/lib/argument/exclusive.js new file mode 100644 index 000000000..8287e00d0 --- /dev/null +++ b/scripts/node_modules/argparse/lib/argument/exclusive.js @@ -0,0 +1,54 @@ +/** internal + * class MutuallyExclusiveGroup + * + * Group arguments. + * By default, ArgumentParser groups command-line arguments + * into “positional arguments” and “optional arguments” + * when displaying help messages. When there is a better + * conceptual grouping of arguments than this default one, + * appropriate groups can be created using the addArgumentGroup() method + * + * This class inherited from [[ArgumentContainer]] + **/ +'use strict'; + +var util = require('util'); + +var ArgumentGroup = require('./group'); + +/** + * new MutuallyExclusiveGroup(container, options) + * - container (object): main container + * - options (object): options.required -> true/false + * + * `required` could be an argument itself, but making it a property of + * the options argument is more consistent with the JS adaptation of the Python) + **/ +var MutuallyExclusiveGroup = module.exports = function MutuallyExclusiveGroup(container, options) { + var required; + options = options || {}; + required = options.required || false; + ArgumentGroup.call(this, container); + this.required = required; + +}; +util.inherits(MutuallyExclusiveGroup, ArgumentGroup); + + +MutuallyExclusiveGroup.prototype._addAction = function (action) { + var msg; + if (action.required) { + msg = 'mutually exclusive arguments must be optional'; + throw new Error(msg); + } + action = this._container._addAction(action); + this._groupActions.push(action); + return action; +}; + + +MutuallyExclusiveGroup.prototype._removeAction = function (action) { + this._container._removeAction(action); + this._groupActions.remove(action); +}; + diff --git a/scripts/node_modules/argparse/lib/argument/group.js b/scripts/node_modules/argparse/lib/argument/group.js new file mode 100644 index 000000000..58b271f2f --- /dev/null +++ b/scripts/node_modules/argparse/lib/argument/group.js @@ -0,0 +1,75 @@ +/** internal + * class ArgumentGroup + * + * Group arguments. + * By default, ArgumentParser groups command-line arguments + * into “positional arguments” and “optional arguments” + * when displaying help messages. When there is a better + * conceptual grouping of arguments than this default one, + * appropriate groups can be created using the addArgumentGroup() method + * + * This class inherited from [[ArgumentContainer]] + **/ +'use strict'; + +var util = require('util'); + +var ActionContainer = require('../action_container'); + + +/** + * new ArgumentGroup(container, options) + * - container (object): main container + * - options (object): hash of group options + * + * #### options + * - **prefixChars** group name prefix + * - **argumentDefault** default argument value + * - **title** group title + * - **description** group description + * + **/ +var ArgumentGroup = module.exports = function ArgumentGroup(container, options) { + + options = options || {}; + + // add any missing keyword arguments by checking the container + options.conflictHandler = (options.conflictHandler || container.conflictHandler); + options.prefixChars = (options.prefixChars || container.prefixChars); + options.argumentDefault = (options.argumentDefault || container.argumentDefault); + + ActionContainer.call(this, options); + + // group attributes + this.title = options.title; + this._groupActions = []; + + // share most attributes with the container + this._container = container; + this._registries = container._registries; + this._actions = container._actions; + this._optionStringActions = container._optionStringActions; + this._defaults = container._defaults; + this._hasNegativeNumberOptionals = container._hasNegativeNumberOptionals; + this._mutuallyExclusiveGroups = container._mutuallyExclusiveGroups; +}; +util.inherits(ArgumentGroup, ActionContainer); + + +ArgumentGroup.prototype._addAction = function (action) { + // Parent add action + action = ActionContainer.prototype._addAction.call(this, action); + this._groupActions.push(action); + return action; +}; + + +ArgumentGroup.prototype._removeAction = function (action) { + // Parent remove action + ActionContainer.prototype._removeAction.call(this, action); + var actionIndex = this._groupActions.indexOf(action); + if (actionIndex >= 0) { + this._groupActions.splice(actionIndex, 1); + } +}; + diff --git a/scripts/node_modules/argparse/lib/argument_parser.js b/scripts/node_modules/argparse/lib/argument_parser.js new file mode 100644 index 000000000..bd9a59a45 --- /dev/null +++ b/scripts/node_modules/argparse/lib/argument_parser.js @@ -0,0 +1,1161 @@ +/** + * class ArgumentParser + * + * Object for parsing command line strings into js objects. + * + * Inherited from [[ActionContainer]] + **/ +'use strict'; + +var util = require('util'); +var format = require('util').format; +var Path = require('path'); +var sprintf = require('sprintf-js').sprintf; + +// Constants +var c = require('./const'); + +var $$ = require('./utils'); + +var ActionContainer = require('./action_container'); + +// Errors +var argumentErrorHelper = require('./argument/error'); + +var HelpFormatter = require('./help/formatter'); + +var Namespace = require('./namespace'); + + +/** + * new ArgumentParser(options) + * + * Create a new ArgumentParser object. + * + * ##### Options: + * - `prog` The name of the program (default: Path.basename(process.argv[1])) + * - `usage` A usage message (default: auto-generated from arguments) + * - `description` A description of what the program does + * - `epilog` Text following the argument descriptions + * - `parents` Parsers whose arguments should be copied into this one + * - `formatterClass` HelpFormatter class for printing help messages + * - `prefixChars` Characters that prefix optional arguments + * - `fromfilePrefixChars` Characters that prefix files containing additional arguments + * - `argumentDefault` The default value for all arguments + * - `addHelp` Add a -h/-help option + * - `conflictHandler` Specifies how to handle conflicting argument names + * - `debug` Enable debug mode. Argument errors throw exception in + * debug mode and process.exit in normal. Used for development and + * testing (default: false) + * + * See also [original guide][1] + * + * [1]:http://docs.python.org/dev/library/argparse.html#argumentparser-objects + **/ +function ArgumentParser(options) { + if (!(this instanceof ArgumentParser)) { + return new ArgumentParser(options); + } + var self = this; + options = options || {}; + + options.description = (options.description || null); + options.argumentDefault = (options.argumentDefault || null); + options.prefixChars = (options.prefixChars || '-'); + options.conflictHandler = (options.conflictHandler || 'error'); + ActionContainer.call(this, options); + + options.addHelp = typeof options.addHelp === 'undefined' || !!options.addHelp; + options.parents = options.parents || []; + // default program name + options.prog = (options.prog || Path.basename(process.argv[1])); + this.prog = options.prog; + this.usage = options.usage; + this.epilog = options.epilog; + this.version = options.version; + + this.debug = (options.debug === true); + + this.formatterClass = (options.formatterClass || HelpFormatter); + this.fromfilePrefixChars = options.fromfilePrefixChars || null; + this._positionals = this.addArgumentGroup({ title: 'Positional arguments' }); + this._optionals = this.addArgumentGroup({ title: 'Optional arguments' }); + this._subparsers = null; + + // register types + function FUNCTION_IDENTITY(o) { + return o; + } + this.register('type', 'auto', FUNCTION_IDENTITY); + this.register('type', null, FUNCTION_IDENTITY); + this.register('type', 'int', function (x) { + var result = parseInt(x, 10); + if (isNaN(result)) { + throw new Error(x + ' is not a valid integer.'); + } + return result; + }); + this.register('type', 'float', function (x) { + var result = parseFloat(x); + if (isNaN(result)) { + throw new Error(x + ' is not a valid float.'); + } + return result; + }); + this.register('type', 'string', function (x) { + return '' + x; + }); + + // add help and version arguments if necessary + var defaultPrefix = (this.prefixChars.indexOf('-') > -1) ? '-' : this.prefixChars[0]; + if (options.addHelp) { + this.addArgument( + [ defaultPrefix + 'h', defaultPrefix + defaultPrefix + 'help' ], + { + action: 'help', + defaultValue: c.SUPPRESS, + help: 'Show this help message and exit.' + } + ); + } + if (typeof this.version !== 'undefined') { + this.addArgument( + [ defaultPrefix + 'v', defaultPrefix + defaultPrefix + 'version' ], + { + action: 'version', + version: this.version, + defaultValue: c.SUPPRESS, + help: "Show program's version number and exit." + } + ); + } + + // add parent arguments and defaults + options.parents.forEach(function (parent) { + self._addContainerActions(parent); + if (typeof parent._defaults !== 'undefined') { + for (var defaultKey in parent._defaults) { + if (parent._defaults.hasOwnProperty(defaultKey)) { + self._defaults[defaultKey] = parent._defaults[defaultKey]; + } + } + } + }); +} + +util.inherits(ArgumentParser, ActionContainer); + +/** + * ArgumentParser#addSubparsers(options) -> [[ActionSubparsers]] + * - options (object): hash of options see [[ActionSubparsers.new]] + * + * See also [subcommands][1] + * + * [1]:http://docs.python.org/dev/library/argparse.html#sub-commands + **/ +ArgumentParser.prototype.addSubparsers = function (options) { + if (this._subparsers) { + this.error('Cannot have multiple subparser arguments.'); + } + + options = options || {}; + options.debug = (this.debug === true); + options.optionStrings = []; + options.parserClass = (options.parserClass || ArgumentParser); + + + if (!!options.title || !!options.description) { + + this._subparsers = this.addArgumentGroup({ + title: (options.title || 'subcommands'), + description: options.description + }); + delete options.title; + delete options.description; + + } else { + this._subparsers = this._positionals; + } + + // prog defaults to the usage message of this parser, skipping + // optional arguments and with no "usage:" prefix + if (!options.prog) { + var formatter = this._getFormatter(); + var positionals = this._getPositionalActions(); + var groups = this._mutuallyExclusiveGroups; + formatter.addUsage(this.usage, positionals, groups, ''); + options.prog = formatter.formatHelp().trim(); + } + + // create the parsers action and add it to the positionals list + var ParsersClass = this._popActionClass(options, 'parsers'); + var action = new ParsersClass(options); + this._subparsers._addAction(action); + + // return the created parsers action + return action; +}; + +ArgumentParser.prototype._addAction = function (action) { + if (action.isOptional()) { + this._optionals._addAction(action); + } else { + this._positionals._addAction(action); + } + return action; +}; + +ArgumentParser.prototype._getOptionalActions = function () { + return this._actions.filter(function (action) { + return action.isOptional(); + }); +}; + +ArgumentParser.prototype._getPositionalActions = function () { + return this._actions.filter(function (action) { + return action.isPositional(); + }); +}; + + +/** + * ArgumentParser#parseArgs(args, namespace) -> Namespace|Object + * - args (array): input elements + * - namespace (Namespace|Object): result object + * + * Parsed args and throws error if some arguments are not recognized + * + * See also [original guide][1] + * + * [1]:http://docs.python.org/dev/library/argparse.html#the-parse-args-method + **/ +ArgumentParser.prototype.parseArgs = function (args, namespace) { + var argv; + var result = this.parseKnownArgs(args, namespace); + + args = result[0]; + argv = result[1]; + if (argv && argv.length > 0) { + this.error( + format('Unrecognized arguments: %s.', argv.join(' ')) + ); + } + return args; +}; + +/** + * ArgumentParser#parseKnownArgs(args, namespace) -> array + * - args (array): input options + * - namespace (Namespace|Object): result object + * + * Parse known arguments and return tuple of result object + * and unknown args + * + * See also [original guide][1] + * + * [1]:http://docs.python.org/dev/library/argparse.html#partial-parsing + **/ +ArgumentParser.prototype.parseKnownArgs = function (args, namespace) { + var self = this; + + // args default to the system args + args = args || process.argv.slice(2); + + // default Namespace built from parser defaults + namespace = namespace || new Namespace(); + + self._actions.forEach(function (action) { + if (action.dest !== c.SUPPRESS) { + if (!$$.has(namespace, action.dest)) { + if (action.defaultValue !== c.SUPPRESS) { + var defaultValue = action.defaultValue; + if (typeof action.defaultValue === 'string') { + defaultValue = self._getValue(action, defaultValue); + } + namespace[action.dest] = defaultValue; + } + } + } + }); + + Object.keys(self._defaults).forEach(function (dest) { + namespace[dest] = self._defaults[dest]; + }); + + // parse the arguments and exit if there are any errors + try { + var res = this._parseKnownArgs(args, namespace); + + namespace = res[0]; + args = res[1]; + if ($$.has(namespace, c._UNRECOGNIZED_ARGS_ATTR)) { + args = $$.arrayUnion(args, namespace[c._UNRECOGNIZED_ARGS_ATTR]); + delete namespace[c._UNRECOGNIZED_ARGS_ATTR]; + } + return [ namespace, args ]; + } catch (e) { + this.error(e); + } +}; + +ArgumentParser.prototype._parseKnownArgs = function (argStrings, namespace) { + var self = this; + + var extras = []; + + // replace arg strings that are file references + if (this.fromfilePrefixChars !== null) { + argStrings = this._readArgsFromFiles(argStrings); + } + // map all mutually exclusive arguments to the other arguments + // they can't occur with + // Python has 'conflicts = action_conflicts.setdefault(mutex_action, [])' + // though I can't conceive of a way in which an action could be a member + // of two different mutually exclusive groups. + + function actionHash(action) { + // some sort of hashable key for this action + // action itself cannot be a key in actionConflicts + // I think getName() (join of optionStrings) is unique enough + return action.getName(); + } + + var conflicts, key; + var actionConflicts = {}; + + this._mutuallyExclusiveGroups.forEach(function (mutexGroup) { + mutexGroup._groupActions.forEach(function (mutexAction, i, groupActions) { + key = actionHash(mutexAction); + if (!$$.has(actionConflicts, key)) { + actionConflicts[key] = []; + } + conflicts = actionConflicts[key]; + conflicts.push.apply(conflicts, groupActions.slice(0, i)); + conflicts.push.apply(conflicts, groupActions.slice(i + 1)); + }); + }); + + // find all option indices, and determine the arg_string_pattern + // which has an 'O' if there is an option at an index, + // an 'A' if there is an argument, or a '-' if there is a '--' + var optionStringIndices = {}; + + var argStringPatternParts = []; + + argStrings.forEach(function (argString, argStringIndex) { + if (argString === '--') { + argStringPatternParts.push('-'); + while (argStringIndex < argStrings.length) { + argStringPatternParts.push('A'); + argStringIndex++; + } + } else { + // otherwise, add the arg to the arg strings + // and note the index if it was an option + var pattern; + var optionTuple = self._parseOptional(argString); + if (!optionTuple) { + pattern = 'A'; + } else { + optionStringIndices[argStringIndex] = optionTuple; + pattern = 'O'; + } + argStringPatternParts.push(pattern); + } + }); + var argStringsPattern = argStringPatternParts.join(''); + + var seenActions = []; + var seenNonDefaultActions = []; + + + function takeAction(action, argumentStrings, optionString) { + seenActions.push(action); + var argumentValues = self._getValues(action, argumentStrings); + + // error if this argument is not allowed with other previously + // seen arguments, assuming that actions that use the default + // value don't really count as "present" + if (argumentValues !== action.defaultValue) { + seenNonDefaultActions.push(action); + if (actionConflicts[actionHash(action)]) { + actionConflicts[actionHash(action)].forEach(function (actionConflict) { + if (seenNonDefaultActions.indexOf(actionConflict) >= 0) { + throw argumentErrorHelper( + action, + format('Not allowed with argument "%s".', actionConflict.getName()) + ); + } + }); + } + } + + if (argumentValues !== c.SUPPRESS) { + action.call(self, namespace, argumentValues, optionString); + } + } + + function consumeOptional(startIndex) { + // get the optional identified at this index + var optionTuple = optionStringIndices[startIndex]; + var action = optionTuple[0]; + var optionString = optionTuple[1]; + var explicitArg = optionTuple[2]; + + // identify additional optionals in the same arg string + // (e.g. -xyz is the same as -x -y -z if no args are required) + var actionTuples = []; + + var args, argCount, start, stop; + + for (;;) { + if (!action) { + extras.push(argStrings[startIndex]); + return startIndex + 1; + } + if (explicitArg) { + argCount = self._matchArgument(action, 'A'); + + // if the action is a single-dash option and takes no + // arguments, try to parse more single-dash options out + // of the tail of the option string + var chars = self.prefixChars; + if (argCount === 0 && chars.indexOf(optionString[1]) < 0) { + actionTuples.push([ action, [], optionString ]); + optionString = optionString[0] + explicitArg[0]; + var newExplicitArg = explicitArg.slice(1) || null; + var optionalsMap = self._optionStringActions; + + if (Object.keys(optionalsMap).indexOf(optionString) >= 0) { + action = optionalsMap[optionString]; + explicitArg = newExplicitArg; + } else { + throw argumentErrorHelper(action, sprintf('ignored explicit argument %r', explicitArg)); + } + } else if (argCount === 1) { + // if the action expect exactly one argument, we've + // successfully matched the option; exit the loop + stop = startIndex + 1; + args = [ explicitArg ]; + actionTuples.push([ action, args, optionString ]); + break; + } else { + // error if a double-dash option did not use the + // explicit argument + throw argumentErrorHelper(action, sprintf('ignored explicit argument %r', explicitArg)); + } + } else { + // if there is no explicit argument, try to match the + // optional's string arguments with the following strings + // if successful, exit the loop + + start = startIndex + 1; + var selectedPatterns = argStringsPattern.substr(start); + + argCount = self._matchArgument(action, selectedPatterns); + stop = start + argCount; + + + args = argStrings.slice(start, stop); + + actionTuples.push([ action, args, optionString ]); + break; + } + + } + + // add the Optional to the list and return the index at which + // the Optional's string args stopped + if (actionTuples.length < 1) { + throw new Error('length should be > 0'); + } + for (var i = 0; i < actionTuples.length; i++) { + takeAction.apply(self, actionTuples[i]); + } + return stop; + } + + // the list of Positionals left to be parsed; this is modified + // by consume_positionals() + var positionals = self._getPositionalActions(); + + function consumePositionals(startIndex) { + // match as many Positionals as possible + var selectedPattern = argStringsPattern.substr(startIndex); + var argCounts = self._matchArgumentsPartial(positionals, selectedPattern); + + // slice off the appropriate arg strings for each Positional + // and add the Positional and its args to the list + for (var i = 0; i < positionals.length; i++) { + var action = positionals[i]; + var argCount = argCounts[i]; + if (typeof argCount === 'undefined') { + continue; + } + var args = argStrings.slice(startIndex, startIndex + argCount); + + startIndex += argCount; + takeAction(action, args); + } + + // slice off the Positionals that we just parsed and return the + // index at which the Positionals' string args stopped + positionals = positionals.slice(argCounts.length); + return startIndex; + } + + // consume Positionals and Optionals alternately, until we have + // passed the last option string + var startIndex = 0; + var position; + + var maxOptionStringIndex = -1; + + Object.keys(optionStringIndices).forEach(function (position) { + maxOptionStringIndex = Math.max(maxOptionStringIndex, parseInt(position, 10)); + }); + + var positionalsEndIndex, nextOptionStringIndex; + + while (startIndex <= maxOptionStringIndex) { + // consume any Positionals preceding the next option + nextOptionStringIndex = null; + for (position in optionStringIndices) { + if (!optionStringIndices.hasOwnProperty(position)) { continue; } + + position = parseInt(position, 10); + if (position >= startIndex) { + if (nextOptionStringIndex !== null) { + nextOptionStringIndex = Math.min(nextOptionStringIndex, position); + } else { + nextOptionStringIndex = position; + } + } + } + + if (startIndex !== nextOptionStringIndex) { + positionalsEndIndex = consumePositionals(startIndex); + // only try to parse the next optional if we didn't consume + // the option string during the positionals parsing + if (positionalsEndIndex > startIndex) { + startIndex = positionalsEndIndex; + continue; + } else { + startIndex = positionalsEndIndex; + } + } + + // if we consumed all the positionals we could and we're not + // at the index of an option string, there were extra arguments + if (!optionStringIndices[startIndex]) { + var strings = argStrings.slice(startIndex, nextOptionStringIndex); + extras = extras.concat(strings); + startIndex = nextOptionStringIndex; + } + // consume the next optional and any arguments for it + startIndex = consumeOptional(startIndex); + } + + // consume any positionals following the last Optional + var stopIndex = consumePositionals(startIndex); + + // if we didn't consume all the argument strings, there were extras + extras = extras.concat(argStrings.slice(stopIndex)); + + // if we didn't use all the Positional objects, there were too few + // arg strings supplied. + if (positionals.length > 0) { + self.error('too few arguments'); + } + + // make sure all required actions were present + self._actions.forEach(function (action) { + if (action.required) { + if (seenActions.indexOf(action) < 0) { + self.error(format('Argument "%s" is required', action.getName())); + } + } + }); + + // make sure all required groups have one option present + var actionUsed = false; + self._mutuallyExclusiveGroups.forEach(function (group) { + if (group.required) { + actionUsed = group._groupActions.some(function (action) { + return seenNonDefaultActions.indexOf(action) !== -1; + }); + + // if no actions were used, report the error + if (!actionUsed) { + var names = []; + group._groupActions.forEach(function (action) { + if (action.help !== c.SUPPRESS) { + names.push(action.getName()); + } + }); + names = names.join(' '); + var msg = 'one of the arguments ' + names + ' is required'; + self.error(msg); + } + } + }); + + // return the updated namespace and the extra arguments + return [ namespace, extras ]; +}; + +ArgumentParser.prototype._readArgsFromFiles = function (argStrings) { + // expand arguments referencing files + var self = this; + var fs = require('fs'); + var newArgStrings = []; + argStrings.forEach(function (argString) { + if (self.fromfilePrefixChars.indexOf(argString[0]) < 0) { + // for regular arguments, just add them back into the list + newArgStrings.push(argString); + } else { + // replace arguments referencing files with the file content + try { + var argstrs = []; + var filename = argString.slice(1); + var content = fs.readFileSync(filename, 'utf8'); + content = content.trim().split('\n'); + content.forEach(function (argLine) { + self.convertArgLineToArgs(argLine).forEach(function (arg) { + argstrs.push(arg); + }); + argstrs = self._readArgsFromFiles(argstrs); + }); + newArgStrings.push.apply(newArgStrings, argstrs); + } catch (error) { + return self.error(error.message); + } + } + }); + return newArgStrings; +}; + +ArgumentParser.prototype.convertArgLineToArgs = function (argLine) { + return [ argLine ]; +}; + +ArgumentParser.prototype._matchArgument = function (action, regexpArgStrings) { + + // match the pattern for this action to the arg strings + var regexpNargs = new RegExp('^' + this._getNargsPattern(action)); + var matches = regexpArgStrings.match(regexpNargs); + var message; + + // throw an exception if we weren't able to find a match + if (!matches) { + switch (action.nargs) { + /*eslint-disable no-undefined*/ + case undefined: + case null: + message = 'Expected one argument.'; + break; + case c.OPTIONAL: + message = 'Expected at most one argument.'; + break; + case c.ONE_OR_MORE: + message = 'Expected at least one argument.'; + break; + default: + message = 'Expected %s argument(s)'; + } + + throw argumentErrorHelper( + action, + format(message, action.nargs) + ); + } + // return the number of arguments matched + return matches[1].length; +}; + +ArgumentParser.prototype._matchArgumentsPartial = function (actions, regexpArgStrings) { + // progressively shorten the actions list by slicing off the + // final actions until we find a match + var self = this; + var result = []; + var actionSlice, pattern, matches; + var i, j; + + function getLength(string) { + return string.length; + } + + for (i = actions.length; i > 0; i--) { + pattern = ''; + actionSlice = actions.slice(0, i); + for (j = 0; j < actionSlice.length; j++) { + pattern += self._getNargsPattern(actionSlice[j]); + } + + pattern = new RegExp('^' + pattern); + matches = regexpArgStrings.match(pattern); + + if (matches && matches.length > 0) { + // need only groups + matches = matches.splice(1); + result = result.concat(matches.map(getLength)); + break; + } + } + + // return the list of arg string counts + return result; +}; + +ArgumentParser.prototype._parseOptional = function (argString) { + var action, optionString, argExplicit, optionTuples; + + // if it's an empty string, it was meant to be a positional + if (!argString) { + return null; + } + + // if it doesn't start with a prefix, it was meant to be positional + if (this.prefixChars.indexOf(argString[0]) < 0) { + return null; + } + + // if the option string is present in the parser, return the action + if (this._optionStringActions[argString]) { + return [ this._optionStringActions[argString], argString, null ]; + } + + // if it's just a single character, it was meant to be positional + if (argString.length === 1) { + return null; + } + + // if the option string before the "=" is present, return the action + if (argString.indexOf('=') >= 0) { + optionString = argString.split('=', 1)[0]; + argExplicit = argString.slice(optionString.length + 1); + + if (this._optionStringActions[optionString]) { + action = this._optionStringActions[optionString]; + return [ action, optionString, argExplicit ]; + } + } + + // search through all possible prefixes of the option string + // and all actions in the parser for possible interpretations + optionTuples = this._getOptionTuples(argString); + + // if multiple actions match, the option string was ambiguous + if (optionTuples.length > 1) { + var optionStrings = optionTuples.map(function (optionTuple) { + return optionTuple[1]; + }); + this.error(format( + 'Ambiguous option: "%s" could match %s.', + argString, optionStrings.join(', ') + )); + // if exactly one action matched, this segmentation is good, + // so return the parsed action + } else if (optionTuples.length === 1) { + return optionTuples[0]; + } + + // if it was not found as an option, but it looks like a negative + // number, it was meant to be positional + // unless there are negative-number-like options + if (argString.match(this._regexpNegativeNumber)) { + if (!this._hasNegativeNumberOptionals.some(Boolean)) { + return null; + } + } + // if it contains a space, it was meant to be a positional + if (argString.search(' ') >= 0) { + return null; + } + + // it was meant to be an optional but there is no such option + // in this parser (though it might be a valid option in a subparser) + return [ null, argString, null ]; +}; + +ArgumentParser.prototype._getOptionTuples = function (optionString) { + var result = []; + var chars = this.prefixChars; + var optionPrefix; + var argExplicit; + var action; + var actionOptionString; + + // option strings starting with two prefix characters are only split at + // the '=' + if (chars.indexOf(optionString[0]) >= 0 && chars.indexOf(optionString[1]) >= 0) { + if (optionString.indexOf('=') >= 0) { + var optionStringSplit = optionString.split('=', 1); + + optionPrefix = optionStringSplit[0]; + argExplicit = optionStringSplit[1]; + } else { + optionPrefix = optionString; + argExplicit = null; + } + + for (actionOptionString in this._optionStringActions) { + if (actionOptionString.substr(0, optionPrefix.length) === optionPrefix) { + action = this._optionStringActions[actionOptionString]; + result.push([ action, actionOptionString, argExplicit ]); + } + } + + // single character options can be concatenated with their arguments + // but multiple character options always have to have their argument + // separate + } else if (chars.indexOf(optionString[0]) >= 0 && chars.indexOf(optionString[1]) < 0) { + optionPrefix = optionString; + argExplicit = null; + var optionPrefixShort = optionString.substr(0, 2); + var argExplicitShort = optionString.substr(2); + + for (actionOptionString in this._optionStringActions) { + if (!$$.has(this._optionStringActions, actionOptionString)) continue; + + action = this._optionStringActions[actionOptionString]; + if (actionOptionString === optionPrefixShort) { + result.push([ action, actionOptionString, argExplicitShort ]); + } else if (actionOptionString.substr(0, optionPrefix.length) === optionPrefix) { + result.push([ action, actionOptionString, argExplicit ]); + } + } + + // shouldn't ever get here + } else { + throw new Error(format('Unexpected option string: %s.', optionString)); + } + // return the collected option tuples + return result; +}; + +ArgumentParser.prototype._getNargsPattern = function (action) { + // in all examples below, we have to allow for '--' args + // which are represented as '-' in the pattern + var regexpNargs; + + switch (action.nargs) { + // the default (null) is assumed to be a single argument + case undefined: + case null: + regexpNargs = '(-*A-*)'; + break; + // allow zero or more arguments + case c.OPTIONAL: + regexpNargs = '(-*A?-*)'; + break; + // allow zero or more arguments + case c.ZERO_OR_MORE: + regexpNargs = '(-*[A-]*)'; + break; + // allow one or more arguments + case c.ONE_OR_MORE: + regexpNargs = '(-*A[A-]*)'; + break; + // allow any number of options or arguments + case c.REMAINDER: + regexpNargs = '([-AO]*)'; + break; + // allow one argument followed by any number of options or arguments + case c.PARSER: + regexpNargs = '(-*A[-AO]*)'; + break; + // all others should be integers + default: + regexpNargs = '(-*' + $$.repeat('-*A', action.nargs) + '-*)'; + } + + // if this is an optional action, -- is not allowed + if (action.isOptional()) { + regexpNargs = regexpNargs.replace(/-\*/g, ''); + regexpNargs = regexpNargs.replace(/-/g, ''); + } + + // return the pattern + return regexpNargs; +}; + +// +// Value conversion methods +// + +ArgumentParser.prototype._getValues = function (action, argStrings) { + var self = this; + + // for everything but PARSER args, strip out '--' + if (action.nargs !== c.PARSER && action.nargs !== c.REMAINDER) { + argStrings = argStrings.filter(function (arrayElement) { + return arrayElement !== '--'; + }); + } + + var value, argString; + + // optional argument produces a default when not present + if (argStrings.length === 0 && action.nargs === c.OPTIONAL) { + + value = (action.isOptional()) ? action.constant : action.defaultValue; + + if (typeof (value) === 'string') { + value = this._getValue(action, value); + this._checkValue(action, value); + } + + // when nargs='*' on a positional, if there were no command-line + // args, use the default if it is anything other than None + } else if (argStrings.length === 0 && action.nargs === c.ZERO_OR_MORE && + action.optionStrings.length === 0) { + + value = (action.defaultValue || argStrings); + this._checkValue(action, value); + + // single argument or optional argument produces a single value + } else if (argStrings.length === 1 && + (!action.nargs || action.nargs === c.OPTIONAL)) { + + argString = argStrings[0]; + value = this._getValue(action, argString); + this._checkValue(action, value); + + // REMAINDER arguments convert all values, checking none + } else if (action.nargs === c.REMAINDER) { + value = argStrings.map(function (v) { + return self._getValue(action, v); + }); + + // PARSER arguments convert all values, but check only the first + } else if (action.nargs === c.PARSER) { + value = argStrings.map(function (v) { + return self._getValue(action, v); + }); + this._checkValue(action, value[0]); + + // all other types of nargs produce a list + } else { + value = argStrings.map(function (v) { + return self._getValue(action, v); + }); + value.forEach(function (v) { + self._checkValue(action, v); + }); + } + + // return the converted value + return value; +}; + +ArgumentParser.prototype._getValue = function (action, argString) { + var result; + + var typeFunction = this._registryGet('type', action.type, action.type); + if (typeof typeFunction !== 'function') { + var message = format('%s is not callable', typeFunction); + throw argumentErrorHelper(action, message); + } + + // convert the value to the appropriate type + try { + result = typeFunction(argString); + + // ArgumentTypeErrors indicate errors + // If action.type is not a registered string, it is a function + // Try to deduce its name for inclusion in the error message + // Failing that, include the error message it raised. + } catch (e) { + var name = null; + if (typeof action.type === 'string') { + name = action.type; + } else { + name = action.type.name || action.type.displayName || ''; + } + var msg = format('Invalid %s value: %s', name, argString); + if (name === '') { msg += '\n' + e.message; } + throw argumentErrorHelper(action, msg); + } + // return the converted value + return result; +}; + +ArgumentParser.prototype._checkValue = function (action, value) { + // converted value must be one of the choices (if specified) + var choices = action.choices; + if (choices) { + // choise for argument can by array or string + if ((typeof choices === 'string' || Array.isArray(choices)) && + choices.indexOf(value) !== -1) { + return; + } + // choise for subparsers can by only hash + if (typeof choices === 'object' && !Array.isArray(choices) && choices[value]) { + return; + } + + if (typeof choices === 'string') { + choices = choices.split('').join(', '); + } else if (Array.isArray(choices)) { + choices = choices.join(', '); + } else { + choices = Object.keys(choices).join(', '); + } + var message = format('Invalid choice: %s (choose from [%s])', value, choices); + throw argumentErrorHelper(action, message); + } +}; + +// +// Help formatting methods +// + +/** + * ArgumentParser#formatUsage -> string + * + * Return usage string + * + * See also [original guide][1] + * + * [1]:http://docs.python.org/dev/library/argparse.html#printing-help + **/ +ArgumentParser.prototype.formatUsage = function () { + var formatter = this._getFormatter(); + formatter.addUsage(this.usage, this._actions, this._mutuallyExclusiveGroups); + return formatter.formatHelp(); +}; + +/** + * ArgumentParser#formatHelp -> string + * + * Return help + * + * See also [original guide][1] + * + * [1]:http://docs.python.org/dev/library/argparse.html#printing-help + **/ +ArgumentParser.prototype.formatHelp = function () { + var formatter = this._getFormatter(); + + // usage + formatter.addUsage(this.usage, this._actions, this._mutuallyExclusiveGroups); + + // description + formatter.addText(this.description); + + // positionals, optionals and user-defined groups + this._actionGroups.forEach(function (actionGroup) { + formatter.startSection(actionGroup.title); + formatter.addText(actionGroup.description); + formatter.addArguments(actionGroup._groupActions); + formatter.endSection(); + }); + + // epilog + formatter.addText(this.epilog); + + // determine help from format above + return formatter.formatHelp(); +}; + +ArgumentParser.prototype._getFormatter = function () { + var FormatterClass = this.formatterClass; + var formatter = new FormatterClass({ prog: this.prog }); + return formatter; +}; + +// +// Print functions +// + +/** + * ArgumentParser#printUsage() -> Void + * + * Print usage + * + * See also [original guide][1] + * + * [1]:http://docs.python.org/dev/library/argparse.html#printing-help + **/ +ArgumentParser.prototype.printUsage = function () { + this._printMessage(this.formatUsage()); +}; + +/** + * ArgumentParser#printHelp() -> Void + * + * Print help + * + * See also [original guide][1] + * + * [1]:http://docs.python.org/dev/library/argparse.html#printing-help + **/ +ArgumentParser.prototype.printHelp = function () { + this._printMessage(this.formatHelp()); +}; + +ArgumentParser.prototype._printMessage = function (message, stream) { + if (!stream) { + stream = process.stdout; + } + if (message) { + stream.write('' + message); + } +}; + +// +// Exit functions +// + +/** + * ArgumentParser#exit(status=0, message) -> Void + * - status (int): exit status + * - message (string): message + * + * Print message in stderr/stdout and exit program + **/ +ArgumentParser.prototype.exit = function (status, message) { + if (message) { + if (status === 0) { + this._printMessage(message); + } else { + this._printMessage(message, process.stderr); + } + } + + process.exit(status); +}; + +/** + * ArgumentParser#error(message) -> Void + * - err (Error|string): message + * + * Error method Prints a usage message incorporating the message to stderr and + * exits. If you override this in a subclass, + * it should not return -- it should + * either exit or throw an exception. + * + **/ +ArgumentParser.prototype.error = function (err) { + var message; + if (err instanceof Error) { + if (this.debug === true) { + throw err; + } + message = err.message; + } else { + message = err; + } + var msg = format('%s: error: %s', this.prog, message) + c.EOL; + + if (this.debug === true) { + throw new Error(msg); + } + + this.printUsage(process.stderr); + + return this.exit(2, msg); +}; + +module.exports = ArgumentParser; diff --git a/scripts/node_modules/argparse/lib/const.js b/scripts/node_modules/argparse/lib/const.js new file mode 100644 index 000000000..b1fd4ced4 --- /dev/null +++ b/scripts/node_modules/argparse/lib/const.js @@ -0,0 +1,21 @@ +// +// Constants +// + +'use strict'; + +module.exports.EOL = '\n'; + +module.exports.SUPPRESS = '==SUPPRESS=='; + +module.exports.OPTIONAL = '?'; + +module.exports.ZERO_OR_MORE = '*'; + +module.exports.ONE_OR_MORE = '+'; + +module.exports.PARSER = 'A...'; + +module.exports.REMAINDER = '...'; + +module.exports._UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args'; diff --git a/scripts/node_modules/argparse/lib/help/added_formatters.js b/scripts/node_modules/argparse/lib/help/added_formatters.js new file mode 100644 index 000000000..f8e42998e --- /dev/null +++ b/scripts/node_modules/argparse/lib/help/added_formatters.js @@ -0,0 +1,87 @@ +'use strict'; + +var util = require('util'); + +// Constants +var c = require('../const'); + +var $$ = require('../utils'); +var HelpFormatter = require('./formatter.js'); + +/** + * new RawDescriptionHelpFormatter(options) + * new ArgumentParser({formatterClass: argparse.RawDescriptionHelpFormatter, ...}) + * + * Help message formatter which adds default values to argument help. + * + * Only the name of this class is considered a public API. All the methods + * provided by the class are considered an implementation detail. + **/ + +function ArgumentDefaultsHelpFormatter(options) { + HelpFormatter.call(this, options); +} + +util.inherits(ArgumentDefaultsHelpFormatter, HelpFormatter); + +ArgumentDefaultsHelpFormatter.prototype._getHelpString = function (action) { + var help = action.help; + if (action.help.indexOf('%(defaultValue)s') === -1) { + if (action.defaultValue !== c.SUPPRESS) { + var defaulting_nargs = [ c.OPTIONAL, c.ZERO_OR_MORE ]; + if (action.isOptional() || (defaulting_nargs.indexOf(action.nargs) >= 0)) { + help += ' (default: %(defaultValue)s)'; + } + } + } + return help; +}; + +module.exports.ArgumentDefaultsHelpFormatter = ArgumentDefaultsHelpFormatter; + +/** + * new RawDescriptionHelpFormatter(options) + * new ArgumentParser({formatterClass: argparse.RawDescriptionHelpFormatter, ...}) + * + * Help message formatter which retains any formatting in descriptions. + * + * Only the name of this class is considered a public API. All the methods + * provided by the class are considered an implementation detail. + **/ + +function RawDescriptionHelpFormatter(options) { + HelpFormatter.call(this, options); +} + +util.inherits(RawDescriptionHelpFormatter, HelpFormatter); + +RawDescriptionHelpFormatter.prototype._fillText = function (text, width, indent) { + var lines = text.split('\n'); + lines = lines.map(function (line) { + return $$.trimEnd(indent + line); + }); + return lines.join('\n'); +}; +module.exports.RawDescriptionHelpFormatter = RawDescriptionHelpFormatter; + +/** + * new RawTextHelpFormatter(options) + * new ArgumentParser({formatterClass: argparse.RawTextHelpFormatter, ...}) + * + * Help message formatter which retains formatting of all help text. + * + * Only the name of this class is considered a public API. All the methods + * provided by the class are considered an implementation detail. + **/ + +function RawTextHelpFormatter(options) { + RawDescriptionHelpFormatter.call(this, options); +} + +util.inherits(RawTextHelpFormatter, RawDescriptionHelpFormatter); + +RawTextHelpFormatter.prototype._splitLines = function (text) { + return text.split('\n'); +}; + +module.exports.RawTextHelpFormatter = RawTextHelpFormatter; diff --git a/scripts/node_modules/argparse/lib/help/formatter.js b/scripts/node_modules/argparse/lib/help/formatter.js new file mode 100644 index 000000000..29036c14b --- /dev/null +++ b/scripts/node_modules/argparse/lib/help/formatter.js @@ -0,0 +1,795 @@ +/** + * class HelpFormatter + * + * Formatter for generating usage messages and argument help strings. Only the + * name of this class is considered a public API. All the methods provided by + * the class are considered an implementation detail. + * + * Do not call in your code, use this class only for inherits your own forvatter + * + * ToDo add [additonal formatters][1] + * + * [1]:http://docs.python.org/dev/library/argparse.html#formatter-class + **/ +'use strict'; + +var sprintf = require('sprintf-js').sprintf; + +// Constants +var c = require('../const'); + +var $$ = require('../utils'); + + +/*:nodoc:* internal + * new Support(parent, heding) + * - parent (object): parent section + * - heading (string): header string + * + **/ +function Section(parent, heading) { + this._parent = parent; + this._heading = heading; + this._items = []; +} + +/*:nodoc:* internal + * Section#addItem(callback) -> Void + * - callback (array): tuple with function and args + * + * Add function for single element + **/ +Section.prototype.addItem = function (callback) { + this._items.push(callback); +}; + +/*:nodoc:* internal + * Section#formatHelp(formatter) -> string + * - formatter (HelpFormatter): current formatter + * + * Form help section string + * + **/ +Section.prototype.formatHelp = function (formatter) { + var itemHelp, heading; + + // format the indented section + if (this._parent) { + formatter._indent(); + } + + itemHelp = this._items.map(function (item) { + var obj, func, args; + + obj = formatter; + func = item[0]; + args = item[1]; + return func.apply(obj, args); + }); + itemHelp = formatter._joinParts(itemHelp); + + if (this._parent) { + formatter._dedent(); + } + + // return nothing if the section was empty + if (!itemHelp) { + return ''; + } + + // add the heading if the section was non-empty + heading = ''; + if (this._heading && this._heading !== c.SUPPRESS) { + var currentIndent = formatter.currentIndent; + heading = $$.repeat(' ', currentIndent) + this._heading + ':' + c.EOL; + } + + // join the section-initialize newline, the heading and the help + return formatter._joinParts([ c.EOL, heading, itemHelp, c.EOL ]); +}; + +/** + * new HelpFormatter(options) + * + * #### Options: + * - `prog`: program name + * - `indentIncriment`: indent step, default value 2 + * - `maxHelpPosition`: max help position, default value = 24 + * - `width`: line width + * + **/ +var HelpFormatter = module.exports = function HelpFormatter(options) { + options = options || {}; + + this._prog = options.prog; + + this._maxHelpPosition = options.maxHelpPosition || 24; + this._width = (options.width || ((process.env.COLUMNS || 80) - 2)); + + this._currentIndent = 0; + this._indentIncriment = options.indentIncriment || 2; + this._level = 0; + this._actionMaxLength = 0; + + this._rootSection = new Section(null); + this._currentSection = this._rootSection; + + this._whitespaceMatcher = new RegExp('\\s+', 'g'); + this._longBreakMatcher = new RegExp(c.EOL + c.EOL + c.EOL + '+', 'g'); +}; + +HelpFormatter.prototype._indent = function () { + this._currentIndent += this._indentIncriment; + this._level += 1; +}; + +HelpFormatter.prototype._dedent = function () { + this._currentIndent -= this._indentIncriment; + this._level -= 1; + if (this._currentIndent < 0) { + throw new Error('Indent decreased below 0.'); + } +}; + +HelpFormatter.prototype._addItem = function (func, args) { + this._currentSection.addItem([ func, args ]); +}; + +// +// Message building methods +// + +/** + * HelpFormatter#startSection(heading) -> Void + * - heading (string): header string + * + * Start new help section + * + * See alse [code example][1] + * + * ##### Example + * + * formatter.startSection(actionGroup.title); + * formatter.addText(actionGroup.description); + * formatter.addArguments(actionGroup._groupActions); + * formatter.endSection(); + * + **/ +HelpFormatter.prototype.startSection = function (heading) { + this._indent(); + var section = new Section(this._currentSection, heading); + var func = section.formatHelp.bind(section); + this._addItem(func, [ this ]); + this._currentSection = section; +}; + +/** + * HelpFormatter#endSection -> Void + * + * End help section + * + * ##### Example + * + * formatter.startSection(actionGroup.title); + * formatter.addText(actionGroup.description); + * formatter.addArguments(actionGroup._groupActions); + * formatter.endSection(); + **/ +HelpFormatter.prototype.endSection = function () { + this._currentSection = this._currentSection._parent; + this._dedent(); +}; + +/** + * HelpFormatter#addText(text) -> Void + * - text (string): plain text + * + * Add plain text into current section + * + * ##### Example + * + * formatter.startSection(actionGroup.title); + * formatter.addText(actionGroup.description); + * formatter.addArguments(actionGroup._groupActions); + * formatter.endSection(); + * + **/ +HelpFormatter.prototype.addText = function (text) { + if (text && text !== c.SUPPRESS) { + this._addItem(this._formatText, [ text ]); + } +}; + +/** + * HelpFormatter#addUsage(usage, actions, groups, prefix) -> Void + * - usage (string): usage text + * - actions (array): actions list + * - groups (array): groups list + * - prefix (string): usage prefix + * + * Add usage data into current section + * + * ##### Example + * + * formatter.addUsage(this.usage, this._actions, []); + * return formatter.formatHelp(); + * + **/ +HelpFormatter.prototype.addUsage = function (usage, actions, groups, prefix) { + if (usage !== c.SUPPRESS) { + this._addItem(this._formatUsage, [ usage, actions, groups, prefix ]); + } +}; + +/** + * HelpFormatter#addArgument(action) -> Void + * - action (object): action + * + * Add argument into current section + * + * Single variant of [[HelpFormatter#addArguments]] + **/ +HelpFormatter.prototype.addArgument = function (action) { + if (action.help !== c.SUPPRESS) { + var self = this; + + // find all invocations + var invocations = [ this._formatActionInvocation(action) ]; + var invocationLength = invocations[0].length; + + var actionLength; + + if (action._getSubactions) { + this._indent(); + action._getSubactions().forEach(function (subaction) { + + var invocationNew = self._formatActionInvocation(subaction); + invocations.push(invocationNew); + invocationLength = Math.max(invocationLength, invocationNew.length); + + }); + this._dedent(); + } + + // update the maximum item length + actionLength = invocationLength + this._currentIndent; + this._actionMaxLength = Math.max(this._actionMaxLength, actionLength); + + // add the item to the list + this._addItem(this._formatAction, [ action ]); + } +}; + +/** + * HelpFormatter#addArguments(actions) -> Void + * - actions (array): actions list + * + * Mass add arguments into current section + * + * ##### Example + * + * formatter.startSection(actionGroup.title); + * formatter.addText(actionGroup.description); + * formatter.addArguments(actionGroup._groupActions); + * formatter.endSection(); + * + **/ +HelpFormatter.prototype.addArguments = function (actions) { + var self = this; + actions.forEach(function (action) { + self.addArgument(action); + }); +}; + +// +// Help-formatting methods +// + +/** + * HelpFormatter#formatHelp -> string + * + * Format help + * + * ##### Example + * + * formatter.addText(this.epilog); + * return formatter.formatHelp(); + * + **/ +HelpFormatter.prototype.formatHelp = function () { + var help = this._rootSection.formatHelp(this); + if (help) { + help = help.replace(this._longBreakMatcher, c.EOL + c.EOL); + help = $$.trimChars(help, c.EOL) + c.EOL; + } + return help; +}; + +HelpFormatter.prototype._joinParts = function (partStrings) { + return partStrings.filter(function (part) { + return (part && part !== c.SUPPRESS); + }).join(''); +}; + +HelpFormatter.prototype._formatUsage = function (usage, actions, groups, prefix) { + if (!prefix && typeof prefix !== 'string') { + prefix = 'usage: '; + } + + actions = actions || []; + groups = groups || []; + + + // if usage is specified, use that + if (usage) { + usage = sprintf(usage, { prog: this._prog }); + + // if no optionals or positionals are available, usage is just prog + } else if (!usage && actions.length === 0) { + usage = this._prog; + + // if optionals and positionals are available, calculate usage + } else if (!usage) { + var prog = this._prog; + var optionals = []; + var positionals = []; + var actionUsage; + var textWidth; + + // split optionals from positionals + actions.forEach(function (action) { + if (action.isOptional()) { + optionals.push(action); + } else { + positionals.push(action); + } + }); + + // build full usage string + actionUsage = this._formatActionsUsage([].concat(optionals, positionals), groups); + usage = [ prog, actionUsage ].join(' '); + + // wrap the usage parts if it's too long + textWidth = this._width - this._currentIndent; + if ((prefix.length + usage.length) > textWidth) { + + // break usage into wrappable parts + var regexpPart = new RegExp('\\(.*?\\)+|\\[.*?\\]+|\\S+', 'g'); + var optionalUsage = this._formatActionsUsage(optionals, groups); + var positionalUsage = this._formatActionsUsage(positionals, groups); + + + var optionalParts = optionalUsage.match(regexpPart); + var positionalParts = positionalUsage.match(regexpPart) || []; + + if (optionalParts.join(' ') !== optionalUsage) { + throw new Error('assert "optionalParts.join(\' \') === optionalUsage"'); + } + if (positionalParts.join(' ') !== positionalUsage) { + throw new Error('assert "positionalParts.join(\' \') === positionalUsage"'); + } + + // helper for wrapping lines + /*eslint-disable func-style*/ // node 0.10 compat + var _getLines = function (parts, indent, prefix) { + var lines = []; + var line = []; + + var lineLength = prefix ? prefix.length - 1 : indent.length - 1; + + parts.forEach(function (part) { + if (lineLength + 1 + part.length > textWidth) { + lines.push(indent + line.join(' ')); + line = []; + lineLength = indent.length - 1; + } + line.push(part); + lineLength += part.length + 1; + }); + + if (line) { + lines.push(indent + line.join(' ')); + } + if (prefix) { + lines[0] = lines[0].substr(indent.length); + } + return lines; + }; + + var lines, indent, parts; + // if prog is short, follow it with optionals or positionals + if (prefix.length + prog.length <= 0.75 * textWidth) { + indent = $$.repeat(' ', (prefix.length + prog.length + 1)); + if (optionalParts) { + lines = [].concat( + _getLines([ prog ].concat(optionalParts), indent, prefix), + _getLines(positionalParts, indent) + ); + } else if (positionalParts) { + lines = _getLines([ prog ].concat(positionalParts), indent, prefix); + } else { + lines = [ prog ]; + } + + // if prog is long, put it on its own line + } else { + indent = $$.repeat(' ', prefix.length); + parts = optionalParts.concat(positionalParts); + lines = _getLines(parts, indent); + if (lines.length > 1) { + lines = [].concat( + _getLines(optionalParts, indent), + _getLines(positionalParts, indent) + ); + } + lines = [ prog ].concat(lines); + } + // join lines into usage + usage = lines.join(c.EOL); + } + } + + // prefix with 'usage:' + return prefix + usage + c.EOL + c.EOL; +}; + +HelpFormatter.prototype._formatActionsUsage = function (actions, groups) { + // find group indices and identify actions in groups + var groupActions = []; + var inserts = []; + var self = this; + + groups.forEach(function (group) { + var end; + var i; + + var start = actions.indexOf(group._groupActions[0]); + if (start >= 0) { + end = start + group._groupActions.length; + + //if (actions.slice(start, end) === group._groupActions) { + if ($$.arrayEqual(actions.slice(start, end), group._groupActions)) { + group._groupActions.forEach(function (action) { + groupActions.push(action); + }); + + if (!group.required) { + if (inserts[start]) { + inserts[start] += ' ['; + } else { + inserts[start] = '['; + } + inserts[end] = ']'; + } else { + if (inserts[start]) { + inserts[start] += ' ('; + } else { + inserts[start] = '('; + } + inserts[end] = ')'; + } + for (i = start + 1; i < end; i += 1) { + inserts[i] = '|'; + } + } + } + }); + + // collect all actions format strings + var parts = []; + + actions.forEach(function (action, actionIndex) { + var part; + var optionString; + var argsDefault; + var argsString; + + // suppressed arguments are marked with None + // remove | separators for suppressed arguments + if (action.help === c.SUPPRESS) { + parts.push(null); + if (inserts[actionIndex] === '|') { + inserts.splice(actionIndex, actionIndex); + } else if (inserts[actionIndex + 1] === '|') { + inserts.splice(actionIndex + 1, actionIndex + 1); + } + + // produce all arg strings + } else if (!action.isOptional()) { + part = self._formatArgs(action, action.dest); + + // if it's in a group, strip the outer [] + if (groupActions.indexOf(action) >= 0) { + if (part[0] === '[' && part[part.length - 1] === ']') { + part = part.slice(1, -1); + } + } + // add the action string to the list + parts.push(part); + + // produce the first way to invoke the option in brackets + } else { + optionString = action.optionStrings[0]; + + // if the Optional doesn't take a value, format is: -s or --long + if (action.nargs === 0) { + part = '' + optionString; + + // if the Optional takes a value, format is: -s ARGS or --long ARGS + } else { + argsDefault = action.dest.toUpperCase(); + argsString = self._formatArgs(action, argsDefault); + part = optionString + ' ' + argsString; + } + // make it look optional if it's not required or in a group + if (!action.required && groupActions.indexOf(action) < 0) { + part = '[' + part + ']'; + } + // add the action string to the list + parts.push(part); + } + }); + + // insert things at the necessary indices + for (var i = inserts.length - 1; i >= 0; --i) { + if (inserts[i] !== null) { + parts.splice(i, 0, inserts[i]); + } + } + + // join all the action items with spaces + var text = parts.filter(function (part) { + return !!part; + }).join(' '); + + // clean up separators for mutually exclusive groups + text = text.replace(/([\[(]) /g, '$1'); // remove spaces + text = text.replace(/ ([\])])/g, '$1'); + text = text.replace(/\[ *\]/g, ''); // remove empty groups + text = text.replace(/\( *\)/g, ''); + text = text.replace(/\(([^|]*)\)/g, '$1'); // remove () from single action groups + + text = text.trim(); + + // return the text + return text; +}; + +HelpFormatter.prototype._formatText = function (text) { + text = sprintf(text, { prog: this._prog }); + var textWidth = this._width - this._currentIndent; + var indentIncriment = $$.repeat(' ', this._currentIndent); + return this._fillText(text, textWidth, indentIncriment) + c.EOL + c.EOL; +}; + +HelpFormatter.prototype._formatAction = function (action) { + var self = this; + + var helpText; + var helpLines; + var parts; + var indentFirst; + + // determine the required width and the entry label + var helpPosition = Math.min(this._actionMaxLength + 2, this._maxHelpPosition); + var helpWidth = this._width - helpPosition; + var actionWidth = helpPosition - this._currentIndent - 2; + var actionHeader = this._formatActionInvocation(action); + + // no help; start on same line and add a final newline + if (!action.help) { + actionHeader = $$.repeat(' ', this._currentIndent) + actionHeader + c.EOL; + + // short action name; start on the same line and pad two spaces + } else if (actionHeader.length <= actionWidth) { + actionHeader = $$.repeat(' ', this._currentIndent) + + actionHeader + + ' ' + + $$.repeat(' ', actionWidth - actionHeader.length); + indentFirst = 0; + + // long action name; start on the next line + } else { + actionHeader = $$.repeat(' ', this._currentIndent) + actionHeader + c.EOL; + indentFirst = helpPosition; + } + + // collect the pieces of the action help + parts = [ actionHeader ]; + + // if there was help for the action, add lines of help text + if (action.help) { + helpText = this._expandHelp(action); + helpLines = this._splitLines(helpText, helpWidth); + parts.push($$.repeat(' ', indentFirst) + helpLines[0] + c.EOL); + helpLines.slice(1).forEach(function (line) { + parts.push($$.repeat(' ', helpPosition) + line + c.EOL); + }); + + // or add a newline if the description doesn't end with one + } else if (actionHeader.charAt(actionHeader.length - 1) !== c.EOL) { + parts.push(c.EOL); + } + // if there are any sub-actions, add their help as well + if (action._getSubactions) { + this._indent(); + action._getSubactions().forEach(function (subaction) { + parts.push(self._formatAction(subaction)); + }); + this._dedent(); + } + // return a single string + return this._joinParts(parts); +}; + +HelpFormatter.prototype._formatActionInvocation = function (action) { + if (!action.isOptional()) { + var format_func = this._metavarFormatter(action, action.dest); + var metavars = format_func(1); + return metavars[0]; + } + + var parts = []; + var argsDefault; + var argsString; + + // if the Optional doesn't take a value, format is: -s, --long + if (action.nargs === 0) { + parts = parts.concat(action.optionStrings); + + // if the Optional takes a value, format is: -s ARGS, --long ARGS + } else { + argsDefault = action.dest.toUpperCase(); + argsString = this._formatArgs(action, argsDefault); + action.optionStrings.forEach(function (optionString) { + parts.push(optionString + ' ' + argsString); + }); + } + return parts.join(', '); +}; + +HelpFormatter.prototype._metavarFormatter = function (action, metavarDefault) { + var result; + + if (action.metavar || action.metavar === '') { + result = action.metavar; + } else if (action.choices) { + var choices = action.choices; + + if (typeof choices === 'string') { + choices = choices.split('').join(', '); + } else if (Array.isArray(choices)) { + choices = choices.join(','); + } else { + choices = Object.keys(choices).join(','); + } + result = '{' + choices + '}'; + } else { + result = metavarDefault; + } + + return function (size) { + if (Array.isArray(result)) { + return result; + } + + var metavars = []; + for (var i = 0; i < size; i += 1) { + metavars.push(result); + } + return metavars; + }; +}; + +HelpFormatter.prototype._formatArgs = function (action, metavarDefault) { + var result; + var metavars; + + var buildMetavar = this._metavarFormatter(action, metavarDefault); + + switch (action.nargs) { + /*eslint-disable no-undefined*/ + case undefined: + case null: + metavars = buildMetavar(1); + result = '' + metavars[0]; + break; + case c.OPTIONAL: + metavars = buildMetavar(1); + result = '[' + metavars[0] + ']'; + break; + case c.ZERO_OR_MORE: + metavars = buildMetavar(2); + result = '[' + metavars[0] + ' [' + metavars[1] + ' ...]]'; + break; + case c.ONE_OR_MORE: + metavars = buildMetavar(2); + result = '' + metavars[0] + ' [' + metavars[1] + ' ...]'; + break; + case c.REMAINDER: + result = '...'; + break; + case c.PARSER: + metavars = buildMetavar(1); + result = metavars[0] + ' ...'; + break; + default: + metavars = buildMetavar(action.nargs); + result = metavars.join(' '); + } + return result; +}; + +HelpFormatter.prototype._expandHelp = function (action) { + var params = { prog: this._prog }; + + Object.keys(action).forEach(function (actionProperty) { + var actionValue = action[actionProperty]; + + if (actionValue !== c.SUPPRESS) { + params[actionProperty] = actionValue; + } + }); + + if (params.choices) { + if (typeof params.choices === 'string') { + params.choices = params.choices.split('').join(', '); + } else if (Array.isArray(params.choices)) { + params.choices = params.choices.join(', '); + } else { + params.choices = Object.keys(params.choices).join(', '); + } + } + + return sprintf(this._getHelpString(action), params); +}; + +HelpFormatter.prototype._splitLines = function (text, width) { + var lines = []; + var delimiters = [ ' ', '.', ',', '!', '?' ]; + var re = new RegExp('[' + delimiters.join('') + '][^' + delimiters.join('') + ']*$'); + + text = text.replace(/[\n\|\t]/g, ' '); + + text = text.trim(); + text = text.replace(this._whitespaceMatcher, ' '); + + // Wraps the single paragraph in text (a string) so every line + // is at most width characters long. + text.split(c.EOL).forEach(function (line) { + if (width >= line.length) { + lines.push(line); + return; + } + + var wrapStart = 0; + var wrapEnd = width; + var delimiterIndex = 0; + while (wrapEnd <= line.length) { + if (wrapEnd !== line.length && delimiters.indexOf(line[wrapEnd] < -1)) { + delimiterIndex = (re.exec(line.substring(wrapStart, wrapEnd)) || {}).index; + wrapEnd = wrapStart + delimiterIndex + 1; + } + lines.push(line.substring(wrapStart, wrapEnd)); + wrapStart = wrapEnd; + wrapEnd += width; + } + if (wrapStart < line.length) { + lines.push(line.substring(wrapStart, wrapEnd)); + } + }); + + return lines; +}; + +HelpFormatter.prototype._fillText = function (text, width, indent) { + var lines = this._splitLines(text, width); + lines = lines.map(function (line) { + return indent + line; + }); + return lines.join(c.EOL); +}; + +HelpFormatter.prototype._getHelpString = function (action) { + return action.help; +}; diff --git a/scripts/node_modules/argparse/lib/namespace.js b/scripts/node_modules/argparse/lib/namespace.js new file mode 100644 index 000000000..a860de9ec --- /dev/null +++ b/scripts/node_modules/argparse/lib/namespace.js @@ -0,0 +1,76 @@ +/** + * class Namespace + * + * Simple object for storing attributes. Implements equality by attribute names + * and values, and provides a simple string representation. + * + * See also [original guide][1] + * + * [1]:http://docs.python.org/dev/library/argparse.html#the-namespace-object + **/ +'use strict'; + +var $$ = require('./utils'); + +/** + * new Namespace(options) + * - options(object): predefined propertis for result object + * + **/ +var Namespace = module.exports = function Namespace(options) { + $$.extend(this, options); +}; + +/** + * Namespace#isset(key) -> Boolean + * - key (string|number): property name + * + * Tells whenever `namespace` contains given `key` or not. + **/ +Namespace.prototype.isset = function (key) { + return $$.has(this, key); +}; + +/** + * Namespace#set(key, value) -> self + * -key (string|number|object): propery name + * -value (mixed): new property value + * + * Set the property named key with value. + * If key object then set all key properties to namespace object + **/ +Namespace.prototype.set = function (key, value) { + if (typeof (key) === 'object') { + $$.extend(this, key); + } else { + this[key] = value; + } + return this; +}; + +/** + * Namespace#get(key, defaultValue) -> mixed + * - key (string|number): property name + * - defaultValue (mixed): default value + * + * Return the property key or defaulValue if not set + **/ +Namespace.prototype.get = function (key, defaultValue) { + return !this[key] ? defaultValue : this[key]; +}; + +/** + * Namespace#unset(key, defaultValue) -> mixed + * - key (string|number): property name + * - defaultValue (mixed): default value + * + * Return data[key](and delete it) or defaultValue + **/ +Namespace.prototype.unset = function (key, defaultValue) { + var value = this[key]; + if (value !== null) { + delete this[key]; + return value; + } + return defaultValue; +}; diff --git a/scripts/node_modules/argparse/lib/utils.js b/scripts/node_modules/argparse/lib/utils.js new file mode 100644 index 000000000..4a9cf3edb --- /dev/null +++ b/scripts/node_modules/argparse/lib/utils.js @@ -0,0 +1,57 @@ +'use strict'; + +exports.repeat = function (str, num) { + var result = ''; + for (var i = 0; i < num; i++) { result += str; } + return result; +}; + +exports.arrayEqual = function (a, b) { + if (a.length !== b.length) { return false; } + for (var i = 0; i < a.length; i++) { + if (a[i] !== b[i]) { return false; } + } + return true; +}; + +exports.trimChars = function (str, chars) { + var start = 0; + var end = str.length - 1; + while (chars.indexOf(str.charAt(start)) >= 0) { start++; } + while (chars.indexOf(str.charAt(end)) >= 0) { end--; } + return str.slice(start, end + 1); +}; + +exports.capitalize = function (str) { + return str.charAt(0).toUpperCase() + str.slice(1); +}; + +exports.arrayUnion = function () { + var result = []; + for (var i = 0, values = {}; i < arguments.length; i++) { + var arr = arguments[i]; + for (var j = 0; j < arr.length; j++) { + if (!values[arr[j]]) { + values[arr[j]] = true; + result.push(arr[j]); + } + } + } + return result; +}; + +function has(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} + +exports.has = has; + +exports.extend = function (dest, src) { + for (var i in src) { + if (has(src, i)) { dest[i] = src[i]; } + } +}; + +exports.trimEnd = function (str) { + return str.replace(/\s+$/g, ''); +}; diff --git a/scripts/node_modules/argparse/package.json b/scripts/node_modules/argparse/package.json new file mode 100644 index 000000000..62fba0a9f --- /dev/null +++ b/scripts/node_modules/argparse/package.json @@ -0,0 +1,34 @@ +{ + "name": "argparse", + "description": "Very powerful CLI arguments parser. Native port of argparse - python's options parsing library", + "version": "1.0.10", + "keywords": [ + "cli", + "parser", + "argparse", + "option", + "args" + ], + "contributors": [ + "Eugene Shkuropat", + "Paul Jacobson" + ], + "files": [ + "index.js", + "lib/" + ], + "license": "MIT", + "repository": "nodeca/argparse", + "scripts": { + "test": "make test" + }, + "dependencies": { + "sprintf-js": "~1.0.2" + }, + "devDependencies": { + "eslint": "^2.13.1", + "istanbul": "^0.4.5", + "mocha": "^3.1.0", + "ndoc": "^5.0.1" + } +} diff --git a/scripts/node_modules/esprima/ChangeLog b/scripts/node_modules/esprima/ChangeLog new file mode 100644 index 000000000..fafe1c98e --- /dev/null +++ b/scripts/node_modules/esprima/ChangeLog @@ -0,0 +1,235 @@ +2018-06-17: Version 4.0.1 + + * Fix parsing async get/set in a class (issue 1861, 1875) + * Account for different return statement argument (issue 1829, 1897, 1928) + * Correct the handling of HTML comment when parsing a module (issue 1841) + * Fix incorrect parse async with proto-identifier-shorthand (issue 1847) + * Fix negative column in binary expression (issue 1844) + * Fix incorrect YieldExpression in object methods (issue 1834) + * Various documentation fixes + +2017-06-10: Version 4.0.0 + + * Support ES2017 async function and await expression (issue 1079) + * Support ES2017 trailing commas in function parameters (issue 1550) + * Explicitly distinguish parsing a module vs a script (issue 1576) + * Fix JSX non-empty container (issue 1786) + * Allow JSX element in a yield expression (issue 1765) + * Allow `in` expression in a concise body with a function body (issue 1793) + * Setter function argument must not be a rest parameter (issue 1693) + * Limit strict mode directive to functions with a simple parameter list (issue 1677) + * Prohibit any escape sequence in a reserved word (issue 1612) + * Only permit hex digits in hex escape sequence (issue 1619) + * Prohibit labelled class/generator/function declaration (issue 1484) + * Limit function declaration as if statement clause only in non-strict mode (issue 1657) + * Tolerate missing ) in a with and do-while statement (issue 1481) + +2016-12-22: Version 3.1.3 + + * Support binding patterns as rest element (issue 1681) + * Account for different possible arguments of a yield expression (issue 1469) + +2016-11-24: Version 3.1.2 + + * Ensure that import specifier is more restrictive (issue 1615) + * Fix duplicated JSX tokens (issue 1613) + * Scan template literal in a JSX expression container (issue 1622) + * Improve XHTML entity scanning in JSX (issue 1629) + +2016-10-31: Version 3.1.1 + + * Fix assignment expression problem in an export declaration (issue 1596) + * Fix incorrect tokenization of hex digits (issue 1605) + +2016-10-09: Version 3.1.0 + + * Do not implicitly collect comments when comment attachment is specified (issue 1553) + * Fix incorrect handling of duplicated proto shorthand fields (issue 1485) + * Prohibit initialization in some variants of for statements (issue 1309, 1561) + * Fix incorrect parsing of export specifier (issue 1578) + * Fix ESTree compatibility for assignment pattern (issue 1575) + +2016-09-03: Version 3.0.0 + + * Support ES2016 exponentiation expression (issue 1490) + * Support JSX syntax (issue 1467) + * Use the latest Unicode 8.0 (issue 1475) + * Add the support for syntax node delegate (issue 1435) + * Fix ESTree compatibility on meta property (issue 1338) + * Fix ESTree compatibility on default parameter value (issue 1081) + * Fix ESTree compatibility on try handler (issue 1030) + +2016-08-23: Version 2.7.3 + + * Fix tokenizer confusion with a comment (issue 1493, 1516) + +2016-02-02: Version 2.7.2 + + * Fix out-of-bound error location in an invalid string literal (issue 1457) + * Fix shorthand object destructuring defaults in variable declarations (issue 1459) + +2015-12-10: Version 2.7.1 + + * Do not allow trailing comma in a variable declaration (issue 1360) + * Fix assignment to `let` in non-strict mode (issue 1376) + * Fix missing delegate property in YieldExpression (issue 1407) + +2015-10-22: Version 2.7.0 + + * Fix the handling of semicolon in a break statement (issue 1044) + * Run the test suite with major web browsers (issue 1259, 1317) + * Allow `let` as an identifier in non-strict mode (issue 1289) + * Attach orphaned comments as `innerComments` (issue 1328) + * Add the support for token delegator (issue 1332) + +2015-09-01: Version 2.6.0 + + * Properly allow or prohibit `let` in a binding identifier/pattern (issue 1048, 1098) + * Add sourceType field for Program node (issue 1159) + * Ensure that strict mode reserved word binding throw an error (issue 1171) + * Run the test suite with Node.js and IE 11 on Windows (issue 1294) + * Allow binding pattern with no initializer in a for statement (issue 1301) + +2015-07-31: Version 2.5.0 + + * Run the test suite in a browser environment (issue 1004) + * Ensure a comma between imported default binding and named imports (issue 1046) + * Distinguish `yield` as a keyword vs an identifier (issue 1186) + * Support ES6 meta property `new.target` (issue 1203) + * Fix the syntax node for yield with expression (issue 1223) + * Fix the check of duplicated proto in property names (issue 1225) + * Fix ES6 Unicode escape in identifier name (issue 1229) + * Support ES6 IdentifierStart and IdentifierPart (issue 1232) + * Treat await as a reserved word when parsing as a module (issue 1234) + * Recognize identifier characters from Unicode SMP (issue 1244) + * Ensure that export and import can be followed by a comma (issue 1250) + * Fix yield operator precedence (issue 1262) + +2015-07-01: Version 2.4.1 + + * Fix some cases of comment attachment (issue 1071, 1175) + * Fix the handling of destructuring in function arguments (issue 1193) + * Fix invalid ranges in assignment expression (issue 1201) + +2015-06-26: Version 2.4.0 + + * Support ES6 for-of iteration (issue 1047) + * Support ES6 spread arguments (issue 1169) + * Minimize npm payload (issue 1191) + +2015-06-16: Version 2.3.0 + + * Support ES6 generator (issue 1033) + * Improve parsing of regular expressions with `u` flag (issue 1179) + +2015-04-17: Version 2.2.0 + + * Support ES6 import and export declarations (issue 1000) + * Fix line terminator before arrow not recognized as error (issue 1009) + * Support ES6 destructuring (issue 1045) + * Support ES6 template literal (issue 1074) + * Fix the handling of invalid/incomplete string escape sequences (issue 1106) + * Fix ES3 static member access restriction (issue 1120) + * Support for `super` in ES6 class (issue 1147) + +2015-03-09: Version 2.1.0 + + * Support ES6 class (issue 1001) + * Support ES6 rest parameter (issue 1011) + * Expand the location of property getter, setter, and methods (issue 1029) + * Enable TryStatement transition to a single handler (issue 1031) + * Support ES6 computed property name (issue 1037) + * Tolerate unclosed block comment (issue 1041) + * Support ES6 lexical declaration (issue 1065) + +2015-02-06: Version 2.0.0 + + * Support ES6 arrow function (issue 517) + * Support ES6 Unicode code point escape (issue 521) + * Improve the speed and accuracy of comment attachment (issue 522) + * Support ES6 default parameter (issue 519) + * Support ES6 regular expression flags (issue 557) + * Fix scanning of implicit octal literals (issue 565) + * Fix the handling of automatic semicolon insertion (issue 574) + * Support ES6 method definition (issue 620) + * Support ES6 octal integer literal (issue 621) + * Support ES6 binary integer literal (issue 622) + * Support ES6 object literal property value shorthand (issue 624) + +2015-03-03: Version 1.2.5 + + * Fix scanning of implicit octal literals (issue 565) + +2015-02-05: Version 1.2.4 + + * Fix parsing of LeftHandSideExpression in ForInStatement (issue 560) + * Fix the handling of automatic semicolon insertion (issue 574) + +2015-01-18: Version 1.2.3 + + * Fix division by this (issue 616) + +2014-05-18: Version 1.2.2 + + * Fix duplicated tokens when collecting comments (issue 537) + +2014-05-04: Version 1.2.1 + + * Ensure that Program node may still have leading comments (issue 536) + +2014-04-29: Version 1.2.0 + + * Fix semicolon handling for expression statement (issue 462, 533) + * Disallow escaped characters in regular expression flags (issue 503) + * Performance improvement for location tracking (issue 520) + * Improve the speed of comment attachment (issue 522) + +2014-03-26: Version 1.1.1 + + * Fix token handling of forward slash after an array literal (issue 512) + +2014-03-23: Version 1.1.0 + + * Optionally attach comments to the owning syntax nodes (issue 197) + * Simplify binary parsing with stack-based shift reduce (issue 352) + * Always include the raw source of literals (issue 376) + * Add optional input source information (issue 386) + * Tokenizer API for pure lexical scanning (issue 398) + * Improve the web site and its online demos (issue 337, 400, 404) + * Performance improvement for location tracking (issue 417, 424) + * Support HTML comment syntax (issue 451) + * Drop support for legacy browsers (issue 474) + +2013-08-27: Version 1.0.4 + + * Minimize the payload for packages (issue 362) + * Fix missing cases on an empty switch statement (issue 436) + * Support escaped ] in regexp literal character classes (issue 442) + * Tolerate invalid left-hand side expression (issue 130) + +2013-05-17: Version 1.0.3 + + * Variable declaration needs at least one declarator (issue 391) + * Fix benchmark's variance unit conversion (issue 397) + * IE < 9: \v should be treated as vertical tab (issue 405) + * Unary expressions should always have prefix: true (issue 418) + * Catch clause should only accept an identifier (issue 423) + * Tolerate setters without parameter (issue 426) + +2012-11-02: Version 1.0.2 + + Improvement: + + * Fix esvalidate JUnit output upon a syntax error (issue 374) + +2012-10-28: Version 1.0.1 + + Improvements: + + * esvalidate understands shebang in a Unix shell script (issue 361) + * esvalidate treats fatal parsing failure as an error (issue 361) + * Reduce Node.js package via .npmignore (issue 362) + +2012-10-22: Version 1.0.0 + + Initial release. diff --git a/scripts/node_modules/esprima/LICENSE.BSD b/scripts/node_modules/esprima/LICENSE.BSD new file mode 100644 index 000000000..7a55160f5 --- /dev/null +++ b/scripts/node_modules/esprima/LICENSE.BSD @@ -0,0 +1,21 @@ +Copyright JS Foundation and other contributors, https://js.foundation/ + +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. diff --git a/scripts/node_modules/esprima/README.md b/scripts/node_modules/esprima/README.md new file mode 100644 index 000000000..8fb25e6c1 --- /dev/null +++ b/scripts/node_modules/esprima/README.md @@ -0,0 +1,46 @@ +[![NPM version](https://img.shields.io/npm/v/esprima.svg)](https://www.npmjs.com/package/esprima) +[![npm download](https://img.shields.io/npm/dm/esprima.svg)](https://www.npmjs.com/package/esprima) +[![Build Status](https://img.shields.io/travis/jquery/esprima/master.svg)](https://travis-ci.org/jquery/esprima) +[![Coverage Status](https://img.shields.io/codecov/c/github/jquery/esprima/master.svg)](https://codecov.io/github/jquery/esprima) + +**Esprima** ([esprima.org](http://esprima.org), BSD license) is a high performance, +standard-compliant [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) +parser written in ECMAScript (also popularly known as +[JavaScript](https://en.wikipedia.org/wiki/JavaScript)). +Esprima is created and maintained by [Ariya Hidayat](https://twitter.com/ariyahidayat), +with the help of [many contributors](https://github.com/jquery/esprima/contributors). + +### Features + +- Full support for ECMAScript 2017 ([ECMA-262 8th Edition](http://www.ecma-international.org/publications/standards/Ecma-262.htm)) +- Sensible [syntax tree format](https://github.com/estree/estree/blob/master/es5.md) as standardized by [ESTree project](https://github.com/estree/estree) +- Experimental support for [JSX](https://facebook.github.io/jsx/), a syntax extension for [React](https://facebook.github.io/react/) +- Optional tracking of syntax node location (index-based and line-column) +- [Heavily tested](http://esprima.org/test/ci.html) (~1500 [unit tests](https://github.com/jquery/esprima/tree/master/test/fixtures) with [full code coverage](https://codecov.io/github/jquery/esprima)) + +### API + +Esprima can be used to perform [lexical analysis](https://en.wikipedia.org/wiki/Lexical_analysis) (tokenization) or [syntactic analysis](https://en.wikipedia.org/wiki/Parsing) (parsing) of a JavaScript program. + +A simple example on Node.js REPL: + +```javascript +> var esprima = require('esprima'); +> var program = 'const answer = 42'; + +> esprima.tokenize(program); +[ { type: 'Keyword', value: 'const' }, + { type: 'Identifier', value: 'answer' }, + { type: 'Punctuator', value: '=' }, + { type: 'Numeric', value: '42' } ] + +> esprima.parseScript(program); +{ type: 'Program', + body: + [ { type: 'VariableDeclaration', + declarations: [Object], + kind: 'const' } ], + sourceType: 'script' } +``` + +For more information, please read the [complete documentation](http://esprima.org/doc). \ No newline at end of file diff --git a/scripts/node_modules/esprima/bin/esparse.js b/scripts/node_modules/esprima/bin/esparse.js new file mode 100755 index 000000000..45d05fbb7 --- /dev/null +++ b/scripts/node_modules/esprima/bin/esparse.js @@ -0,0 +1,139 @@ +#!/usr/bin/env node +/* + Copyright JS Foundation and other contributors, https://js.foundation/ + + 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. +*/ + +/*jslint sloppy:true node:true rhino:true */ + +var fs, esprima, fname, forceFile, content, options, syntax; + +if (typeof require === 'function') { + fs = require('fs'); + try { + esprima = require('esprima'); + } catch (e) { + esprima = require('../'); + } +} else if (typeof load === 'function') { + try { + load('esprima.js'); + } catch (e) { + load('../esprima.js'); + } +} + +// Shims to Node.js objects when running under Rhino. +if (typeof console === 'undefined' && typeof process === 'undefined') { + console = { log: print }; + fs = { readFileSync: readFile }; + process = { argv: arguments, exit: quit }; + process.argv.unshift('esparse.js'); + process.argv.unshift('rhino'); +} + +function showUsage() { + console.log('Usage:'); + console.log(' esparse [options] [file.js]'); + console.log(); + console.log('Available options:'); + console.log(); + console.log(' --comment Gather all line and block comments in an array'); + console.log(' --loc Include line-column location info for each syntax node'); + console.log(' --range Include index-based range for each syntax node'); + console.log(' --raw Display the raw value of literals'); + console.log(' --tokens List all tokens in an array'); + console.log(' --tolerant Tolerate errors on a best-effort basis (experimental)'); + console.log(' -v, --version Shows program version'); + console.log(); + process.exit(1); +} + +options = {}; + +process.argv.splice(2).forEach(function (entry) { + + if (forceFile || entry === '-' || entry.slice(0, 1) !== '-') { + if (typeof fname === 'string') { + console.log('Error: more than one input file.'); + process.exit(1); + } else { + fname = entry; + } + } else if (entry === '-h' || entry === '--help') { + showUsage(); + } else if (entry === '-v' || entry === '--version') { + console.log('ECMAScript Parser (using Esprima version', esprima.version, ')'); + console.log(); + process.exit(0); + } else if (entry === '--comment') { + options.comment = true; + } else if (entry === '--loc') { + options.loc = true; + } else if (entry === '--range') { + options.range = true; + } else if (entry === '--raw') { + options.raw = true; + } else if (entry === '--tokens') { + options.tokens = true; + } else if (entry === '--tolerant') { + options.tolerant = true; + } else if (entry === '--') { + forceFile = true; + } else { + console.log('Error: unknown option ' + entry + '.'); + process.exit(1); + } +}); + +// Special handling for regular expression literal since we need to +// convert it to a string literal, otherwise it will be decoded +// as object "{}" and the regular expression would be lost. +function adjustRegexLiteral(key, value) { + if (key === 'value' && value instanceof RegExp) { + value = value.toString(); + } + return value; +} + +function run(content) { + syntax = esprima.parse(content, options); + console.log(JSON.stringify(syntax, adjustRegexLiteral, 4)); +} + +try { + if (fname && (fname !== '-' || forceFile)) { + run(fs.readFileSync(fname, 'utf-8')); + } else { + var content = ''; + process.stdin.resume(); + process.stdin.on('data', function(chunk) { + content += chunk; + }); + process.stdin.on('end', function() { + run(content); + }); + } +} catch (e) { + console.log('Error: ' + e.message); + process.exit(1); +} diff --git a/scripts/node_modules/esprima/bin/esvalidate.js b/scripts/node_modules/esprima/bin/esvalidate.js new file mode 100755 index 000000000..d49a7e40a --- /dev/null +++ b/scripts/node_modules/esprima/bin/esvalidate.js @@ -0,0 +1,236 @@ +#!/usr/bin/env node +/* + Copyright JS Foundation and other contributors, https://js.foundation/ + + 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. +*/ + +/*jslint sloppy:true plusplus:true node:true rhino:true */ +/*global phantom:true */ + +var fs, system, esprima, options, fnames, forceFile, count; + +if (typeof esprima === 'undefined') { + // PhantomJS can only require() relative files + if (typeof phantom === 'object') { + fs = require('fs'); + system = require('system'); + esprima = require('./esprima'); + } else if (typeof require === 'function') { + fs = require('fs'); + try { + esprima = require('esprima'); + } catch (e) { + esprima = require('../'); + } + } else if (typeof load === 'function') { + try { + load('esprima.js'); + } catch (e) { + load('../esprima.js'); + } + } +} + +// Shims to Node.js objects when running under PhantomJS 1.7+. +if (typeof phantom === 'object') { + fs.readFileSync = fs.read; + process = { + argv: [].slice.call(system.args), + exit: phantom.exit, + on: function (evt, callback) { + callback(); + } + }; + process.argv.unshift('phantomjs'); +} + +// Shims to Node.js objects when running under Rhino. +if (typeof console === 'undefined' && typeof process === 'undefined') { + console = { log: print }; + fs = { readFileSync: readFile }; + process = { + argv: arguments, + exit: quit, + on: function (evt, callback) { + callback(); + } + }; + process.argv.unshift('esvalidate.js'); + process.argv.unshift('rhino'); +} + +function showUsage() { + console.log('Usage:'); + console.log(' esvalidate [options] [file.js...]'); + console.log(); + console.log('Available options:'); + console.log(); + console.log(' --format=type Set the report format, plain (default) or junit'); + console.log(' -v, --version Print program version'); + console.log(); + process.exit(1); +} + +options = { + format: 'plain' +}; + +fnames = []; + +process.argv.splice(2).forEach(function (entry) { + + if (forceFile || entry === '-' || entry.slice(0, 1) !== '-') { + fnames.push(entry); + } else if (entry === '-h' || entry === '--help') { + showUsage(); + } else if (entry === '-v' || entry === '--version') { + console.log('ECMAScript Validator (using Esprima version', esprima.version, ')'); + console.log(); + process.exit(0); + } else if (entry.slice(0, 9) === '--format=') { + options.format = entry.slice(9); + if (options.format !== 'plain' && options.format !== 'junit') { + console.log('Error: unknown report format ' + options.format + '.'); + process.exit(1); + } + } else if (entry === '--') { + forceFile = true; + } else { + console.log('Error: unknown option ' + entry + '.'); + process.exit(1); + } +}); + +if (fnames.length === 0) { + fnames.push(''); +} + +if (options.format === 'junit') { + console.log(''); + console.log(''); +} + +count = 0; + +function run(fname, content) { + var timestamp, syntax, name; + try { + if (typeof content !== 'string') { + throw content; + } + + if (content[0] === '#' && content[1] === '!') { + content = '//' + content.substr(2, content.length); + } + + timestamp = Date.now(); + syntax = esprima.parse(content, { tolerant: true }); + + if (options.format === 'junit') { + + name = fname; + if (name.lastIndexOf('/') >= 0) { + name = name.slice(name.lastIndexOf('/') + 1); + } + + console.log(''); + + syntax.errors.forEach(function (error) { + var msg = error.message; + msg = msg.replace(/^Line\ [0-9]*\:\ /, ''); + console.log(' '); + console.log(' ' + + error.message + '(' + name + ':' + error.lineNumber + ')' + + ''); + console.log(' '); + }); + + console.log(''); + + } else if (options.format === 'plain') { + + syntax.errors.forEach(function (error) { + var msg = error.message; + msg = msg.replace(/^Line\ [0-9]*\:\ /, ''); + msg = fname + ':' + error.lineNumber + ': ' + msg; + console.log(msg); + ++count; + }); + + } + } catch (e) { + ++count; + if (options.format === 'junit') { + console.log(''); + console.log(' '); + console.log(' ' + + e.message + '(' + fname + ((e.lineNumber) ? ':' + e.lineNumber : '') + + ')'); + console.log(' '); + console.log(''); + } else { + console.log(fname + ':' + e.lineNumber + ': ' + e.message.replace(/^Line\ [0-9]*\:\ /, '')); + } + } +} + +fnames.forEach(function (fname) { + var content = ''; + try { + if (fname && (fname !== '-' || forceFile)) { + content = fs.readFileSync(fname, 'utf-8'); + } else { + fname = ''; + process.stdin.resume(); + process.stdin.on('data', function(chunk) { + content += chunk; + }); + process.stdin.on('end', function() { + run(fname, content); + }); + return; + } + } catch (e) { + content = e; + } + run(fname, content); +}); + +process.on('exit', function () { + if (options.format === 'junit') { + console.log(''); + } + + if (count > 0) { + process.exit(1); + } + + if (count === 0 && typeof phantom === 'object') { + process.exit(0); + } +}); diff --git a/scripts/node_modules/esprima/dist/esprima.js b/scripts/node_modules/esprima/dist/esprima.js new file mode 100644 index 000000000..2af3eee12 --- /dev/null +++ b/scripts/node_modules/esprima/dist/esprima.js @@ -0,0 +1,6709 @@ +(function webpackUniversalModuleDefinition(root, factory) { +/* istanbul ignore next */ + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); +/* istanbul ignore next */ + else if(typeof exports === 'object') + exports["esprima"] = factory(); + else + root["esprima"] = factory(); +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/* istanbul ignore if */ +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; + +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + +/******/ // Flag the module as loaded +/******/ module.loaded = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + + +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; + +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; + +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; + +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; + /* + Copyright JS Foundation and other contributors, https://js.foundation/ + + 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. + */ + Object.defineProperty(exports, "__esModule", { value: true }); + var comment_handler_1 = __webpack_require__(1); + var jsx_parser_1 = __webpack_require__(3); + var parser_1 = __webpack_require__(8); + var tokenizer_1 = __webpack_require__(15); + function parse(code, options, delegate) { + var commentHandler = null; + var proxyDelegate = function (node, metadata) { + if (delegate) { + delegate(node, metadata); + } + if (commentHandler) { + commentHandler.visit(node, metadata); + } + }; + var parserDelegate = (typeof delegate === 'function') ? proxyDelegate : null; + var collectComment = false; + if (options) { + collectComment = (typeof options.comment === 'boolean' && options.comment); + var attachComment = (typeof options.attachComment === 'boolean' && options.attachComment); + if (collectComment || attachComment) { + commentHandler = new comment_handler_1.CommentHandler(); + commentHandler.attach = attachComment; + options.comment = true; + parserDelegate = proxyDelegate; + } + } + var isModule = false; + if (options && typeof options.sourceType === 'string') { + isModule = (options.sourceType === 'module'); + } + var parser; + if (options && typeof options.jsx === 'boolean' && options.jsx) { + parser = new jsx_parser_1.JSXParser(code, options, parserDelegate); + } + else { + parser = new parser_1.Parser(code, options, parserDelegate); + } + var program = isModule ? parser.parseModule() : parser.parseScript(); + var ast = program; + if (collectComment && commentHandler) { + ast.comments = commentHandler.comments; + } + if (parser.config.tokens) { + ast.tokens = parser.tokens; + } + if (parser.config.tolerant) { + ast.errors = parser.errorHandler.errors; + } + return ast; + } + exports.parse = parse; + function parseModule(code, options, delegate) { + var parsingOptions = options || {}; + parsingOptions.sourceType = 'module'; + return parse(code, parsingOptions, delegate); + } + exports.parseModule = parseModule; + function parseScript(code, options, delegate) { + var parsingOptions = options || {}; + parsingOptions.sourceType = 'script'; + return parse(code, parsingOptions, delegate); + } + exports.parseScript = parseScript; + function tokenize(code, options, delegate) { + var tokenizer = new tokenizer_1.Tokenizer(code, options); + var tokens; + tokens = []; + try { + while (true) { + var token = tokenizer.getNextToken(); + if (!token) { + break; + } + if (delegate) { + token = delegate(token); + } + tokens.push(token); + } + } + catch (e) { + tokenizer.errorHandler.tolerate(e); + } + if (tokenizer.errorHandler.tolerant) { + tokens.errors = tokenizer.errors(); + } + return tokens; + } + exports.tokenize = tokenize; + var syntax_1 = __webpack_require__(2); + exports.Syntax = syntax_1.Syntax; + // Sync with *.json manifests. + exports.version = '4.0.1'; + + +/***/ }, +/* 1 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var syntax_1 = __webpack_require__(2); + var CommentHandler = (function () { + function CommentHandler() { + this.attach = false; + this.comments = []; + this.stack = []; + this.leading = []; + this.trailing = []; + } + CommentHandler.prototype.insertInnerComments = function (node, metadata) { + // innnerComments for properties empty block + // `function a() {/** comments **\/}` + if (node.type === syntax_1.Syntax.BlockStatement && node.body.length === 0) { + var innerComments = []; + for (var i = this.leading.length - 1; i >= 0; --i) { + var entry = this.leading[i]; + if (metadata.end.offset >= entry.start) { + innerComments.unshift(entry.comment); + this.leading.splice(i, 1); + this.trailing.splice(i, 1); + } + } + if (innerComments.length) { + node.innerComments = innerComments; + } + } + }; + CommentHandler.prototype.findTrailingComments = function (metadata) { + var trailingComments = []; + if (this.trailing.length > 0) { + for (var i = this.trailing.length - 1; i >= 0; --i) { + var entry_1 = this.trailing[i]; + if (entry_1.start >= metadata.end.offset) { + trailingComments.unshift(entry_1.comment); + } + } + this.trailing.length = 0; + return trailingComments; + } + var entry = this.stack[this.stack.length - 1]; + if (entry && entry.node.trailingComments) { + var firstComment = entry.node.trailingComments[0]; + if (firstComment && firstComment.range[0] >= metadata.end.offset) { + trailingComments = entry.node.trailingComments; + delete entry.node.trailingComments; + } + } + return trailingComments; + }; + CommentHandler.prototype.findLeadingComments = function (metadata) { + var leadingComments = []; + var target; + while (this.stack.length > 0) { + var entry = this.stack[this.stack.length - 1]; + if (entry && entry.start >= metadata.start.offset) { + target = entry.node; + this.stack.pop(); + } + else { + break; + } + } + if (target) { + var count = target.leadingComments ? target.leadingComments.length : 0; + for (var i = count - 1; i >= 0; --i) { + var comment = target.leadingComments[i]; + if (comment.range[1] <= metadata.start.offset) { + leadingComments.unshift(comment); + target.leadingComments.splice(i, 1); + } + } + if (target.leadingComments && target.leadingComments.length === 0) { + delete target.leadingComments; + } + return leadingComments; + } + for (var i = this.leading.length - 1; i >= 0; --i) { + var entry = this.leading[i]; + if (entry.start <= metadata.start.offset) { + leadingComments.unshift(entry.comment); + this.leading.splice(i, 1); + } + } + return leadingComments; + }; + CommentHandler.prototype.visitNode = function (node, metadata) { + if (node.type === syntax_1.Syntax.Program && node.body.length > 0) { + return; + } + this.insertInnerComments(node, metadata); + var trailingComments = this.findTrailingComments(metadata); + var leadingComments = this.findLeadingComments(metadata); + if (leadingComments.length > 0) { + node.leadingComments = leadingComments; + } + if (trailingComments.length > 0) { + node.trailingComments = trailingComments; + } + this.stack.push({ + node: node, + start: metadata.start.offset + }); + }; + CommentHandler.prototype.visitComment = function (node, metadata) { + var type = (node.type[0] === 'L') ? 'Line' : 'Block'; + var comment = { + type: type, + value: node.value + }; + if (node.range) { + comment.range = node.range; + } + if (node.loc) { + comment.loc = node.loc; + } + this.comments.push(comment); + if (this.attach) { + var entry = { + comment: { + type: type, + value: node.value, + range: [metadata.start.offset, metadata.end.offset] + }, + start: metadata.start.offset + }; + if (node.loc) { + entry.comment.loc = node.loc; + } + node.type = type; + this.leading.push(entry); + this.trailing.push(entry); + } + }; + CommentHandler.prototype.visit = function (node, metadata) { + if (node.type === 'LineComment') { + this.visitComment(node, metadata); + } + else if (node.type === 'BlockComment') { + this.visitComment(node, metadata); + } + else if (this.attach) { + this.visitNode(node, metadata); + } + }; + return CommentHandler; + }()); + exports.CommentHandler = CommentHandler; + + +/***/ }, +/* 2 */ +/***/ function(module, exports) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Syntax = { + AssignmentExpression: 'AssignmentExpression', + AssignmentPattern: 'AssignmentPattern', + ArrayExpression: 'ArrayExpression', + ArrayPattern: 'ArrayPattern', + ArrowFunctionExpression: 'ArrowFunctionExpression', + AwaitExpression: 'AwaitExpression', + BlockStatement: 'BlockStatement', + BinaryExpression: 'BinaryExpression', + BreakStatement: 'BreakStatement', + CallExpression: 'CallExpression', + CatchClause: 'CatchClause', + ClassBody: 'ClassBody', + ClassDeclaration: 'ClassDeclaration', + ClassExpression: 'ClassExpression', + ConditionalExpression: 'ConditionalExpression', + ContinueStatement: 'ContinueStatement', + DoWhileStatement: 'DoWhileStatement', + DebuggerStatement: 'DebuggerStatement', + EmptyStatement: 'EmptyStatement', + ExportAllDeclaration: 'ExportAllDeclaration', + ExportDefaultDeclaration: 'ExportDefaultDeclaration', + ExportNamedDeclaration: 'ExportNamedDeclaration', + ExportSpecifier: 'ExportSpecifier', + ExpressionStatement: 'ExpressionStatement', + ForStatement: 'ForStatement', + ForOfStatement: 'ForOfStatement', + ForInStatement: 'ForInStatement', + FunctionDeclaration: 'FunctionDeclaration', + FunctionExpression: 'FunctionExpression', + Identifier: 'Identifier', + IfStatement: 'IfStatement', + ImportDeclaration: 'ImportDeclaration', + ImportDefaultSpecifier: 'ImportDefaultSpecifier', + ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', + ImportSpecifier: 'ImportSpecifier', + Literal: 'Literal', + LabeledStatement: 'LabeledStatement', + LogicalExpression: 'LogicalExpression', + MemberExpression: 'MemberExpression', + MetaProperty: 'MetaProperty', + MethodDefinition: 'MethodDefinition', + NewExpression: 'NewExpression', + ObjectExpression: 'ObjectExpression', + ObjectPattern: 'ObjectPattern', + Program: 'Program', + Property: 'Property', + RestElement: 'RestElement', + ReturnStatement: 'ReturnStatement', + SequenceExpression: 'SequenceExpression', + SpreadElement: 'SpreadElement', + Super: 'Super', + SwitchCase: 'SwitchCase', + SwitchStatement: 'SwitchStatement', + TaggedTemplateExpression: 'TaggedTemplateExpression', + TemplateElement: 'TemplateElement', + TemplateLiteral: 'TemplateLiteral', + ThisExpression: 'ThisExpression', + ThrowStatement: 'ThrowStatement', + TryStatement: 'TryStatement', + UnaryExpression: 'UnaryExpression', + UpdateExpression: 'UpdateExpression', + VariableDeclaration: 'VariableDeclaration', + VariableDeclarator: 'VariableDeclarator', + WhileStatement: 'WhileStatement', + WithStatement: 'WithStatement', + YieldExpression: 'YieldExpression' + }; + + +/***/ }, +/* 3 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; +/* istanbul ignore next */ + var __extends = (this && this.__extends) || (function () { + var 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 function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + var character_1 = __webpack_require__(4); + var JSXNode = __webpack_require__(5); + var jsx_syntax_1 = __webpack_require__(6); + var Node = __webpack_require__(7); + var parser_1 = __webpack_require__(8); + var token_1 = __webpack_require__(13); + var xhtml_entities_1 = __webpack_require__(14); + token_1.TokenName[100 /* Identifier */] = 'JSXIdentifier'; + token_1.TokenName[101 /* Text */] = 'JSXText'; + // Fully qualified element name, e.g. returns "svg:path" + function getQualifiedElementName(elementName) { + var qualifiedName; + switch (elementName.type) { + case jsx_syntax_1.JSXSyntax.JSXIdentifier: + var id = elementName; + qualifiedName = id.name; + break; + case jsx_syntax_1.JSXSyntax.JSXNamespacedName: + var ns = elementName; + qualifiedName = getQualifiedElementName(ns.namespace) + ':' + + getQualifiedElementName(ns.name); + break; + case jsx_syntax_1.JSXSyntax.JSXMemberExpression: + var expr = elementName; + qualifiedName = getQualifiedElementName(expr.object) + '.' + + getQualifiedElementName(expr.property); + break; + /* istanbul ignore next */ + default: + break; + } + return qualifiedName; + } + var JSXParser = (function (_super) { + __extends(JSXParser, _super); + function JSXParser(code, options, delegate) { + return _super.call(this, code, options, delegate) || this; + } + JSXParser.prototype.parsePrimaryExpression = function () { + return this.match('<') ? this.parseJSXRoot() : _super.prototype.parsePrimaryExpression.call(this); + }; + JSXParser.prototype.startJSX = function () { + // Unwind the scanner before the lookahead token. + this.scanner.index = this.startMarker.index; + this.scanner.lineNumber = this.startMarker.line; + this.scanner.lineStart = this.startMarker.index - this.startMarker.column; + }; + JSXParser.prototype.finishJSX = function () { + // Prime the next lookahead. + this.nextToken(); + }; + JSXParser.prototype.reenterJSX = function () { + this.startJSX(); + this.expectJSX('}'); + // Pop the closing '}' added from the lookahead. + if (this.config.tokens) { + this.tokens.pop(); + } + }; + JSXParser.prototype.createJSXNode = function () { + this.collectComments(); + return { + index: this.scanner.index, + line: this.scanner.lineNumber, + column: this.scanner.index - this.scanner.lineStart + }; + }; + JSXParser.prototype.createJSXChildNode = function () { + return { + index: this.scanner.index, + line: this.scanner.lineNumber, + column: this.scanner.index - this.scanner.lineStart + }; + }; + JSXParser.prototype.scanXHTMLEntity = function (quote) { + var result = '&'; + var valid = true; + var terminated = false; + var numeric = false; + var hex = false; + while (!this.scanner.eof() && valid && !terminated) { + var ch = this.scanner.source[this.scanner.index]; + if (ch === quote) { + break; + } + terminated = (ch === ';'); + result += ch; + ++this.scanner.index; + if (!terminated) { + switch (result.length) { + case 2: + // e.g. '{' + numeric = (ch === '#'); + break; + case 3: + if (numeric) { + // e.g. 'A' + hex = (ch === 'x'); + valid = hex || character_1.Character.isDecimalDigit(ch.charCodeAt(0)); + numeric = numeric && !hex; + } + break; + default: + valid = valid && !(numeric && !character_1.Character.isDecimalDigit(ch.charCodeAt(0))); + valid = valid && !(hex && !character_1.Character.isHexDigit(ch.charCodeAt(0))); + break; + } + } + } + if (valid && terminated && result.length > 2) { + // e.g. 'A' becomes just '#x41' + var str = result.substr(1, result.length - 2); + if (numeric && str.length > 1) { + result = String.fromCharCode(parseInt(str.substr(1), 10)); + } + else if (hex && str.length > 2) { + result = String.fromCharCode(parseInt('0' + str.substr(1), 16)); + } + else if (!numeric && !hex && xhtml_entities_1.XHTMLEntities[str]) { + result = xhtml_entities_1.XHTMLEntities[str]; + } + } + return result; + }; + // Scan the next JSX token. This replaces Scanner#lex when in JSX mode. + JSXParser.prototype.lexJSX = function () { + var cp = this.scanner.source.charCodeAt(this.scanner.index); + // < > / : = { } + if (cp === 60 || cp === 62 || cp === 47 || cp === 58 || cp === 61 || cp === 123 || cp === 125) { + var value = this.scanner.source[this.scanner.index++]; + return { + type: 7 /* Punctuator */, + value: value, + lineNumber: this.scanner.lineNumber, + lineStart: this.scanner.lineStart, + start: this.scanner.index - 1, + end: this.scanner.index + }; + } + // " ' + if (cp === 34 || cp === 39) { + var start = this.scanner.index; + var quote = this.scanner.source[this.scanner.index++]; + var str = ''; + while (!this.scanner.eof()) { + var ch = this.scanner.source[this.scanner.index++]; + if (ch === quote) { + break; + } + else if (ch === '&') { + str += this.scanXHTMLEntity(quote); + } + else { + str += ch; + } + } + return { + type: 8 /* StringLiteral */, + value: str, + lineNumber: this.scanner.lineNumber, + lineStart: this.scanner.lineStart, + start: start, + end: this.scanner.index + }; + } + // ... or . + if (cp === 46) { + var n1 = this.scanner.source.charCodeAt(this.scanner.index + 1); + var n2 = this.scanner.source.charCodeAt(this.scanner.index + 2); + var value = (n1 === 46 && n2 === 46) ? '...' : '.'; + var start = this.scanner.index; + this.scanner.index += value.length; + return { + type: 7 /* Punctuator */, + value: value, + lineNumber: this.scanner.lineNumber, + lineStart: this.scanner.lineStart, + start: start, + end: this.scanner.index + }; + } + // ` + if (cp === 96) { + // Only placeholder, since it will be rescanned as a real assignment expression. + return { + type: 10 /* Template */, + value: '', + lineNumber: this.scanner.lineNumber, + lineStart: this.scanner.lineStart, + start: this.scanner.index, + end: this.scanner.index + }; + } + // Identifer can not contain backslash (char code 92). + if (character_1.Character.isIdentifierStart(cp) && (cp !== 92)) { + var start = this.scanner.index; + ++this.scanner.index; + while (!this.scanner.eof()) { + var ch = this.scanner.source.charCodeAt(this.scanner.index); + if (character_1.Character.isIdentifierPart(ch) && (ch !== 92)) { + ++this.scanner.index; + } + else if (ch === 45) { + // Hyphen (char code 45) can be part of an identifier. + ++this.scanner.index; + } + else { + break; + } + } + var id = this.scanner.source.slice(start, this.scanner.index); + return { + type: 100 /* Identifier */, + value: id, + lineNumber: this.scanner.lineNumber, + lineStart: this.scanner.lineStart, + start: start, + end: this.scanner.index + }; + } + return this.scanner.lex(); + }; + JSXParser.prototype.nextJSXToken = function () { + this.collectComments(); + this.startMarker.index = this.scanner.index; + this.startMarker.line = this.scanner.lineNumber; + this.startMarker.column = this.scanner.index - this.scanner.lineStart; + var token = this.lexJSX(); + this.lastMarker.index = this.scanner.index; + this.lastMarker.line = this.scanner.lineNumber; + this.lastMarker.column = this.scanner.index - this.scanner.lineStart; + if (this.config.tokens) { + this.tokens.push(this.convertToken(token)); + } + return token; + }; + JSXParser.prototype.nextJSXText = function () { + this.startMarker.index = this.scanner.index; + this.startMarker.line = this.scanner.lineNumber; + this.startMarker.column = this.scanner.index - this.scanner.lineStart; + var start = this.scanner.index; + var text = ''; + while (!this.scanner.eof()) { + var ch = this.scanner.source[this.scanner.index]; + if (ch === '{' || ch === '<') { + break; + } + ++this.scanner.index; + text += ch; + if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) { + ++this.scanner.lineNumber; + if (ch === '\r' && this.scanner.source[this.scanner.index] === '\n') { + ++this.scanner.index; + } + this.scanner.lineStart = this.scanner.index; + } + } + this.lastMarker.index = this.scanner.index; + this.lastMarker.line = this.scanner.lineNumber; + this.lastMarker.column = this.scanner.index - this.scanner.lineStart; + var token = { + type: 101 /* Text */, + value: text, + lineNumber: this.scanner.lineNumber, + lineStart: this.scanner.lineStart, + start: start, + end: this.scanner.index + }; + if ((text.length > 0) && this.config.tokens) { + this.tokens.push(this.convertToken(token)); + } + return token; + }; + JSXParser.prototype.peekJSXToken = function () { + var state = this.scanner.saveState(); + this.scanner.scanComments(); + var next = this.lexJSX(); + this.scanner.restoreState(state); + return next; + }; + // Expect the next JSX token to match the specified punctuator. + // If not, an exception will be thrown. + JSXParser.prototype.expectJSX = function (value) { + var token = this.nextJSXToken(); + if (token.type !== 7 /* Punctuator */ || token.value !== value) { + this.throwUnexpectedToken(token); + } + }; + // Return true if the next JSX token matches the specified punctuator. + JSXParser.prototype.matchJSX = function (value) { + var next = this.peekJSXToken(); + return next.type === 7 /* Punctuator */ && next.value === value; + }; + JSXParser.prototype.parseJSXIdentifier = function () { + var node = this.createJSXNode(); + var token = this.nextJSXToken(); + if (token.type !== 100 /* Identifier */) { + this.throwUnexpectedToken(token); + } + return this.finalize(node, new JSXNode.JSXIdentifier(token.value)); + }; + JSXParser.prototype.parseJSXElementName = function () { + var node = this.createJSXNode(); + var elementName = this.parseJSXIdentifier(); + if (this.matchJSX(':')) { + var namespace = elementName; + this.expectJSX(':'); + var name_1 = this.parseJSXIdentifier(); + elementName = this.finalize(node, new JSXNode.JSXNamespacedName(namespace, name_1)); + } + else if (this.matchJSX('.')) { + while (this.matchJSX('.')) { + var object = elementName; + this.expectJSX('.'); + var property = this.parseJSXIdentifier(); + elementName = this.finalize(node, new JSXNode.JSXMemberExpression(object, property)); + } + } + return elementName; + }; + JSXParser.prototype.parseJSXAttributeName = function () { + var node = this.createJSXNode(); + var attributeName; + var identifier = this.parseJSXIdentifier(); + if (this.matchJSX(':')) { + var namespace = identifier; + this.expectJSX(':'); + var name_2 = this.parseJSXIdentifier(); + attributeName = this.finalize(node, new JSXNode.JSXNamespacedName(namespace, name_2)); + } + else { + attributeName = identifier; + } + return attributeName; + }; + JSXParser.prototype.parseJSXStringLiteralAttribute = function () { + var node = this.createJSXNode(); + var token = this.nextJSXToken(); + if (token.type !== 8 /* StringLiteral */) { + this.throwUnexpectedToken(token); + } + var raw = this.getTokenRaw(token); + return this.finalize(node, new Node.Literal(token.value, raw)); + }; + JSXParser.prototype.parseJSXExpressionAttribute = function () { + var node = this.createJSXNode(); + this.expectJSX('{'); + this.finishJSX(); + if (this.match('}')) { + this.tolerateError('JSX attributes must only be assigned a non-empty expression'); + } + var expression = this.parseAssignmentExpression(); + this.reenterJSX(); + return this.finalize(node, new JSXNode.JSXExpressionContainer(expression)); + }; + JSXParser.prototype.parseJSXAttributeValue = function () { + return this.matchJSX('{') ? this.parseJSXExpressionAttribute() : + this.matchJSX('<') ? this.parseJSXElement() : this.parseJSXStringLiteralAttribute(); + }; + JSXParser.prototype.parseJSXNameValueAttribute = function () { + var node = this.createJSXNode(); + var name = this.parseJSXAttributeName(); + var value = null; + if (this.matchJSX('=')) { + this.expectJSX('='); + value = this.parseJSXAttributeValue(); + } + return this.finalize(node, new JSXNode.JSXAttribute(name, value)); + }; + JSXParser.prototype.parseJSXSpreadAttribute = function () { + var node = this.createJSXNode(); + this.expectJSX('{'); + this.expectJSX('...'); + this.finishJSX(); + var argument = this.parseAssignmentExpression(); + this.reenterJSX(); + return this.finalize(node, new JSXNode.JSXSpreadAttribute(argument)); + }; + JSXParser.prototype.parseJSXAttributes = function () { + var attributes = []; + while (!this.matchJSX('/') && !this.matchJSX('>')) { + var attribute = this.matchJSX('{') ? this.parseJSXSpreadAttribute() : + this.parseJSXNameValueAttribute(); + attributes.push(attribute); + } + return attributes; + }; + JSXParser.prototype.parseJSXOpeningElement = function () { + var node = this.createJSXNode(); + this.expectJSX('<'); + var name = this.parseJSXElementName(); + var attributes = this.parseJSXAttributes(); + var selfClosing = this.matchJSX('/'); + if (selfClosing) { + this.expectJSX('/'); + } + this.expectJSX('>'); + return this.finalize(node, new JSXNode.JSXOpeningElement(name, selfClosing, attributes)); + }; + JSXParser.prototype.parseJSXBoundaryElement = function () { + var node = this.createJSXNode(); + this.expectJSX('<'); + if (this.matchJSX('/')) { + this.expectJSX('/'); + var name_3 = this.parseJSXElementName(); + this.expectJSX('>'); + return this.finalize(node, new JSXNode.JSXClosingElement(name_3)); + } + var name = this.parseJSXElementName(); + var attributes = this.parseJSXAttributes(); + var selfClosing = this.matchJSX('/'); + if (selfClosing) { + this.expectJSX('/'); + } + this.expectJSX('>'); + return this.finalize(node, new JSXNode.JSXOpeningElement(name, selfClosing, attributes)); + }; + JSXParser.prototype.parseJSXEmptyExpression = function () { + var node = this.createJSXChildNode(); + this.collectComments(); + this.lastMarker.index = this.scanner.index; + this.lastMarker.line = this.scanner.lineNumber; + this.lastMarker.column = this.scanner.index - this.scanner.lineStart; + return this.finalize(node, new JSXNode.JSXEmptyExpression()); + }; + JSXParser.prototype.parseJSXExpressionContainer = function () { + var node = this.createJSXNode(); + this.expectJSX('{'); + var expression; + if (this.matchJSX('}')) { + expression = this.parseJSXEmptyExpression(); + this.expectJSX('}'); + } + else { + this.finishJSX(); + expression = this.parseAssignmentExpression(); + this.reenterJSX(); + } + return this.finalize(node, new JSXNode.JSXExpressionContainer(expression)); + }; + JSXParser.prototype.parseJSXChildren = function () { + var children = []; + while (!this.scanner.eof()) { + var node = this.createJSXChildNode(); + var token = this.nextJSXText(); + if (token.start < token.end) { + var raw = this.getTokenRaw(token); + var child = this.finalize(node, new JSXNode.JSXText(token.value, raw)); + children.push(child); + } + if (this.scanner.source[this.scanner.index] === '{') { + var container = this.parseJSXExpressionContainer(); + children.push(container); + } + else { + break; + } + } + return children; + }; + JSXParser.prototype.parseComplexJSXElement = function (el) { + var stack = []; + while (!this.scanner.eof()) { + el.children = el.children.concat(this.parseJSXChildren()); + var node = this.createJSXChildNode(); + var element = this.parseJSXBoundaryElement(); + if (element.type === jsx_syntax_1.JSXSyntax.JSXOpeningElement) { + var opening = element; + if (opening.selfClosing) { + var child = this.finalize(node, new JSXNode.JSXElement(opening, [], null)); + el.children.push(child); + } + else { + stack.push(el); + el = { node: node, opening: opening, closing: null, children: [] }; + } + } + if (element.type === jsx_syntax_1.JSXSyntax.JSXClosingElement) { + el.closing = element; + var open_1 = getQualifiedElementName(el.opening.name); + var close_1 = getQualifiedElementName(el.closing.name); + if (open_1 !== close_1) { + this.tolerateError('Expected corresponding JSX closing tag for %0', open_1); + } + if (stack.length > 0) { + var child = this.finalize(el.node, new JSXNode.JSXElement(el.opening, el.children, el.closing)); + el = stack[stack.length - 1]; + el.children.push(child); + stack.pop(); + } + else { + break; + } + } + } + return el; + }; + JSXParser.prototype.parseJSXElement = function () { + var node = this.createJSXNode(); + var opening = this.parseJSXOpeningElement(); + var children = []; + var closing = null; + if (!opening.selfClosing) { + var el = this.parseComplexJSXElement({ node: node, opening: opening, closing: closing, children: children }); + children = el.children; + closing = el.closing; + } + return this.finalize(node, new JSXNode.JSXElement(opening, children, closing)); + }; + JSXParser.prototype.parseJSXRoot = function () { + // Pop the opening '<' added from the lookahead. + if (this.config.tokens) { + this.tokens.pop(); + } + this.startJSX(); + var element = this.parseJSXElement(); + this.finishJSX(); + return element; + }; + JSXParser.prototype.isStartOfExpression = function () { + return _super.prototype.isStartOfExpression.call(this) || this.match('<'); + }; + return JSXParser; + }(parser_1.Parser)); + exports.JSXParser = JSXParser; + + +/***/ }, +/* 4 */ +/***/ function(module, exports) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + // See also tools/generate-unicode-regex.js. + var Regex = { + // Unicode v8.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\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\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\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\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-\uA7AD\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\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[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\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]|\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]|\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]/, + // Unicode v8.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\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F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D\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\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\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\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-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\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-\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DE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\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]|\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]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\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]/ + }; + exports.Character = { + /* tslint:disable:no-bitwise */ + fromCodePoint: function (cp) { + return (cp < 0x10000) ? String.fromCharCode(cp) : + String.fromCharCode(0xD800 + ((cp - 0x10000) >> 10)) + + String.fromCharCode(0xDC00 + ((cp - 0x10000) & 1023)); + }, + // https://tc39.github.io/ecma262/#sec-white-space + isWhiteSpace: function (cp) { + return (cp === 0x20) || (cp === 0x09) || (cp === 0x0B) || (cp === 0x0C) || (cp === 0xA0) || + (cp >= 0x1680 && [0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(cp) >= 0); + }, + // https://tc39.github.io/ecma262/#sec-line-terminators + isLineTerminator: function (cp) { + return (cp === 0x0A) || (cp === 0x0D) || (cp === 0x2028) || (cp === 0x2029); + }, + // https://tc39.github.io/ecma262/#sec-names-and-keywords + isIdentifierStart: function (cp) { + return (cp === 0x24) || (cp === 0x5F) || + (cp >= 0x41 && cp <= 0x5A) || + (cp >= 0x61 && cp <= 0x7A) || + (cp === 0x5C) || + ((cp >= 0x80) && Regex.NonAsciiIdentifierStart.test(exports.Character.fromCodePoint(cp))); + }, + isIdentifierPart: function (cp) { + return (cp === 0x24) || (cp === 0x5F) || + (cp >= 0x41 && cp <= 0x5A) || + (cp >= 0x61 && cp <= 0x7A) || + (cp >= 0x30 && cp <= 0x39) || + (cp === 0x5C) || + ((cp >= 0x80) && Regex.NonAsciiIdentifierPart.test(exports.Character.fromCodePoint(cp))); + }, + // https://tc39.github.io/ecma262/#sec-literals-numeric-literals + isDecimalDigit: function (cp) { + return (cp >= 0x30 && cp <= 0x39); // 0..9 + }, + isHexDigit: function (cp) { + return (cp >= 0x30 && cp <= 0x39) || + (cp >= 0x41 && cp <= 0x46) || + (cp >= 0x61 && cp <= 0x66); // a..f + }, + isOctalDigit: function (cp) { + return (cp >= 0x30 && cp <= 0x37); // 0..7 + } + }; + + +/***/ }, +/* 5 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var jsx_syntax_1 = __webpack_require__(6); + /* tslint:disable:max-classes-per-file */ + var JSXClosingElement = (function () { + function JSXClosingElement(name) { + this.type = jsx_syntax_1.JSXSyntax.JSXClosingElement; + this.name = name; + } + return JSXClosingElement; + }()); + exports.JSXClosingElement = JSXClosingElement; + var JSXElement = (function () { + function JSXElement(openingElement, children, closingElement) { + this.type = jsx_syntax_1.JSXSyntax.JSXElement; + this.openingElement = openingElement; + this.children = children; + this.closingElement = closingElement; + } + return JSXElement; + }()); + exports.JSXElement = JSXElement; + var JSXEmptyExpression = (function () { + function JSXEmptyExpression() { + this.type = jsx_syntax_1.JSXSyntax.JSXEmptyExpression; + } + return JSXEmptyExpression; + }()); + exports.JSXEmptyExpression = JSXEmptyExpression; + var JSXExpressionContainer = (function () { + function JSXExpressionContainer(expression) { + this.type = jsx_syntax_1.JSXSyntax.JSXExpressionContainer; + this.expression = expression; + } + return JSXExpressionContainer; + }()); + exports.JSXExpressionContainer = JSXExpressionContainer; + var JSXIdentifier = (function () { + function JSXIdentifier(name) { + this.type = jsx_syntax_1.JSXSyntax.JSXIdentifier; + this.name = name; + } + return JSXIdentifier; + }()); + exports.JSXIdentifier = JSXIdentifier; + var JSXMemberExpression = (function () { + function JSXMemberExpression(object, property) { + this.type = jsx_syntax_1.JSXSyntax.JSXMemberExpression; + this.object = object; + this.property = property; + } + return JSXMemberExpression; + }()); + exports.JSXMemberExpression = JSXMemberExpression; + var JSXAttribute = (function () { + function JSXAttribute(name, value) { + this.type = jsx_syntax_1.JSXSyntax.JSXAttribute; + this.name = name; + this.value = value; + } + return JSXAttribute; + }()); + exports.JSXAttribute = JSXAttribute; + var JSXNamespacedName = (function () { + function JSXNamespacedName(namespace, name) { + this.type = jsx_syntax_1.JSXSyntax.JSXNamespacedName; + this.namespace = namespace; + this.name = name; + } + return JSXNamespacedName; + }()); + exports.JSXNamespacedName = JSXNamespacedName; + var JSXOpeningElement = (function () { + function JSXOpeningElement(name, selfClosing, attributes) { + this.type = jsx_syntax_1.JSXSyntax.JSXOpeningElement; + this.name = name; + this.selfClosing = selfClosing; + this.attributes = attributes; + } + return JSXOpeningElement; + }()); + exports.JSXOpeningElement = JSXOpeningElement; + var JSXSpreadAttribute = (function () { + function JSXSpreadAttribute(argument) { + this.type = jsx_syntax_1.JSXSyntax.JSXSpreadAttribute; + this.argument = argument; + } + return JSXSpreadAttribute; + }()); + exports.JSXSpreadAttribute = JSXSpreadAttribute; + var JSXText = (function () { + function JSXText(value, raw) { + this.type = jsx_syntax_1.JSXSyntax.JSXText; + this.value = value; + this.raw = raw; + } + return JSXText; + }()); + exports.JSXText = JSXText; + + +/***/ }, +/* 6 */ +/***/ function(module, exports) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JSXSyntax = { + JSXAttribute: 'JSXAttribute', + JSXClosingElement: 'JSXClosingElement', + JSXElement: 'JSXElement', + JSXEmptyExpression: 'JSXEmptyExpression', + JSXExpressionContainer: 'JSXExpressionContainer', + JSXIdentifier: 'JSXIdentifier', + JSXMemberExpression: 'JSXMemberExpression', + JSXNamespacedName: 'JSXNamespacedName', + JSXOpeningElement: 'JSXOpeningElement', + JSXSpreadAttribute: 'JSXSpreadAttribute', + JSXText: 'JSXText' + }; + + +/***/ }, +/* 7 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var syntax_1 = __webpack_require__(2); + /* tslint:disable:max-classes-per-file */ + var ArrayExpression = (function () { + function ArrayExpression(elements) { + this.type = syntax_1.Syntax.ArrayExpression; + this.elements = elements; + } + return ArrayExpression; + }()); + exports.ArrayExpression = ArrayExpression; + var ArrayPattern = (function () { + function ArrayPattern(elements) { + this.type = syntax_1.Syntax.ArrayPattern; + this.elements = elements; + } + return ArrayPattern; + }()); + exports.ArrayPattern = ArrayPattern; + var ArrowFunctionExpression = (function () { + function ArrowFunctionExpression(params, body, expression) { + this.type = syntax_1.Syntax.ArrowFunctionExpression; + this.id = null; + this.params = params; + this.body = body; + this.generator = false; + this.expression = expression; + this.async = false; + } + return ArrowFunctionExpression; + }()); + exports.ArrowFunctionExpression = ArrowFunctionExpression; + var AssignmentExpression = (function () { + function AssignmentExpression(operator, left, right) { + this.type = syntax_1.Syntax.AssignmentExpression; + this.operator = operator; + this.left = left; + this.right = right; + } + return AssignmentExpression; + }()); + exports.AssignmentExpression = AssignmentExpression; + var AssignmentPattern = (function () { + function AssignmentPattern(left, right) { + this.type = syntax_1.Syntax.AssignmentPattern; + this.left = left; + this.right = right; + } + return AssignmentPattern; + }()); + exports.AssignmentPattern = AssignmentPattern; + var AsyncArrowFunctionExpression = (function () { + function AsyncArrowFunctionExpression(params, body, expression) { + this.type = syntax_1.Syntax.ArrowFunctionExpression; + this.id = null; + this.params = params; + this.body = body; + this.generator = false; + this.expression = expression; + this.async = true; + } + return AsyncArrowFunctionExpression; + }()); + exports.AsyncArrowFunctionExpression = AsyncArrowFunctionExpression; + var AsyncFunctionDeclaration = (function () { + function AsyncFunctionDeclaration(id, params, body) { + this.type = syntax_1.Syntax.FunctionDeclaration; + this.id = id; + this.params = params; + this.body = body; + this.generator = false; + this.expression = false; + this.async = true; + } + return AsyncFunctionDeclaration; + }()); + exports.AsyncFunctionDeclaration = AsyncFunctionDeclaration; + var AsyncFunctionExpression = (function () { + function AsyncFunctionExpression(id, params, body) { + this.type = syntax_1.Syntax.FunctionExpression; + this.id = id; + this.params = params; + this.body = body; + this.generator = false; + this.expression = false; + this.async = true; + } + return AsyncFunctionExpression; + }()); + exports.AsyncFunctionExpression = AsyncFunctionExpression; + var AwaitExpression = (function () { + function AwaitExpression(argument) { + this.type = syntax_1.Syntax.AwaitExpression; + this.argument = argument; + } + return AwaitExpression; + }()); + exports.AwaitExpression = AwaitExpression; + var BinaryExpression = (function () { + function BinaryExpression(operator, left, right) { + var logical = (operator === '||' || operator === '&&'); + this.type = logical ? syntax_1.Syntax.LogicalExpression : syntax_1.Syntax.BinaryExpression; + this.operator = operator; + this.left = left; + this.right = right; + } + return BinaryExpression; + }()); + exports.BinaryExpression = BinaryExpression; + var BlockStatement = (function () { + function BlockStatement(body) { + this.type = syntax_1.Syntax.BlockStatement; + this.body = body; + } + return BlockStatement; + }()); + exports.BlockStatement = BlockStatement; + var BreakStatement = (function () { + function BreakStatement(label) { + this.type = syntax_1.Syntax.BreakStatement; + this.label = label; + } + return BreakStatement; + }()); + exports.BreakStatement = BreakStatement; + var CallExpression = (function () { + function CallExpression(callee, args) { + this.type = syntax_1.Syntax.CallExpression; + this.callee = callee; + this.arguments = args; + } + return CallExpression; + }()); + exports.CallExpression = CallExpression; + var CatchClause = (function () { + function CatchClause(param, body) { + this.type = syntax_1.Syntax.CatchClause; + this.param = param; + this.body = body; + } + return CatchClause; + }()); + exports.CatchClause = CatchClause; + var ClassBody = (function () { + function ClassBody(body) { + this.type = syntax_1.Syntax.ClassBody; + this.body = body; + } + return ClassBody; + }()); + exports.ClassBody = ClassBody; + var ClassDeclaration = (function () { + function ClassDeclaration(id, superClass, body) { + this.type = syntax_1.Syntax.ClassDeclaration; + this.id = id; + this.superClass = superClass; + this.body = body; + } + return ClassDeclaration; + }()); + exports.ClassDeclaration = ClassDeclaration; + var ClassExpression = (function () { + function ClassExpression(id, superClass, body) { + this.type = syntax_1.Syntax.ClassExpression; + this.id = id; + this.superClass = superClass; + this.body = body; + } + return ClassExpression; + }()); + exports.ClassExpression = ClassExpression; + var ComputedMemberExpression = (function () { + function ComputedMemberExpression(object, property) { + this.type = syntax_1.Syntax.MemberExpression; + this.computed = true; + this.object = object; + this.property = property; + } + return ComputedMemberExpression; + }()); + exports.ComputedMemberExpression = ComputedMemberExpression; + var ConditionalExpression = (function () { + function ConditionalExpression(test, consequent, alternate) { + this.type = syntax_1.Syntax.ConditionalExpression; + this.test = test; + this.consequent = consequent; + this.alternate = alternate; + } + return ConditionalExpression; + }()); + exports.ConditionalExpression = ConditionalExpression; + var ContinueStatement = (function () { + function ContinueStatement(label) { + this.type = syntax_1.Syntax.ContinueStatement; + this.label = label; + } + return ContinueStatement; + }()); + exports.ContinueStatement = ContinueStatement; + var DebuggerStatement = (function () { + function DebuggerStatement() { + this.type = syntax_1.Syntax.DebuggerStatement; + } + return DebuggerStatement; + }()); + exports.DebuggerStatement = DebuggerStatement; + var Directive = (function () { + function Directive(expression, directive) { + this.type = syntax_1.Syntax.ExpressionStatement; + this.expression = expression; + this.directive = directive; + } + return Directive; + }()); + exports.Directive = Directive; + var DoWhileStatement = (function () { + function DoWhileStatement(body, test) { + this.type = syntax_1.Syntax.DoWhileStatement; + this.body = body; + this.test = test; + } + return DoWhileStatement; + }()); + exports.DoWhileStatement = DoWhileStatement; + var EmptyStatement = (function () { + function EmptyStatement() { + this.type = syntax_1.Syntax.EmptyStatement; + } + return EmptyStatement; + }()); + exports.EmptyStatement = EmptyStatement; + var ExportAllDeclaration = (function () { + function ExportAllDeclaration(source) { + this.type = syntax_1.Syntax.ExportAllDeclaration; + this.source = source; + } + return ExportAllDeclaration; + }()); + exports.ExportAllDeclaration = ExportAllDeclaration; + var ExportDefaultDeclaration = (function () { + function ExportDefaultDeclaration(declaration) { + this.type = syntax_1.Syntax.ExportDefaultDeclaration; + this.declaration = declaration; + } + return ExportDefaultDeclaration; + }()); + exports.ExportDefaultDeclaration = ExportDefaultDeclaration; + var ExportNamedDeclaration = (function () { + function ExportNamedDeclaration(declaration, specifiers, source) { + this.type = syntax_1.Syntax.ExportNamedDeclaration; + this.declaration = declaration; + this.specifiers = specifiers; + this.source = source; + } + return ExportNamedDeclaration; + }()); + exports.ExportNamedDeclaration = ExportNamedDeclaration; + var ExportSpecifier = (function () { + function ExportSpecifier(local, exported) { + this.type = syntax_1.Syntax.ExportSpecifier; + this.exported = exported; + this.local = local; + } + return ExportSpecifier; + }()); + exports.ExportSpecifier = ExportSpecifier; + var ExpressionStatement = (function () { + function ExpressionStatement(expression) { + this.type = syntax_1.Syntax.ExpressionStatement; + this.expression = expression; + } + return ExpressionStatement; + }()); + exports.ExpressionStatement = ExpressionStatement; + var ForInStatement = (function () { + function ForInStatement(left, right, body) { + this.type = syntax_1.Syntax.ForInStatement; + this.left = left; + this.right = right; + this.body = body; + this.each = false; + } + return ForInStatement; + }()); + exports.ForInStatement = ForInStatement; + var ForOfStatement = (function () { + function ForOfStatement(left, right, body) { + this.type = syntax_1.Syntax.ForOfStatement; + this.left = left; + this.right = right; + this.body = body; + } + return ForOfStatement; + }()); + exports.ForOfStatement = ForOfStatement; + var ForStatement = (function () { + function ForStatement(init, test, update, body) { + this.type = syntax_1.Syntax.ForStatement; + this.init = init; + this.test = test; + this.update = update; + this.body = body; + } + return ForStatement; + }()); + exports.ForStatement = ForStatement; + var FunctionDeclaration = (function () { + function FunctionDeclaration(id, params, body, generator) { + this.type = syntax_1.Syntax.FunctionDeclaration; + this.id = id; + this.params = params; + this.body = body; + this.generator = generator; + this.expression = false; + this.async = false; + } + return FunctionDeclaration; + }()); + exports.FunctionDeclaration = FunctionDeclaration; + var FunctionExpression = (function () { + function FunctionExpression(id, params, body, generator) { + this.type = syntax_1.Syntax.FunctionExpression; + this.id = id; + this.params = params; + this.body = body; + this.generator = generator; + this.expression = false; + this.async = false; + } + return FunctionExpression; + }()); + exports.FunctionExpression = FunctionExpression; + var Identifier = (function () { + function Identifier(name) { + this.type = syntax_1.Syntax.Identifier; + this.name = name; + } + return Identifier; + }()); + exports.Identifier = Identifier; + var IfStatement = (function () { + function IfStatement(test, consequent, alternate) { + this.type = syntax_1.Syntax.IfStatement; + this.test = test; + this.consequent = consequent; + this.alternate = alternate; + } + return IfStatement; + }()); + exports.IfStatement = IfStatement; + var ImportDeclaration = (function () { + function ImportDeclaration(specifiers, source) { + this.type = syntax_1.Syntax.ImportDeclaration; + this.specifiers = specifiers; + this.source = source; + } + return ImportDeclaration; + }()); + exports.ImportDeclaration = ImportDeclaration; + var ImportDefaultSpecifier = (function () { + function ImportDefaultSpecifier(local) { + this.type = syntax_1.Syntax.ImportDefaultSpecifier; + this.local = local; + } + return ImportDefaultSpecifier; + }()); + exports.ImportDefaultSpecifier = ImportDefaultSpecifier; + var ImportNamespaceSpecifier = (function () { + function ImportNamespaceSpecifier(local) { + this.type = syntax_1.Syntax.ImportNamespaceSpecifier; + this.local = local; + } + return ImportNamespaceSpecifier; + }()); + exports.ImportNamespaceSpecifier = ImportNamespaceSpecifier; + var ImportSpecifier = (function () { + function ImportSpecifier(local, imported) { + this.type = syntax_1.Syntax.ImportSpecifier; + this.local = local; + this.imported = imported; + } + return ImportSpecifier; + }()); + exports.ImportSpecifier = ImportSpecifier; + var LabeledStatement = (function () { + function LabeledStatement(label, body) { + this.type = syntax_1.Syntax.LabeledStatement; + this.label = label; + this.body = body; + } + return LabeledStatement; + }()); + exports.LabeledStatement = LabeledStatement; + var Literal = (function () { + function Literal(value, raw) { + this.type = syntax_1.Syntax.Literal; + this.value = value; + this.raw = raw; + } + return Literal; + }()); + exports.Literal = Literal; + var MetaProperty = (function () { + function MetaProperty(meta, property) { + this.type = syntax_1.Syntax.MetaProperty; + this.meta = meta; + this.property = property; + } + return MetaProperty; + }()); + exports.MetaProperty = MetaProperty; + var MethodDefinition = (function () { + function MethodDefinition(key, computed, value, kind, isStatic) { + this.type = syntax_1.Syntax.MethodDefinition; + this.key = key; + this.computed = computed; + this.value = value; + this.kind = kind; + this.static = isStatic; + } + return MethodDefinition; + }()); + exports.MethodDefinition = MethodDefinition; + var Module = (function () { + function Module(body) { + this.type = syntax_1.Syntax.Program; + this.body = body; + this.sourceType = 'module'; + } + return Module; + }()); + exports.Module = Module; + var NewExpression = (function () { + function NewExpression(callee, args) { + this.type = syntax_1.Syntax.NewExpression; + this.callee = callee; + this.arguments = args; + } + return NewExpression; + }()); + exports.NewExpression = NewExpression; + var ObjectExpression = (function () { + function ObjectExpression(properties) { + this.type = syntax_1.Syntax.ObjectExpression; + this.properties = properties; + } + return ObjectExpression; + }()); + exports.ObjectExpression = ObjectExpression; + var ObjectPattern = (function () { + function ObjectPattern(properties) { + this.type = syntax_1.Syntax.ObjectPattern; + this.properties = properties; + } + return ObjectPattern; + }()); + exports.ObjectPattern = ObjectPattern; + var Property = (function () { + function Property(kind, key, computed, value, method, shorthand) { + this.type = syntax_1.Syntax.Property; + this.key = key; + this.computed = computed; + this.value = value; + this.kind = kind; + this.method = method; + this.shorthand = shorthand; + } + return Property; + }()); + exports.Property = Property; + var RegexLiteral = (function () { + function RegexLiteral(value, raw, pattern, flags) { + this.type = syntax_1.Syntax.Literal; + this.value = value; + this.raw = raw; + this.regex = { pattern: pattern, flags: flags }; + } + return RegexLiteral; + }()); + exports.RegexLiteral = RegexLiteral; + var RestElement = (function () { + function RestElement(argument) { + this.type = syntax_1.Syntax.RestElement; + this.argument = argument; + } + return RestElement; + }()); + exports.RestElement = RestElement; + var ReturnStatement = (function () { + function ReturnStatement(argument) { + this.type = syntax_1.Syntax.ReturnStatement; + this.argument = argument; + } + return ReturnStatement; + }()); + exports.ReturnStatement = ReturnStatement; + var Script = (function () { + function Script(body) { + this.type = syntax_1.Syntax.Program; + this.body = body; + this.sourceType = 'script'; + } + return Script; + }()); + exports.Script = Script; + var SequenceExpression = (function () { + function SequenceExpression(expressions) { + this.type = syntax_1.Syntax.SequenceExpression; + this.expressions = expressions; + } + return SequenceExpression; + }()); + exports.SequenceExpression = SequenceExpression; + var SpreadElement = (function () { + function SpreadElement(argument) { + this.type = syntax_1.Syntax.SpreadElement; + this.argument = argument; + } + return SpreadElement; + }()); + exports.SpreadElement = SpreadElement; + var StaticMemberExpression = (function () { + function StaticMemberExpression(object, property) { + this.type = syntax_1.Syntax.MemberExpression; + this.computed = false; + this.object = object; + this.property = property; + } + return StaticMemberExpression; + }()); + exports.StaticMemberExpression = StaticMemberExpression; + var Super = (function () { + function Super() { + this.type = syntax_1.Syntax.Super; + } + return Super; + }()); + exports.Super = Super; + var SwitchCase = (function () { + function SwitchCase(test, consequent) { + this.type = syntax_1.Syntax.SwitchCase; + this.test = test; + this.consequent = consequent; + } + return SwitchCase; + }()); + exports.SwitchCase = SwitchCase; + var SwitchStatement = (function () { + function SwitchStatement(discriminant, cases) { + this.type = syntax_1.Syntax.SwitchStatement; + this.discriminant = discriminant; + this.cases = cases; + } + return SwitchStatement; + }()); + exports.SwitchStatement = SwitchStatement; + var TaggedTemplateExpression = (function () { + function TaggedTemplateExpression(tag, quasi) { + this.type = syntax_1.Syntax.TaggedTemplateExpression; + this.tag = tag; + this.quasi = quasi; + } + return TaggedTemplateExpression; + }()); + exports.TaggedTemplateExpression = TaggedTemplateExpression; + var TemplateElement = (function () { + function TemplateElement(value, tail) { + this.type = syntax_1.Syntax.TemplateElement; + this.value = value; + this.tail = tail; + } + return TemplateElement; + }()); + exports.TemplateElement = TemplateElement; + var TemplateLiteral = (function () { + function TemplateLiteral(quasis, expressions) { + this.type = syntax_1.Syntax.TemplateLiteral; + this.quasis = quasis; + this.expressions = expressions; + } + return TemplateLiteral; + }()); + exports.TemplateLiteral = TemplateLiteral; + var ThisExpression = (function () { + function ThisExpression() { + this.type = syntax_1.Syntax.ThisExpression; + } + return ThisExpression; + }()); + exports.ThisExpression = ThisExpression; + var ThrowStatement = (function () { + function ThrowStatement(argument) { + this.type = syntax_1.Syntax.ThrowStatement; + this.argument = argument; + } + return ThrowStatement; + }()); + exports.ThrowStatement = ThrowStatement; + var TryStatement = (function () { + function TryStatement(block, handler, finalizer) { + this.type = syntax_1.Syntax.TryStatement; + this.block = block; + this.handler = handler; + this.finalizer = finalizer; + } + return TryStatement; + }()); + exports.TryStatement = TryStatement; + var UnaryExpression = (function () { + function UnaryExpression(operator, argument) { + this.type = syntax_1.Syntax.UnaryExpression; + this.operator = operator; + this.argument = argument; + this.prefix = true; + } + return UnaryExpression; + }()); + exports.UnaryExpression = UnaryExpression; + var UpdateExpression = (function () { + function UpdateExpression(operator, argument, prefix) { + this.type = syntax_1.Syntax.UpdateExpression; + this.operator = operator; + this.argument = argument; + this.prefix = prefix; + } + return UpdateExpression; + }()); + exports.UpdateExpression = UpdateExpression; + var VariableDeclaration = (function () { + function VariableDeclaration(declarations, kind) { + this.type = syntax_1.Syntax.VariableDeclaration; + this.declarations = declarations; + this.kind = kind; + } + return VariableDeclaration; + }()); + exports.VariableDeclaration = VariableDeclaration; + var VariableDeclarator = (function () { + function VariableDeclarator(id, init) { + this.type = syntax_1.Syntax.VariableDeclarator; + this.id = id; + this.init = init; + } + return VariableDeclarator; + }()); + exports.VariableDeclarator = VariableDeclarator; + var WhileStatement = (function () { + function WhileStatement(test, body) { + this.type = syntax_1.Syntax.WhileStatement; + this.test = test; + this.body = body; + } + return WhileStatement; + }()); + exports.WhileStatement = WhileStatement; + var WithStatement = (function () { + function WithStatement(object, body) { + this.type = syntax_1.Syntax.WithStatement; + this.object = object; + this.body = body; + } + return WithStatement; + }()); + exports.WithStatement = WithStatement; + var YieldExpression = (function () { + function YieldExpression(argument, delegate) { + this.type = syntax_1.Syntax.YieldExpression; + this.argument = argument; + this.delegate = delegate; + } + return YieldExpression; + }()); + exports.YieldExpression = YieldExpression; + + +/***/ }, +/* 8 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var assert_1 = __webpack_require__(9); + var error_handler_1 = __webpack_require__(10); + var messages_1 = __webpack_require__(11); + var Node = __webpack_require__(7); + var scanner_1 = __webpack_require__(12); + var syntax_1 = __webpack_require__(2); + var token_1 = __webpack_require__(13); + var ArrowParameterPlaceHolder = 'ArrowParameterPlaceHolder'; + var Parser = (function () { + function Parser(code, options, delegate) { + if (options === void 0) { options = {}; } + this.config = { + range: (typeof options.range === 'boolean') && options.range, + loc: (typeof options.loc === 'boolean') && options.loc, + source: null, + tokens: (typeof options.tokens === 'boolean') && options.tokens, + comment: (typeof options.comment === 'boolean') && options.comment, + tolerant: (typeof options.tolerant === 'boolean') && options.tolerant + }; + if (this.config.loc && options.source && options.source !== null) { + this.config.source = String(options.source); + } + this.delegate = delegate; + this.errorHandler = new error_handler_1.ErrorHandler(); + this.errorHandler.tolerant = this.config.tolerant; + this.scanner = new scanner_1.Scanner(code, this.errorHandler); + this.scanner.trackComment = this.config.comment; + this.operatorPrecedence = { + ')': 0, + ';': 0, + ',': 0, + '=': 0, + ']': 0, + '||': 1, + '&&': 2, + '|': 3, + '^': 4, + '&': 5, + '==': 6, + '!=': 6, + '===': 6, + '!==': 6, + '<': 7, + '>': 7, + '<=': 7, + '>=': 7, + '<<': 8, + '>>': 8, + '>>>': 8, + '+': 9, + '-': 9, + '*': 11, + '/': 11, + '%': 11 + }; + this.lookahead = { + type: 2 /* EOF */, + value: '', + lineNumber: this.scanner.lineNumber, + lineStart: 0, + start: 0, + end: 0 + }; + this.hasLineTerminator = false; + this.context = { + isModule: false, + await: false, + allowIn: true, + allowStrictDirective: true, + allowYield: true, + firstCoverInitializedNameError: null, + isAssignmentTarget: false, + isBindingElement: false, + inFunctionBody: false, + inIteration: false, + inSwitch: false, + labelSet: {}, + strict: false + }; + this.tokens = []; + this.startMarker = { + index: 0, + line: this.scanner.lineNumber, + column: 0 + }; + this.lastMarker = { + index: 0, + line: this.scanner.lineNumber, + column: 0 + }; + this.nextToken(); + this.lastMarker = { + index: this.scanner.index, + line: this.scanner.lineNumber, + column: this.scanner.index - this.scanner.lineStart + }; + } + Parser.prototype.throwError = function (messageFormat) { + var values = []; + for (var _i = 1; _i < arguments.length; _i++) { + values[_i - 1] = arguments[_i]; + } + var args = Array.prototype.slice.call(arguments, 1); + var msg = messageFormat.replace(/%(\d)/g, function (whole, idx) { + assert_1.assert(idx < args.length, 'Message reference must be in range'); + return args[idx]; + }); + var index = this.lastMarker.index; + var line = this.lastMarker.line; + var column = this.lastMarker.column + 1; + throw this.errorHandler.createError(index, line, column, msg); + }; + Parser.prototype.tolerateError = function (messageFormat) { + var values = []; + for (var _i = 1; _i < arguments.length; _i++) { + values[_i - 1] = arguments[_i]; + } + var args = Array.prototype.slice.call(arguments, 1); + var msg = messageFormat.replace(/%(\d)/g, function (whole, idx) { + assert_1.assert(idx < args.length, 'Message reference must be in range'); + return args[idx]; + }); + var index = this.lastMarker.index; + var line = this.scanner.lineNumber; + var column = this.lastMarker.column + 1; + this.errorHandler.tolerateError(index, line, column, msg); + }; + // Throw an exception because of the token. + Parser.prototype.unexpectedTokenError = function (token, message) { + var msg = message || messages_1.Messages.UnexpectedToken; + var value; + if (token) { + if (!message) { + msg = (token.type === 2 /* EOF */) ? messages_1.Messages.UnexpectedEOS : + (token.type === 3 /* Identifier */) ? messages_1.Messages.UnexpectedIdentifier : + (token.type === 6 /* NumericLiteral */) ? messages_1.Messages.UnexpectedNumber : + (token.type === 8 /* StringLiteral */) ? messages_1.Messages.UnexpectedString : + (token.type === 10 /* Template */) ? messages_1.Messages.UnexpectedTemplate : + messages_1.Messages.UnexpectedToken; + if (token.type === 4 /* Keyword */) { + if (this.scanner.isFutureReservedWord(token.value)) { + msg = messages_1.Messages.UnexpectedReserved; + } + else if (this.context.strict && this.scanner.isStrictModeReservedWord(token.value)) { + msg = messages_1.Messages.StrictReservedWord; + } + } + } + value = token.value; + } + else { + value = 'ILLEGAL'; + } + msg = msg.replace('%0', value); + if (token && typeof token.lineNumber === 'number') { + var index = token.start; + var line = token.lineNumber; + var lastMarkerLineStart = this.lastMarker.index - this.lastMarker.column; + var column = token.start - lastMarkerLineStart + 1; + return this.errorHandler.createError(index, line, column, msg); + } + else { + var index = this.lastMarker.index; + var line = this.lastMarker.line; + var column = this.lastMarker.column + 1; + return this.errorHandler.createError(index, line, column, msg); + } + }; + Parser.prototype.throwUnexpectedToken = function (token, message) { + throw this.unexpectedTokenError(token, message); + }; + Parser.prototype.tolerateUnexpectedToken = function (token, message) { + this.errorHandler.tolerate(this.unexpectedTokenError(token, message)); + }; + Parser.prototype.collectComments = function () { + if (!this.config.comment) { + this.scanner.scanComments(); + } + else { + var comments = this.scanner.scanComments(); + if (comments.length > 0 && this.delegate) { + for (var i = 0; i < comments.length; ++i) { + var e = comments[i]; + var node = void 0; + node = { + type: e.multiLine ? 'BlockComment' : 'LineComment', + value: this.scanner.source.slice(e.slice[0], e.slice[1]) + }; + if (this.config.range) { + node.range = e.range; + } + if (this.config.loc) { + node.loc = e.loc; + } + var metadata = { + start: { + line: e.loc.start.line, + column: e.loc.start.column, + offset: e.range[0] + }, + end: { + line: e.loc.end.line, + column: e.loc.end.column, + offset: e.range[1] + } + }; + this.delegate(node, metadata); + } + } + } + }; + // From internal representation to an external structure + Parser.prototype.getTokenRaw = function (token) { + return this.scanner.source.slice(token.start, token.end); + }; + Parser.prototype.convertToken = function (token) { + var t = { + type: token_1.TokenName[token.type], + value: this.getTokenRaw(token) + }; + if (this.config.range) { + t.range = [token.start, token.end]; + } + if (this.config.loc) { + t.loc = { + start: { + line: this.startMarker.line, + column: this.startMarker.column + }, + end: { + line: this.scanner.lineNumber, + column: this.scanner.index - this.scanner.lineStart + } + }; + } + if (token.type === 9 /* RegularExpression */) { + var pattern = token.pattern; + var flags = token.flags; + t.regex = { pattern: pattern, flags: flags }; + } + return t; + }; + Parser.prototype.nextToken = function () { + var token = this.lookahead; + this.lastMarker.index = this.scanner.index; + this.lastMarker.line = this.scanner.lineNumber; + this.lastMarker.column = this.scanner.index - this.scanner.lineStart; + this.collectComments(); + if (this.scanner.index !== this.startMarker.index) { + this.startMarker.index = this.scanner.index; + this.startMarker.line = this.scanner.lineNumber; + this.startMarker.column = this.scanner.index - this.scanner.lineStart; + } + var next = this.scanner.lex(); + this.hasLineTerminator = (token.lineNumber !== next.lineNumber); + if (next && this.context.strict && next.type === 3 /* Identifier */) { + if (this.scanner.isStrictModeReservedWord(next.value)) { + next.type = 4 /* Keyword */; + } + } + this.lookahead = next; + if (this.config.tokens && next.type !== 2 /* EOF */) { + this.tokens.push(this.convertToken(next)); + } + return token; + }; + Parser.prototype.nextRegexToken = function () { + this.collectComments(); + var token = this.scanner.scanRegExp(); + if (this.config.tokens) { + // Pop the previous token, '/' or '/=' + // This is added from the lookahead token. + this.tokens.pop(); + this.tokens.push(this.convertToken(token)); + } + // Prime the next lookahead. + this.lookahead = token; + this.nextToken(); + return token; + }; + Parser.prototype.createNode = function () { + return { + index: this.startMarker.index, + line: this.startMarker.line, + column: this.startMarker.column + }; + }; + Parser.prototype.startNode = function (token, lastLineStart) { + if (lastLineStart === void 0) { lastLineStart = 0; } + var column = token.start - token.lineStart; + var line = token.lineNumber; + if (column < 0) { + column += lastLineStart; + line--; + } + return { + index: token.start, + line: line, + column: column + }; + }; + Parser.prototype.finalize = function (marker, node) { + if (this.config.range) { + node.range = [marker.index, this.lastMarker.index]; + } + if (this.config.loc) { + node.loc = { + start: { + line: marker.line, + column: marker.column, + }, + end: { + line: this.lastMarker.line, + column: this.lastMarker.column + } + }; + if (this.config.source) { + node.loc.source = this.config.source; + } + } + if (this.delegate) { + var metadata = { + start: { + line: marker.line, + column: marker.column, + offset: marker.index + }, + end: { + line: this.lastMarker.line, + column: this.lastMarker.column, + offset: this.lastMarker.index + } + }; + this.delegate(node, metadata); + } + return node; + }; + // Expect the next token to match the specified punctuator. + // If not, an exception will be thrown. + Parser.prototype.expect = function (value) { + var token = this.nextToken(); + if (token.type !== 7 /* Punctuator */ || token.value !== value) { + this.throwUnexpectedToken(token); + } + }; + // Quietly expect a comma when in tolerant mode, otherwise delegates to expect(). + Parser.prototype.expectCommaSeparator = function () { + if (this.config.tolerant) { + var token = this.lookahead; + if (token.type === 7 /* Punctuator */ && token.value === ',') { + this.nextToken(); + } + else if (token.type === 7 /* Punctuator */ && token.value === ';') { + this.nextToken(); + this.tolerateUnexpectedToken(token); + } + else { + this.tolerateUnexpectedToken(token, messages_1.Messages.UnexpectedToken); + } + } + else { + this.expect(','); + } + }; + // Expect the next token to match the specified keyword. + // If not, an exception will be thrown. + Parser.prototype.expectKeyword = function (keyword) { + var token = this.nextToken(); + if (token.type !== 4 /* Keyword */ || token.value !== keyword) { + this.throwUnexpectedToken(token); + } + }; + // Return true if the next token matches the specified punctuator. + Parser.prototype.match = function (value) { + return this.lookahead.type === 7 /* Punctuator */ && this.lookahead.value === value; + }; + // Return true if the next token matches the specified keyword + Parser.prototype.matchKeyword = function (keyword) { + return this.lookahead.type === 4 /* Keyword */ && this.lookahead.value === keyword; + }; + // Return true if the next token matches the specified contextual keyword + // (where an identifier is sometimes a keyword depending on the context) + Parser.prototype.matchContextualKeyword = function (keyword) { + return this.lookahead.type === 3 /* Identifier */ && this.lookahead.value === keyword; + }; + // Return true if the next token is an assignment operator + Parser.prototype.matchAssign = function () { + if (this.lookahead.type !== 7 /* Punctuator */) { + return false; + } + var op = this.lookahead.value; + return op === '=' || + op === '*=' || + op === '**=' || + op === '/=' || + op === '%=' || + op === '+=' || + op === '-=' || + op === '<<=' || + op === '>>=' || + op === '>>>=' || + op === '&=' || + op === '^=' || + op === '|='; + }; + // Cover grammar support. + // + // When an assignment expression position starts with an left parenthesis, the determination of the type + // of the syntax is to be deferred arbitrarily long until the end of the parentheses pair (plus a lookahead) + // or the first comma. This situation also defers the determination of all the expressions nested in the pair. + // + // There are three productions that can be parsed in a parentheses pair that needs to be determined + // after the outermost pair is closed. They are: + // + // 1. AssignmentExpression + // 2. BindingElements + // 3. AssignmentTargets + // + // In order to avoid exponential backtracking, we use two flags to denote if the production can be + // binding element or assignment target. + // + // The three productions have the relationship: + // + // BindingElements ⊆ AssignmentTargets ⊆ AssignmentExpression + // + // with a single exception that CoverInitializedName when used directly in an Expression, generates + // an early error. Therefore, we need the third state, firstCoverInitializedNameError, to track the + // first usage of CoverInitializedName and report it when we reached the end of the parentheses pair. + // + // isolateCoverGrammar function runs the given parser function with a new cover grammar context, and it does not + // effect the current flags. This means the production the parser parses is only used as an expression. Therefore + // the CoverInitializedName check is conducted. + // + // inheritCoverGrammar function runs the given parse function with a new cover grammar context, and it propagates + // the flags outside of the parser. This means the production the parser parses is used as a part of a potential + // pattern. The CoverInitializedName check is deferred. + Parser.prototype.isolateCoverGrammar = function (parseFunction) { + var previousIsBindingElement = this.context.isBindingElement; + var previousIsAssignmentTarget = this.context.isAssignmentTarget; + var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError; + this.context.isBindingElement = true; + this.context.isAssignmentTarget = true; + this.context.firstCoverInitializedNameError = null; + var result = parseFunction.call(this); + if (this.context.firstCoverInitializedNameError !== null) { + this.throwUnexpectedToken(this.context.firstCoverInitializedNameError); + } + this.context.isBindingElement = previousIsBindingElement; + this.context.isAssignmentTarget = previousIsAssignmentTarget; + this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError; + return result; + }; + Parser.prototype.inheritCoverGrammar = function (parseFunction) { + var previousIsBindingElement = this.context.isBindingElement; + var previousIsAssignmentTarget = this.context.isAssignmentTarget; + var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError; + this.context.isBindingElement = true; + this.context.isAssignmentTarget = true; + this.context.firstCoverInitializedNameError = null; + var result = parseFunction.call(this); + this.context.isBindingElement = this.context.isBindingElement && previousIsBindingElement; + this.context.isAssignmentTarget = this.context.isAssignmentTarget && previousIsAssignmentTarget; + this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError || this.context.firstCoverInitializedNameError; + return result; + }; + Parser.prototype.consumeSemicolon = function () { + if (this.match(';')) { + this.nextToken(); + } + else if (!this.hasLineTerminator) { + if (this.lookahead.type !== 2 /* EOF */ && !this.match('}')) { + this.throwUnexpectedToken(this.lookahead); + } + this.lastMarker.index = this.startMarker.index; + this.lastMarker.line = this.startMarker.line; + this.lastMarker.column = this.startMarker.column; + } + }; + // https://tc39.github.io/ecma262/#sec-primary-expression + Parser.prototype.parsePrimaryExpression = function () { + var node = this.createNode(); + var expr; + var token, raw; + switch (this.lookahead.type) { + case 3 /* Identifier */: + if ((this.context.isModule || this.context.await) && this.lookahead.value === 'await') { + this.tolerateUnexpectedToken(this.lookahead); + } + expr = this.matchAsyncFunction() ? this.parseFunctionExpression() : this.finalize(node, new Node.Identifier(this.nextToken().value)); + break; + case 6 /* NumericLiteral */: + case 8 /* StringLiteral */: + if (this.context.strict && this.lookahead.octal) { + this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.StrictOctalLiteral); + } + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + token = this.nextToken(); + raw = this.getTokenRaw(token); + expr = this.finalize(node, new Node.Literal(token.value, raw)); + break; + case 1 /* BooleanLiteral */: + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + token = this.nextToken(); + raw = this.getTokenRaw(token); + expr = this.finalize(node, new Node.Literal(token.value === 'true', raw)); + break; + case 5 /* NullLiteral */: + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + token = this.nextToken(); + raw = this.getTokenRaw(token); + expr = this.finalize(node, new Node.Literal(null, raw)); + break; + case 10 /* Template */: + expr = this.parseTemplateLiteral(); + break; + case 7 /* Punctuator */: + switch (this.lookahead.value) { + case '(': + this.context.isBindingElement = false; + expr = this.inheritCoverGrammar(this.parseGroupExpression); + break; + case '[': + expr = this.inheritCoverGrammar(this.parseArrayInitializer); + break; + case '{': + expr = this.inheritCoverGrammar(this.parseObjectInitializer); + break; + case '/': + case '/=': + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + this.scanner.index = this.startMarker.index; + token = this.nextRegexToken(); + raw = this.getTokenRaw(token); + expr = this.finalize(node, new Node.RegexLiteral(token.regex, raw, token.pattern, token.flags)); + break; + default: + expr = this.throwUnexpectedToken(this.nextToken()); + } + break; + case 4 /* Keyword */: + if (!this.context.strict && this.context.allowYield && this.matchKeyword('yield')) { + expr = this.parseIdentifierName(); + } + else if (!this.context.strict && this.matchKeyword('let')) { + expr = this.finalize(node, new Node.Identifier(this.nextToken().value)); + } + else { + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + if (this.matchKeyword('function')) { + expr = this.parseFunctionExpression(); + } + else if (this.matchKeyword('this')) { + this.nextToken(); + expr = this.finalize(node, new Node.ThisExpression()); + } + else if (this.matchKeyword('class')) { + expr = this.parseClassExpression(); + } + else { + expr = this.throwUnexpectedToken(this.nextToken()); + } + } + break; + default: + expr = this.throwUnexpectedToken(this.nextToken()); + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-array-initializer + Parser.prototype.parseSpreadElement = function () { + var node = this.createNode(); + this.expect('...'); + var arg = this.inheritCoverGrammar(this.parseAssignmentExpression); + return this.finalize(node, new Node.SpreadElement(arg)); + }; + Parser.prototype.parseArrayInitializer = function () { + var node = this.createNode(); + var elements = []; + this.expect('['); + while (!this.match(']')) { + if (this.match(',')) { + this.nextToken(); + elements.push(null); + } + else if (this.match('...')) { + var element = this.parseSpreadElement(); + if (!this.match(']')) { + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + this.expect(','); + } + elements.push(element); + } + else { + elements.push(this.inheritCoverGrammar(this.parseAssignmentExpression)); + if (!this.match(']')) { + this.expect(','); + } + } + } + this.expect(']'); + return this.finalize(node, new Node.ArrayExpression(elements)); + }; + // https://tc39.github.io/ecma262/#sec-object-initializer + Parser.prototype.parsePropertyMethod = function (params) { + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + var previousStrict = this.context.strict; + var previousAllowStrictDirective = this.context.allowStrictDirective; + this.context.allowStrictDirective = params.simple; + var body = this.isolateCoverGrammar(this.parseFunctionSourceElements); + if (this.context.strict && params.firstRestricted) { + this.tolerateUnexpectedToken(params.firstRestricted, params.message); + } + if (this.context.strict && params.stricted) { + this.tolerateUnexpectedToken(params.stricted, params.message); + } + this.context.strict = previousStrict; + this.context.allowStrictDirective = previousAllowStrictDirective; + return body; + }; + Parser.prototype.parsePropertyMethodFunction = function () { + var isGenerator = false; + var node = this.createNode(); + var previousAllowYield = this.context.allowYield; + this.context.allowYield = true; + var params = this.parseFormalParameters(); + var method = this.parsePropertyMethod(params); + this.context.allowYield = previousAllowYield; + return this.finalize(node, new Node.FunctionExpression(null, params.params, method, isGenerator)); + }; + Parser.prototype.parsePropertyMethodAsyncFunction = function () { + var node = this.createNode(); + var previousAllowYield = this.context.allowYield; + var previousAwait = this.context.await; + this.context.allowYield = false; + this.context.await = true; + var params = this.parseFormalParameters(); + var method = this.parsePropertyMethod(params); + this.context.allowYield = previousAllowYield; + this.context.await = previousAwait; + return this.finalize(node, new Node.AsyncFunctionExpression(null, params.params, method)); + }; + Parser.prototype.parseObjectPropertyKey = function () { + var node = this.createNode(); + var token = this.nextToken(); + var key; + switch (token.type) { + case 8 /* StringLiteral */: + case 6 /* NumericLiteral */: + if (this.context.strict && token.octal) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictOctalLiteral); + } + var raw = this.getTokenRaw(token); + key = this.finalize(node, new Node.Literal(token.value, raw)); + break; + case 3 /* Identifier */: + case 1 /* BooleanLiteral */: + case 5 /* NullLiteral */: + case 4 /* Keyword */: + key = this.finalize(node, new Node.Identifier(token.value)); + break; + case 7 /* Punctuator */: + if (token.value === '[') { + key = this.isolateCoverGrammar(this.parseAssignmentExpression); + this.expect(']'); + } + else { + key = this.throwUnexpectedToken(token); + } + break; + default: + key = this.throwUnexpectedToken(token); + } + return key; + }; + Parser.prototype.isPropertyKey = function (key, value) { + return (key.type === syntax_1.Syntax.Identifier && key.name === value) || + (key.type === syntax_1.Syntax.Literal && key.value === value); + }; + Parser.prototype.parseObjectProperty = function (hasProto) { + var node = this.createNode(); + var token = this.lookahead; + var kind; + var key = null; + var value = null; + var computed = false; + var method = false; + var shorthand = false; + var isAsync = false; + if (token.type === 3 /* Identifier */) { + var id = token.value; + this.nextToken(); + computed = this.match('['); + isAsync = !this.hasLineTerminator && (id === 'async') && + !this.match(':') && !this.match('(') && !this.match('*') && !this.match(','); + key = isAsync ? this.parseObjectPropertyKey() : this.finalize(node, new Node.Identifier(id)); + } + else if (this.match('*')) { + this.nextToken(); + } + else { + computed = this.match('['); + key = this.parseObjectPropertyKey(); + } + var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead); + if (token.type === 3 /* Identifier */ && !isAsync && token.value === 'get' && lookaheadPropertyKey) { + kind = 'get'; + computed = this.match('['); + key = this.parseObjectPropertyKey(); + this.context.allowYield = false; + value = this.parseGetterMethod(); + } + else if (token.type === 3 /* Identifier */ && !isAsync && token.value === 'set' && lookaheadPropertyKey) { + kind = 'set'; + computed = this.match('['); + key = this.parseObjectPropertyKey(); + value = this.parseSetterMethod(); + } + else if (token.type === 7 /* Punctuator */ && token.value === '*' && lookaheadPropertyKey) { + kind = 'init'; + computed = this.match('['); + key = this.parseObjectPropertyKey(); + value = this.parseGeneratorMethod(); + method = true; + } + else { + if (!key) { + this.throwUnexpectedToken(this.lookahead); + } + kind = 'init'; + if (this.match(':') && !isAsync) { + if (!computed && this.isPropertyKey(key, '__proto__')) { + if (hasProto.value) { + this.tolerateError(messages_1.Messages.DuplicateProtoProperty); + } + hasProto.value = true; + } + this.nextToken(); + value = this.inheritCoverGrammar(this.parseAssignmentExpression); + } + else if (this.match('(')) { + value = isAsync ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction(); + method = true; + } + else if (token.type === 3 /* Identifier */) { + var id = this.finalize(node, new Node.Identifier(token.value)); + if (this.match('=')) { + this.context.firstCoverInitializedNameError = this.lookahead; + this.nextToken(); + shorthand = true; + var init = this.isolateCoverGrammar(this.parseAssignmentExpression); + value = this.finalize(node, new Node.AssignmentPattern(id, init)); + } + else { + shorthand = true; + value = id; + } + } + else { + this.throwUnexpectedToken(this.nextToken()); + } + } + return this.finalize(node, new Node.Property(kind, key, computed, value, method, shorthand)); + }; + Parser.prototype.parseObjectInitializer = function () { + var node = this.createNode(); + this.expect('{'); + var properties = []; + var hasProto = { value: false }; + while (!this.match('}')) { + properties.push(this.parseObjectProperty(hasProto)); + if (!this.match('}')) { + this.expectCommaSeparator(); + } + } + this.expect('}'); + return this.finalize(node, new Node.ObjectExpression(properties)); + }; + // https://tc39.github.io/ecma262/#sec-template-literals + Parser.prototype.parseTemplateHead = function () { + assert_1.assert(this.lookahead.head, 'Template literal must start with a template head'); + var node = this.createNode(); + var token = this.nextToken(); + var raw = token.value; + var cooked = token.cooked; + return this.finalize(node, new Node.TemplateElement({ raw: raw, cooked: cooked }, token.tail)); + }; + Parser.prototype.parseTemplateElement = function () { + if (this.lookahead.type !== 10 /* Template */) { + this.throwUnexpectedToken(); + } + var node = this.createNode(); + var token = this.nextToken(); + var raw = token.value; + var cooked = token.cooked; + return this.finalize(node, new Node.TemplateElement({ raw: raw, cooked: cooked }, token.tail)); + }; + Parser.prototype.parseTemplateLiteral = function () { + var node = this.createNode(); + var expressions = []; + var quasis = []; + var quasi = this.parseTemplateHead(); + quasis.push(quasi); + while (!quasi.tail) { + expressions.push(this.parseExpression()); + quasi = this.parseTemplateElement(); + quasis.push(quasi); + } + return this.finalize(node, new Node.TemplateLiteral(quasis, expressions)); + }; + // https://tc39.github.io/ecma262/#sec-grouping-operator + Parser.prototype.reinterpretExpressionAsPattern = function (expr) { + switch (expr.type) { + case syntax_1.Syntax.Identifier: + case syntax_1.Syntax.MemberExpression: + case syntax_1.Syntax.RestElement: + case syntax_1.Syntax.AssignmentPattern: + break; + case syntax_1.Syntax.SpreadElement: + expr.type = syntax_1.Syntax.RestElement; + this.reinterpretExpressionAsPattern(expr.argument); + break; + case syntax_1.Syntax.ArrayExpression: + expr.type = syntax_1.Syntax.ArrayPattern; + for (var i = 0; i < expr.elements.length; i++) { + if (expr.elements[i] !== null) { + this.reinterpretExpressionAsPattern(expr.elements[i]); + } + } + break; + case syntax_1.Syntax.ObjectExpression: + expr.type = syntax_1.Syntax.ObjectPattern; + for (var i = 0; i < expr.properties.length; i++) { + this.reinterpretExpressionAsPattern(expr.properties[i].value); + } + break; + case syntax_1.Syntax.AssignmentExpression: + expr.type = syntax_1.Syntax.AssignmentPattern; + delete expr.operator; + this.reinterpretExpressionAsPattern(expr.left); + break; + default: + // Allow other node type for tolerant parsing. + break; + } + }; + Parser.prototype.parseGroupExpression = function () { + var expr; + this.expect('('); + if (this.match(')')) { + this.nextToken(); + if (!this.match('=>')) { + this.expect('=>'); + } + expr = { + type: ArrowParameterPlaceHolder, + params: [], + async: false + }; + } + else { + var startToken = this.lookahead; + var params = []; + if (this.match('...')) { + expr = this.parseRestElement(params); + this.expect(')'); + if (!this.match('=>')) { + this.expect('=>'); + } + expr = { + type: ArrowParameterPlaceHolder, + params: [expr], + async: false + }; + } + else { + var arrow = false; + this.context.isBindingElement = true; + expr = this.inheritCoverGrammar(this.parseAssignmentExpression); + if (this.match(',')) { + var expressions = []; + this.context.isAssignmentTarget = false; + expressions.push(expr); + while (this.lookahead.type !== 2 /* EOF */) { + if (!this.match(',')) { + break; + } + this.nextToken(); + if (this.match(')')) { + this.nextToken(); + for (var i = 0; i < expressions.length; i++) { + this.reinterpretExpressionAsPattern(expressions[i]); + } + arrow = true; + expr = { + type: ArrowParameterPlaceHolder, + params: expressions, + async: false + }; + } + else if (this.match('...')) { + if (!this.context.isBindingElement) { + this.throwUnexpectedToken(this.lookahead); + } + expressions.push(this.parseRestElement(params)); + this.expect(')'); + if (!this.match('=>')) { + this.expect('=>'); + } + this.context.isBindingElement = false; + for (var i = 0; i < expressions.length; i++) { + this.reinterpretExpressionAsPattern(expressions[i]); + } + arrow = true; + expr = { + type: ArrowParameterPlaceHolder, + params: expressions, + async: false + }; + } + else { + expressions.push(this.inheritCoverGrammar(this.parseAssignmentExpression)); + } + if (arrow) { + break; + } + } + if (!arrow) { + expr = this.finalize(this.startNode(startToken), new Node.SequenceExpression(expressions)); + } + } + if (!arrow) { + this.expect(')'); + if (this.match('=>')) { + if (expr.type === syntax_1.Syntax.Identifier && expr.name === 'yield') { + arrow = true; + expr = { + type: ArrowParameterPlaceHolder, + params: [expr], + async: false + }; + } + if (!arrow) { + if (!this.context.isBindingElement) { + this.throwUnexpectedToken(this.lookahead); + } + if (expr.type === syntax_1.Syntax.SequenceExpression) { + for (var i = 0; i < expr.expressions.length; i++) { + this.reinterpretExpressionAsPattern(expr.expressions[i]); + } + } + else { + this.reinterpretExpressionAsPattern(expr); + } + var parameters = (expr.type === syntax_1.Syntax.SequenceExpression ? expr.expressions : [expr]); + expr = { + type: ArrowParameterPlaceHolder, + params: parameters, + async: false + }; + } + } + this.context.isBindingElement = false; + } + } + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-left-hand-side-expressions + Parser.prototype.parseArguments = function () { + this.expect('('); + var args = []; + if (!this.match(')')) { + while (true) { + var expr = this.match('...') ? this.parseSpreadElement() : + this.isolateCoverGrammar(this.parseAssignmentExpression); + args.push(expr); + if (this.match(')')) { + break; + } + this.expectCommaSeparator(); + if (this.match(')')) { + break; + } + } + } + this.expect(')'); + return args; + }; + Parser.prototype.isIdentifierName = function (token) { + return token.type === 3 /* Identifier */ || + token.type === 4 /* Keyword */ || + token.type === 1 /* BooleanLiteral */ || + token.type === 5 /* NullLiteral */; + }; + Parser.prototype.parseIdentifierName = function () { + var node = this.createNode(); + var token = this.nextToken(); + if (!this.isIdentifierName(token)) { + this.throwUnexpectedToken(token); + } + return this.finalize(node, new Node.Identifier(token.value)); + }; + Parser.prototype.parseNewExpression = function () { + var node = this.createNode(); + var id = this.parseIdentifierName(); + assert_1.assert(id.name === 'new', 'New expression must start with `new`'); + var expr; + if (this.match('.')) { + this.nextToken(); + if (this.lookahead.type === 3 /* Identifier */ && this.context.inFunctionBody && this.lookahead.value === 'target') { + var property = this.parseIdentifierName(); + expr = new Node.MetaProperty(id, property); + } + else { + this.throwUnexpectedToken(this.lookahead); + } + } + else { + var callee = this.isolateCoverGrammar(this.parseLeftHandSideExpression); + var args = this.match('(') ? this.parseArguments() : []; + expr = new Node.NewExpression(callee, args); + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + } + return this.finalize(node, expr); + }; + Parser.prototype.parseAsyncArgument = function () { + var arg = this.parseAssignmentExpression(); + this.context.firstCoverInitializedNameError = null; + return arg; + }; + Parser.prototype.parseAsyncArguments = function () { + this.expect('('); + var args = []; + if (!this.match(')')) { + while (true) { + var expr = this.match('...') ? this.parseSpreadElement() : + this.isolateCoverGrammar(this.parseAsyncArgument); + args.push(expr); + if (this.match(')')) { + break; + } + this.expectCommaSeparator(); + if (this.match(')')) { + break; + } + } + } + this.expect(')'); + return args; + }; + Parser.prototype.parseLeftHandSideExpressionAllowCall = function () { + var startToken = this.lookahead; + var maybeAsync = this.matchContextualKeyword('async'); + var previousAllowIn = this.context.allowIn; + this.context.allowIn = true; + var expr; + if (this.matchKeyword('super') && this.context.inFunctionBody) { + expr = this.createNode(); + this.nextToken(); + expr = this.finalize(expr, new Node.Super()); + if (!this.match('(') && !this.match('.') && !this.match('[')) { + this.throwUnexpectedToken(this.lookahead); + } + } + else { + expr = this.inheritCoverGrammar(this.matchKeyword('new') ? this.parseNewExpression : this.parsePrimaryExpression); + } + while (true) { + if (this.match('.')) { + this.context.isBindingElement = false; + this.context.isAssignmentTarget = true; + this.expect('.'); + var property = this.parseIdentifierName(); + expr = this.finalize(this.startNode(startToken), new Node.StaticMemberExpression(expr, property)); + } + else if (this.match('(')) { + var asyncArrow = maybeAsync && (startToken.lineNumber === this.lookahead.lineNumber); + this.context.isBindingElement = false; + this.context.isAssignmentTarget = false; + var args = asyncArrow ? this.parseAsyncArguments() : this.parseArguments(); + expr = this.finalize(this.startNode(startToken), new Node.CallExpression(expr, args)); + if (asyncArrow && this.match('=>')) { + for (var i = 0; i < args.length; ++i) { + this.reinterpretExpressionAsPattern(args[i]); + } + expr = { + type: ArrowParameterPlaceHolder, + params: args, + async: true + }; + } + } + else if (this.match('[')) { + this.context.isBindingElement = false; + this.context.isAssignmentTarget = true; + this.expect('['); + var property = this.isolateCoverGrammar(this.parseExpression); + this.expect(']'); + expr = this.finalize(this.startNode(startToken), new Node.ComputedMemberExpression(expr, property)); + } + else if (this.lookahead.type === 10 /* Template */ && this.lookahead.head) { + var quasi = this.parseTemplateLiteral(); + expr = this.finalize(this.startNode(startToken), new Node.TaggedTemplateExpression(expr, quasi)); + } + else { + break; + } + } + this.context.allowIn = previousAllowIn; + return expr; + }; + Parser.prototype.parseSuper = function () { + var node = this.createNode(); + this.expectKeyword('super'); + if (!this.match('[') && !this.match('.')) { + this.throwUnexpectedToken(this.lookahead); + } + return this.finalize(node, new Node.Super()); + }; + Parser.prototype.parseLeftHandSideExpression = function () { + assert_1.assert(this.context.allowIn, 'callee of new expression always allow in keyword.'); + var node = this.startNode(this.lookahead); + var expr = (this.matchKeyword('super') && this.context.inFunctionBody) ? this.parseSuper() : + this.inheritCoverGrammar(this.matchKeyword('new') ? this.parseNewExpression : this.parsePrimaryExpression); + while (true) { + if (this.match('[')) { + this.context.isBindingElement = false; + this.context.isAssignmentTarget = true; + this.expect('['); + var property = this.isolateCoverGrammar(this.parseExpression); + this.expect(']'); + expr = this.finalize(node, new Node.ComputedMemberExpression(expr, property)); + } + else if (this.match('.')) { + this.context.isBindingElement = false; + this.context.isAssignmentTarget = true; + this.expect('.'); + var property = this.parseIdentifierName(); + expr = this.finalize(node, new Node.StaticMemberExpression(expr, property)); + } + else if (this.lookahead.type === 10 /* Template */ && this.lookahead.head) { + var quasi = this.parseTemplateLiteral(); + expr = this.finalize(node, new Node.TaggedTemplateExpression(expr, quasi)); + } + else { + break; + } + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-update-expressions + Parser.prototype.parseUpdateExpression = function () { + var expr; + var startToken = this.lookahead; + if (this.match('++') || this.match('--')) { + var node = this.startNode(startToken); + var token = this.nextToken(); + expr = this.inheritCoverGrammar(this.parseUnaryExpression); + if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) { + this.tolerateError(messages_1.Messages.StrictLHSPrefix); + } + if (!this.context.isAssignmentTarget) { + this.tolerateError(messages_1.Messages.InvalidLHSInAssignment); + } + var prefix = true; + expr = this.finalize(node, new Node.UpdateExpression(token.value, expr, prefix)); + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + } + else { + expr = this.inheritCoverGrammar(this.parseLeftHandSideExpressionAllowCall); + if (!this.hasLineTerminator && this.lookahead.type === 7 /* Punctuator */) { + if (this.match('++') || this.match('--')) { + if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) { + this.tolerateError(messages_1.Messages.StrictLHSPostfix); + } + if (!this.context.isAssignmentTarget) { + this.tolerateError(messages_1.Messages.InvalidLHSInAssignment); + } + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + var operator = this.nextToken().value; + var prefix = false; + expr = this.finalize(this.startNode(startToken), new Node.UpdateExpression(operator, expr, prefix)); + } + } + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-unary-operators + Parser.prototype.parseAwaitExpression = function () { + var node = this.createNode(); + this.nextToken(); + var argument = this.parseUnaryExpression(); + return this.finalize(node, new Node.AwaitExpression(argument)); + }; + Parser.prototype.parseUnaryExpression = function () { + var expr; + if (this.match('+') || this.match('-') || this.match('~') || this.match('!') || + this.matchKeyword('delete') || this.matchKeyword('void') || this.matchKeyword('typeof')) { + var node = this.startNode(this.lookahead); + var token = this.nextToken(); + expr = this.inheritCoverGrammar(this.parseUnaryExpression); + expr = this.finalize(node, new Node.UnaryExpression(token.value, expr)); + if (this.context.strict && expr.operator === 'delete' && expr.argument.type === syntax_1.Syntax.Identifier) { + this.tolerateError(messages_1.Messages.StrictDelete); + } + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + } + else if (this.context.await && this.matchContextualKeyword('await')) { + expr = this.parseAwaitExpression(); + } + else { + expr = this.parseUpdateExpression(); + } + return expr; + }; + Parser.prototype.parseExponentiationExpression = function () { + var startToken = this.lookahead; + var expr = this.inheritCoverGrammar(this.parseUnaryExpression); + if (expr.type !== syntax_1.Syntax.UnaryExpression && this.match('**')) { + this.nextToken(); + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + var left = expr; + var right = this.isolateCoverGrammar(this.parseExponentiationExpression); + expr = this.finalize(this.startNode(startToken), new Node.BinaryExpression('**', left, right)); + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-exp-operator + // https://tc39.github.io/ecma262/#sec-multiplicative-operators + // https://tc39.github.io/ecma262/#sec-additive-operators + // https://tc39.github.io/ecma262/#sec-bitwise-shift-operators + // https://tc39.github.io/ecma262/#sec-relational-operators + // https://tc39.github.io/ecma262/#sec-equality-operators + // https://tc39.github.io/ecma262/#sec-binary-bitwise-operators + // https://tc39.github.io/ecma262/#sec-binary-logical-operators + Parser.prototype.binaryPrecedence = function (token) { + var op = token.value; + var precedence; + if (token.type === 7 /* Punctuator */) { + precedence = this.operatorPrecedence[op] || 0; + } + else if (token.type === 4 /* Keyword */) { + precedence = (op === 'instanceof' || (this.context.allowIn && op === 'in')) ? 7 : 0; + } + else { + precedence = 0; + } + return precedence; + }; + Parser.prototype.parseBinaryExpression = function () { + var startToken = this.lookahead; + var expr = this.inheritCoverGrammar(this.parseExponentiationExpression); + var token = this.lookahead; + var prec = this.binaryPrecedence(token); + if (prec > 0) { + this.nextToken(); + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + var markers = [startToken, this.lookahead]; + var left = expr; + var right = this.isolateCoverGrammar(this.parseExponentiationExpression); + var stack = [left, token.value, right]; + var precedences = [prec]; + while (true) { + prec = this.binaryPrecedence(this.lookahead); + if (prec <= 0) { + break; + } + // Reduce: make a binary expression from the three topmost entries. + while ((stack.length > 2) && (prec <= precedences[precedences.length - 1])) { + right = stack.pop(); + var operator = stack.pop(); + precedences.pop(); + left = stack.pop(); + markers.pop(); + var node = this.startNode(markers[markers.length - 1]); + stack.push(this.finalize(node, new Node.BinaryExpression(operator, left, right))); + } + // Shift. + stack.push(this.nextToken().value); + precedences.push(prec); + markers.push(this.lookahead); + stack.push(this.isolateCoverGrammar(this.parseExponentiationExpression)); + } + // Final reduce to clean-up the stack. + var i = stack.length - 1; + expr = stack[i]; + var lastMarker = markers.pop(); + while (i > 1) { + var marker = markers.pop(); + var lastLineStart = lastMarker && lastMarker.lineStart; + var node = this.startNode(marker, lastLineStart); + var operator = stack[i - 1]; + expr = this.finalize(node, new Node.BinaryExpression(operator, stack[i - 2], expr)); + i -= 2; + lastMarker = marker; + } + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-conditional-operator + Parser.prototype.parseConditionalExpression = function () { + var startToken = this.lookahead; + var expr = this.inheritCoverGrammar(this.parseBinaryExpression); + if (this.match('?')) { + this.nextToken(); + var previousAllowIn = this.context.allowIn; + this.context.allowIn = true; + var consequent = this.isolateCoverGrammar(this.parseAssignmentExpression); + this.context.allowIn = previousAllowIn; + this.expect(':'); + var alternate = this.isolateCoverGrammar(this.parseAssignmentExpression); + expr = this.finalize(this.startNode(startToken), new Node.ConditionalExpression(expr, consequent, alternate)); + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-assignment-operators + Parser.prototype.checkPatternParam = function (options, param) { + switch (param.type) { + case syntax_1.Syntax.Identifier: + this.validateParam(options, param, param.name); + break; + case syntax_1.Syntax.RestElement: + this.checkPatternParam(options, param.argument); + break; + case syntax_1.Syntax.AssignmentPattern: + this.checkPatternParam(options, param.left); + break; + case syntax_1.Syntax.ArrayPattern: + for (var i = 0; i < param.elements.length; i++) { + if (param.elements[i] !== null) { + this.checkPatternParam(options, param.elements[i]); + } + } + break; + case syntax_1.Syntax.ObjectPattern: + for (var i = 0; i < param.properties.length; i++) { + this.checkPatternParam(options, param.properties[i].value); + } + break; + default: + break; + } + options.simple = options.simple && (param instanceof Node.Identifier); + }; + Parser.prototype.reinterpretAsCoverFormalsList = function (expr) { + var params = [expr]; + var options; + var asyncArrow = false; + switch (expr.type) { + case syntax_1.Syntax.Identifier: + break; + case ArrowParameterPlaceHolder: + params = expr.params; + asyncArrow = expr.async; + break; + default: + return null; + } + options = { + simple: true, + paramSet: {} + }; + for (var i = 0; i < params.length; ++i) { + var param = params[i]; + if (param.type === syntax_1.Syntax.AssignmentPattern) { + if (param.right.type === syntax_1.Syntax.YieldExpression) { + if (param.right.argument) { + this.throwUnexpectedToken(this.lookahead); + } + param.right.type = syntax_1.Syntax.Identifier; + param.right.name = 'yield'; + delete param.right.argument; + delete param.right.delegate; + } + } + else if (asyncArrow && param.type === syntax_1.Syntax.Identifier && param.name === 'await') { + this.throwUnexpectedToken(this.lookahead); + } + this.checkPatternParam(options, param); + params[i] = param; + } + if (this.context.strict || !this.context.allowYield) { + for (var i = 0; i < params.length; ++i) { + var param = params[i]; + if (param.type === syntax_1.Syntax.YieldExpression) { + this.throwUnexpectedToken(this.lookahead); + } + } + } + if (options.message === messages_1.Messages.StrictParamDupe) { + var token = this.context.strict ? options.stricted : options.firstRestricted; + this.throwUnexpectedToken(token, options.message); + } + return { + simple: options.simple, + params: params, + stricted: options.stricted, + firstRestricted: options.firstRestricted, + message: options.message + }; + }; + Parser.prototype.parseAssignmentExpression = function () { + var expr; + if (!this.context.allowYield && this.matchKeyword('yield')) { + expr = this.parseYieldExpression(); + } + else { + var startToken = this.lookahead; + var token = startToken; + expr = this.parseConditionalExpression(); + if (token.type === 3 /* Identifier */ && (token.lineNumber === this.lookahead.lineNumber) && token.value === 'async') { + if (this.lookahead.type === 3 /* Identifier */ || this.matchKeyword('yield')) { + var arg = this.parsePrimaryExpression(); + this.reinterpretExpressionAsPattern(arg); + expr = { + type: ArrowParameterPlaceHolder, + params: [arg], + async: true + }; + } + } + if (expr.type === ArrowParameterPlaceHolder || this.match('=>')) { + // https://tc39.github.io/ecma262/#sec-arrow-function-definitions + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + var isAsync = expr.async; + var list = this.reinterpretAsCoverFormalsList(expr); + if (list) { + if (this.hasLineTerminator) { + this.tolerateUnexpectedToken(this.lookahead); + } + this.context.firstCoverInitializedNameError = null; + var previousStrict = this.context.strict; + var previousAllowStrictDirective = this.context.allowStrictDirective; + this.context.allowStrictDirective = list.simple; + var previousAllowYield = this.context.allowYield; + var previousAwait = this.context.await; + this.context.allowYield = true; + this.context.await = isAsync; + var node = this.startNode(startToken); + this.expect('=>'); + var body = void 0; + if (this.match('{')) { + var previousAllowIn = this.context.allowIn; + this.context.allowIn = true; + body = this.parseFunctionSourceElements(); + this.context.allowIn = previousAllowIn; + } + else { + body = this.isolateCoverGrammar(this.parseAssignmentExpression); + } + var expression = body.type !== syntax_1.Syntax.BlockStatement; + if (this.context.strict && list.firstRestricted) { + this.throwUnexpectedToken(list.firstRestricted, list.message); + } + if (this.context.strict && list.stricted) { + this.tolerateUnexpectedToken(list.stricted, list.message); + } + expr = isAsync ? this.finalize(node, new Node.AsyncArrowFunctionExpression(list.params, body, expression)) : + this.finalize(node, new Node.ArrowFunctionExpression(list.params, body, expression)); + this.context.strict = previousStrict; + this.context.allowStrictDirective = previousAllowStrictDirective; + this.context.allowYield = previousAllowYield; + this.context.await = previousAwait; + } + } + else { + if (this.matchAssign()) { + if (!this.context.isAssignmentTarget) { + this.tolerateError(messages_1.Messages.InvalidLHSInAssignment); + } + if (this.context.strict && expr.type === syntax_1.Syntax.Identifier) { + var id = expr; + if (this.scanner.isRestrictedWord(id.name)) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictLHSAssignment); + } + if (this.scanner.isStrictModeReservedWord(id.name)) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord); + } + } + if (!this.match('=')) { + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + } + else { + this.reinterpretExpressionAsPattern(expr); + } + token = this.nextToken(); + var operator = token.value; + var right = this.isolateCoverGrammar(this.parseAssignmentExpression); + expr = this.finalize(this.startNode(startToken), new Node.AssignmentExpression(operator, expr, right)); + this.context.firstCoverInitializedNameError = null; + } + } + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-comma-operator + Parser.prototype.parseExpression = function () { + var startToken = this.lookahead; + var expr = this.isolateCoverGrammar(this.parseAssignmentExpression); + if (this.match(',')) { + var expressions = []; + expressions.push(expr); + while (this.lookahead.type !== 2 /* EOF */) { + if (!this.match(',')) { + break; + } + this.nextToken(); + expressions.push(this.isolateCoverGrammar(this.parseAssignmentExpression)); + } + expr = this.finalize(this.startNode(startToken), new Node.SequenceExpression(expressions)); + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-block + Parser.prototype.parseStatementListItem = function () { + var statement; + this.context.isAssignmentTarget = true; + this.context.isBindingElement = true; + if (this.lookahead.type === 4 /* Keyword */) { + switch (this.lookahead.value) { + case 'export': + if (!this.context.isModule) { + this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalExportDeclaration); + } + statement = this.parseExportDeclaration(); + break; + case 'import': + if (!this.context.isModule) { + this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalImportDeclaration); + } + statement = this.parseImportDeclaration(); + break; + case 'const': + statement = this.parseLexicalDeclaration({ inFor: false }); + break; + case 'function': + statement = this.parseFunctionDeclaration(); + break; + case 'class': + statement = this.parseClassDeclaration(); + break; + case 'let': + statement = this.isLexicalDeclaration() ? this.parseLexicalDeclaration({ inFor: false }) : this.parseStatement(); + break; + default: + statement = this.parseStatement(); + break; + } + } + else { + statement = this.parseStatement(); + } + return statement; + }; + Parser.prototype.parseBlock = function () { + var node = this.createNode(); + this.expect('{'); + var block = []; + while (true) { + if (this.match('}')) { + break; + } + block.push(this.parseStatementListItem()); + } + this.expect('}'); + return this.finalize(node, new Node.BlockStatement(block)); + }; + // https://tc39.github.io/ecma262/#sec-let-and-const-declarations + Parser.prototype.parseLexicalBinding = function (kind, options) { + var node = this.createNode(); + var params = []; + var id = this.parsePattern(params, kind); + if (this.context.strict && id.type === syntax_1.Syntax.Identifier) { + if (this.scanner.isRestrictedWord(id.name)) { + this.tolerateError(messages_1.Messages.StrictVarName); + } + } + var init = null; + if (kind === 'const') { + if (!this.matchKeyword('in') && !this.matchContextualKeyword('of')) { + if (this.match('=')) { + this.nextToken(); + init = this.isolateCoverGrammar(this.parseAssignmentExpression); + } + else { + this.throwError(messages_1.Messages.DeclarationMissingInitializer, 'const'); + } + } + } + else if ((!options.inFor && id.type !== syntax_1.Syntax.Identifier) || this.match('=')) { + this.expect('='); + init = this.isolateCoverGrammar(this.parseAssignmentExpression); + } + return this.finalize(node, new Node.VariableDeclarator(id, init)); + }; + Parser.prototype.parseBindingList = function (kind, options) { + var list = [this.parseLexicalBinding(kind, options)]; + while (this.match(',')) { + this.nextToken(); + list.push(this.parseLexicalBinding(kind, options)); + } + return list; + }; + Parser.prototype.isLexicalDeclaration = function () { + var state = this.scanner.saveState(); + this.scanner.scanComments(); + var next = this.scanner.lex(); + this.scanner.restoreState(state); + return (next.type === 3 /* Identifier */) || + (next.type === 7 /* Punctuator */ && next.value === '[') || + (next.type === 7 /* Punctuator */ && next.value === '{') || + (next.type === 4 /* Keyword */ && next.value === 'let') || + (next.type === 4 /* Keyword */ && next.value === 'yield'); + }; + Parser.prototype.parseLexicalDeclaration = function (options) { + var node = this.createNode(); + var kind = this.nextToken().value; + assert_1.assert(kind === 'let' || kind === 'const', 'Lexical declaration must be either let or const'); + var declarations = this.parseBindingList(kind, options); + this.consumeSemicolon(); + return this.finalize(node, new Node.VariableDeclaration(declarations, kind)); + }; + // https://tc39.github.io/ecma262/#sec-destructuring-binding-patterns + Parser.prototype.parseBindingRestElement = function (params, kind) { + var node = this.createNode(); + this.expect('...'); + var arg = this.parsePattern(params, kind); + return this.finalize(node, new Node.RestElement(arg)); + }; + Parser.prototype.parseArrayPattern = function (params, kind) { + var node = this.createNode(); + this.expect('['); + var elements = []; + while (!this.match(']')) { + if (this.match(',')) { + this.nextToken(); + elements.push(null); + } + else { + if (this.match('...')) { + elements.push(this.parseBindingRestElement(params, kind)); + break; + } + else { + elements.push(this.parsePatternWithDefault(params, kind)); + } + if (!this.match(']')) { + this.expect(','); + } + } + } + this.expect(']'); + return this.finalize(node, new Node.ArrayPattern(elements)); + }; + Parser.prototype.parsePropertyPattern = function (params, kind) { + var node = this.createNode(); + var computed = false; + var shorthand = false; + var method = false; + var key; + var value; + if (this.lookahead.type === 3 /* Identifier */) { + var keyToken = this.lookahead; + key = this.parseVariableIdentifier(); + var init = this.finalize(node, new Node.Identifier(keyToken.value)); + if (this.match('=')) { + params.push(keyToken); + shorthand = true; + this.nextToken(); + var expr = this.parseAssignmentExpression(); + value = this.finalize(this.startNode(keyToken), new Node.AssignmentPattern(init, expr)); + } + else if (!this.match(':')) { + params.push(keyToken); + shorthand = true; + value = init; + } + else { + this.expect(':'); + value = this.parsePatternWithDefault(params, kind); + } + } + else { + computed = this.match('['); + key = this.parseObjectPropertyKey(); + this.expect(':'); + value = this.parsePatternWithDefault(params, kind); + } + return this.finalize(node, new Node.Property('init', key, computed, value, method, shorthand)); + }; + Parser.prototype.parseObjectPattern = function (params, kind) { + var node = this.createNode(); + var properties = []; + this.expect('{'); + while (!this.match('}')) { + properties.push(this.parsePropertyPattern(params, kind)); + if (!this.match('}')) { + this.expect(','); + } + } + this.expect('}'); + return this.finalize(node, new Node.ObjectPattern(properties)); + }; + Parser.prototype.parsePattern = function (params, kind) { + var pattern; + if (this.match('[')) { + pattern = this.parseArrayPattern(params, kind); + } + else if (this.match('{')) { + pattern = this.parseObjectPattern(params, kind); + } + else { + if (this.matchKeyword('let') && (kind === 'const' || kind === 'let')) { + this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.LetInLexicalBinding); + } + params.push(this.lookahead); + pattern = this.parseVariableIdentifier(kind); + } + return pattern; + }; + Parser.prototype.parsePatternWithDefault = function (params, kind) { + var startToken = this.lookahead; + var pattern = this.parsePattern(params, kind); + if (this.match('=')) { + this.nextToken(); + var previousAllowYield = this.context.allowYield; + this.context.allowYield = true; + var right = this.isolateCoverGrammar(this.parseAssignmentExpression); + this.context.allowYield = previousAllowYield; + pattern = this.finalize(this.startNode(startToken), new Node.AssignmentPattern(pattern, right)); + } + return pattern; + }; + // https://tc39.github.io/ecma262/#sec-variable-statement + Parser.prototype.parseVariableIdentifier = function (kind) { + var node = this.createNode(); + var token = this.nextToken(); + if (token.type === 4 /* Keyword */ && token.value === 'yield') { + if (this.context.strict) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord); + } + else if (!this.context.allowYield) { + this.throwUnexpectedToken(token); + } + } + else if (token.type !== 3 /* Identifier */) { + if (this.context.strict && token.type === 4 /* Keyword */ && this.scanner.isStrictModeReservedWord(token.value)) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord); + } + else { + if (this.context.strict || token.value !== 'let' || kind !== 'var') { + this.throwUnexpectedToken(token); + } + } + } + else if ((this.context.isModule || this.context.await) && token.type === 3 /* Identifier */ && token.value === 'await') { + this.tolerateUnexpectedToken(token); + } + return this.finalize(node, new Node.Identifier(token.value)); + }; + Parser.prototype.parseVariableDeclaration = function (options) { + var node = this.createNode(); + var params = []; + var id = this.parsePattern(params, 'var'); + if (this.context.strict && id.type === syntax_1.Syntax.Identifier) { + if (this.scanner.isRestrictedWord(id.name)) { + this.tolerateError(messages_1.Messages.StrictVarName); + } + } + var init = null; + if (this.match('=')) { + this.nextToken(); + init = this.isolateCoverGrammar(this.parseAssignmentExpression); + } + else if (id.type !== syntax_1.Syntax.Identifier && !options.inFor) { + this.expect('='); + } + return this.finalize(node, new Node.VariableDeclarator(id, init)); + }; + Parser.prototype.parseVariableDeclarationList = function (options) { + var opt = { inFor: options.inFor }; + var list = []; + list.push(this.parseVariableDeclaration(opt)); + while (this.match(',')) { + this.nextToken(); + list.push(this.parseVariableDeclaration(opt)); + } + return list; + }; + Parser.prototype.parseVariableStatement = function () { + var node = this.createNode(); + this.expectKeyword('var'); + var declarations = this.parseVariableDeclarationList({ inFor: false }); + this.consumeSemicolon(); + return this.finalize(node, new Node.VariableDeclaration(declarations, 'var')); + }; + // https://tc39.github.io/ecma262/#sec-empty-statement + Parser.prototype.parseEmptyStatement = function () { + var node = this.createNode(); + this.expect(';'); + return this.finalize(node, new Node.EmptyStatement()); + }; + // https://tc39.github.io/ecma262/#sec-expression-statement + Parser.prototype.parseExpressionStatement = function () { + var node = this.createNode(); + var expr = this.parseExpression(); + this.consumeSemicolon(); + return this.finalize(node, new Node.ExpressionStatement(expr)); + }; + // https://tc39.github.io/ecma262/#sec-if-statement + Parser.prototype.parseIfClause = function () { + if (this.context.strict && this.matchKeyword('function')) { + this.tolerateError(messages_1.Messages.StrictFunction); + } + return this.parseStatement(); + }; + Parser.prototype.parseIfStatement = function () { + var node = this.createNode(); + var consequent; + var alternate = null; + this.expectKeyword('if'); + this.expect('('); + var test = this.parseExpression(); + if (!this.match(')') && this.config.tolerant) { + this.tolerateUnexpectedToken(this.nextToken()); + consequent = this.finalize(this.createNode(), new Node.EmptyStatement()); + } + else { + this.expect(')'); + consequent = this.parseIfClause(); + if (this.matchKeyword('else')) { + this.nextToken(); + alternate = this.parseIfClause(); + } + } + return this.finalize(node, new Node.IfStatement(test, consequent, alternate)); + }; + // https://tc39.github.io/ecma262/#sec-do-while-statement + Parser.prototype.parseDoWhileStatement = function () { + var node = this.createNode(); + this.expectKeyword('do'); + var previousInIteration = this.context.inIteration; + this.context.inIteration = true; + var body = this.parseStatement(); + this.context.inIteration = previousInIteration; + this.expectKeyword('while'); + this.expect('('); + var test = this.parseExpression(); + if (!this.match(')') && this.config.tolerant) { + this.tolerateUnexpectedToken(this.nextToken()); + } + else { + this.expect(')'); + if (this.match(';')) { + this.nextToken(); + } + } + return this.finalize(node, new Node.DoWhileStatement(body, test)); + }; + // https://tc39.github.io/ecma262/#sec-while-statement + Parser.prototype.parseWhileStatement = function () { + var node = this.createNode(); + var body; + this.expectKeyword('while'); + this.expect('('); + var test = this.parseExpression(); + if (!this.match(')') && this.config.tolerant) { + this.tolerateUnexpectedToken(this.nextToken()); + body = this.finalize(this.createNode(), new Node.EmptyStatement()); + } + else { + this.expect(')'); + var previousInIteration = this.context.inIteration; + this.context.inIteration = true; + body = this.parseStatement(); + this.context.inIteration = previousInIteration; + } + return this.finalize(node, new Node.WhileStatement(test, body)); + }; + // https://tc39.github.io/ecma262/#sec-for-statement + // https://tc39.github.io/ecma262/#sec-for-in-and-for-of-statements + Parser.prototype.parseForStatement = function () { + var init = null; + var test = null; + var update = null; + var forIn = true; + var left, right; + var node = this.createNode(); + this.expectKeyword('for'); + this.expect('('); + if (this.match(';')) { + this.nextToken(); + } + else { + if (this.matchKeyword('var')) { + init = this.createNode(); + this.nextToken(); + var previousAllowIn = this.context.allowIn; + this.context.allowIn = false; + var declarations = this.parseVariableDeclarationList({ inFor: true }); + this.context.allowIn = previousAllowIn; + if (declarations.length === 1 && this.matchKeyword('in')) { + var decl = declarations[0]; + if (decl.init && (decl.id.type === syntax_1.Syntax.ArrayPattern || decl.id.type === syntax_1.Syntax.ObjectPattern || this.context.strict)) { + this.tolerateError(messages_1.Messages.ForInOfLoopInitializer, 'for-in'); + } + init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var')); + this.nextToken(); + left = init; + right = this.parseExpression(); + init = null; + } + else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword('of')) { + init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var')); + this.nextToken(); + left = init; + right = this.parseAssignmentExpression(); + init = null; + forIn = false; + } + else { + init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var')); + this.expect(';'); + } + } + else if (this.matchKeyword('const') || this.matchKeyword('let')) { + init = this.createNode(); + var kind = this.nextToken().value; + if (!this.context.strict && this.lookahead.value === 'in') { + init = this.finalize(init, new Node.Identifier(kind)); + this.nextToken(); + left = init; + right = this.parseExpression(); + init = null; + } + else { + var previousAllowIn = this.context.allowIn; + this.context.allowIn = false; + var declarations = this.parseBindingList(kind, { inFor: true }); + this.context.allowIn = previousAllowIn; + if (declarations.length === 1 && declarations[0].init === null && this.matchKeyword('in')) { + init = this.finalize(init, new Node.VariableDeclaration(declarations, kind)); + this.nextToken(); + left = init; + right = this.parseExpression(); + init = null; + } + else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword('of')) { + init = this.finalize(init, new Node.VariableDeclaration(declarations, kind)); + this.nextToken(); + left = init; + right = this.parseAssignmentExpression(); + init = null; + forIn = false; + } + else { + this.consumeSemicolon(); + init = this.finalize(init, new Node.VariableDeclaration(declarations, kind)); + } + } + } + else { + var initStartToken = this.lookahead; + var previousAllowIn = this.context.allowIn; + this.context.allowIn = false; + init = this.inheritCoverGrammar(this.parseAssignmentExpression); + this.context.allowIn = previousAllowIn; + if (this.matchKeyword('in')) { + if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) { + this.tolerateError(messages_1.Messages.InvalidLHSInForIn); + } + this.nextToken(); + this.reinterpretExpressionAsPattern(init); + left = init; + right = this.parseExpression(); + init = null; + } + else if (this.matchContextualKeyword('of')) { + if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) { + this.tolerateError(messages_1.Messages.InvalidLHSInForLoop); + } + this.nextToken(); + this.reinterpretExpressionAsPattern(init); + left = init; + right = this.parseAssignmentExpression(); + init = null; + forIn = false; + } + else { + if (this.match(',')) { + var initSeq = [init]; + while (this.match(',')) { + this.nextToken(); + initSeq.push(this.isolateCoverGrammar(this.parseAssignmentExpression)); + } + init = this.finalize(this.startNode(initStartToken), new Node.SequenceExpression(initSeq)); + } + this.expect(';'); + } + } + } + if (typeof left === 'undefined') { + if (!this.match(';')) { + test = this.parseExpression(); + } + this.expect(';'); + if (!this.match(')')) { + update = this.parseExpression(); + } + } + var body; + if (!this.match(')') && this.config.tolerant) { + this.tolerateUnexpectedToken(this.nextToken()); + body = this.finalize(this.createNode(), new Node.EmptyStatement()); + } + else { + this.expect(')'); + var previousInIteration = this.context.inIteration; + this.context.inIteration = true; + body = this.isolateCoverGrammar(this.parseStatement); + this.context.inIteration = previousInIteration; + } + return (typeof left === 'undefined') ? + this.finalize(node, new Node.ForStatement(init, test, update, body)) : + forIn ? this.finalize(node, new Node.ForInStatement(left, right, body)) : + this.finalize(node, new Node.ForOfStatement(left, right, body)); + }; + // https://tc39.github.io/ecma262/#sec-continue-statement + Parser.prototype.parseContinueStatement = function () { + var node = this.createNode(); + this.expectKeyword('continue'); + var label = null; + if (this.lookahead.type === 3 /* Identifier */ && !this.hasLineTerminator) { + var id = this.parseVariableIdentifier(); + label = id; + var key = '$' + id.name; + if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) { + this.throwError(messages_1.Messages.UnknownLabel, id.name); + } + } + this.consumeSemicolon(); + if (label === null && !this.context.inIteration) { + this.throwError(messages_1.Messages.IllegalContinue); + } + return this.finalize(node, new Node.ContinueStatement(label)); + }; + // https://tc39.github.io/ecma262/#sec-break-statement + Parser.prototype.parseBreakStatement = function () { + var node = this.createNode(); + this.expectKeyword('break'); + var label = null; + if (this.lookahead.type === 3 /* Identifier */ && !this.hasLineTerminator) { + var id = this.parseVariableIdentifier(); + var key = '$' + id.name; + if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) { + this.throwError(messages_1.Messages.UnknownLabel, id.name); + } + label = id; + } + this.consumeSemicolon(); + if (label === null && !this.context.inIteration && !this.context.inSwitch) { + this.throwError(messages_1.Messages.IllegalBreak); + } + return this.finalize(node, new Node.BreakStatement(label)); + }; + // https://tc39.github.io/ecma262/#sec-return-statement + Parser.prototype.parseReturnStatement = function () { + if (!this.context.inFunctionBody) { + this.tolerateError(messages_1.Messages.IllegalReturn); + } + var node = this.createNode(); + this.expectKeyword('return'); + var hasArgument = (!this.match(';') && !this.match('}') && + !this.hasLineTerminator && this.lookahead.type !== 2 /* EOF */) || + this.lookahead.type === 8 /* StringLiteral */ || + this.lookahead.type === 10 /* Template */; + var argument = hasArgument ? this.parseExpression() : null; + this.consumeSemicolon(); + return this.finalize(node, new Node.ReturnStatement(argument)); + }; + // https://tc39.github.io/ecma262/#sec-with-statement + Parser.prototype.parseWithStatement = function () { + if (this.context.strict) { + this.tolerateError(messages_1.Messages.StrictModeWith); + } + var node = this.createNode(); + var body; + this.expectKeyword('with'); + this.expect('('); + var object = this.parseExpression(); + if (!this.match(')') && this.config.tolerant) { + this.tolerateUnexpectedToken(this.nextToken()); + body = this.finalize(this.createNode(), new Node.EmptyStatement()); + } + else { + this.expect(')'); + body = this.parseStatement(); + } + return this.finalize(node, new Node.WithStatement(object, body)); + }; + // https://tc39.github.io/ecma262/#sec-switch-statement + Parser.prototype.parseSwitchCase = function () { + var node = this.createNode(); + var test; + if (this.matchKeyword('default')) { + this.nextToken(); + test = null; + } + else { + this.expectKeyword('case'); + test = this.parseExpression(); + } + this.expect(':'); + var consequent = []; + while (true) { + if (this.match('}') || this.matchKeyword('default') || this.matchKeyword('case')) { + break; + } + consequent.push(this.parseStatementListItem()); + } + return this.finalize(node, new Node.SwitchCase(test, consequent)); + }; + Parser.prototype.parseSwitchStatement = function () { + var node = this.createNode(); + this.expectKeyword('switch'); + this.expect('('); + var discriminant = this.parseExpression(); + this.expect(')'); + var previousInSwitch = this.context.inSwitch; + this.context.inSwitch = true; + var cases = []; + var defaultFound = false; + this.expect('{'); + while (true) { + if (this.match('}')) { + break; + } + var clause = this.parseSwitchCase(); + if (clause.test === null) { + if (defaultFound) { + this.throwError(messages_1.Messages.MultipleDefaultsInSwitch); + } + defaultFound = true; + } + cases.push(clause); + } + this.expect('}'); + this.context.inSwitch = previousInSwitch; + return this.finalize(node, new Node.SwitchStatement(discriminant, cases)); + }; + // https://tc39.github.io/ecma262/#sec-labelled-statements + Parser.prototype.parseLabelledStatement = function () { + var node = this.createNode(); + var expr = this.parseExpression(); + var statement; + if ((expr.type === syntax_1.Syntax.Identifier) && this.match(':')) { + this.nextToken(); + var id = expr; + var key = '$' + id.name; + if (Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) { + this.throwError(messages_1.Messages.Redeclaration, 'Label', id.name); + } + this.context.labelSet[key] = true; + var body = void 0; + if (this.matchKeyword('class')) { + this.tolerateUnexpectedToken(this.lookahead); + body = this.parseClassDeclaration(); + } + else if (this.matchKeyword('function')) { + var token = this.lookahead; + var declaration = this.parseFunctionDeclaration(); + if (this.context.strict) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunction); + } + else if (declaration.generator) { + this.tolerateUnexpectedToken(token, messages_1.Messages.GeneratorInLegacyContext); + } + body = declaration; + } + else { + body = this.parseStatement(); + } + delete this.context.labelSet[key]; + statement = new Node.LabeledStatement(id, body); + } + else { + this.consumeSemicolon(); + statement = new Node.ExpressionStatement(expr); + } + return this.finalize(node, statement); + }; + // https://tc39.github.io/ecma262/#sec-throw-statement + Parser.prototype.parseThrowStatement = function () { + var node = this.createNode(); + this.expectKeyword('throw'); + if (this.hasLineTerminator) { + this.throwError(messages_1.Messages.NewlineAfterThrow); + } + var argument = this.parseExpression(); + this.consumeSemicolon(); + return this.finalize(node, new Node.ThrowStatement(argument)); + }; + // https://tc39.github.io/ecma262/#sec-try-statement + Parser.prototype.parseCatchClause = function () { + var node = this.createNode(); + this.expectKeyword('catch'); + this.expect('('); + if (this.match(')')) { + this.throwUnexpectedToken(this.lookahead); + } + var params = []; + var param = this.parsePattern(params); + var paramMap = {}; + for (var i = 0; i < params.length; i++) { + var key = '$' + params[i].value; + if (Object.prototype.hasOwnProperty.call(paramMap, key)) { + this.tolerateError(messages_1.Messages.DuplicateBinding, params[i].value); + } + paramMap[key] = true; + } + if (this.context.strict && param.type === syntax_1.Syntax.Identifier) { + if (this.scanner.isRestrictedWord(param.name)) { + this.tolerateError(messages_1.Messages.StrictCatchVariable); + } + } + this.expect(')'); + var body = this.parseBlock(); + return this.finalize(node, new Node.CatchClause(param, body)); + }; + Parser.prototype.parseFinallyClause = function () { + this.expectKeyword('finally'); + return this.parseBlock(); + }; + Parser.prototype.parseTryStatement = function () { + var node = this.createNode(); + this.expectKeyword('try'); + var block = this.parseBlock(); + var handler = this.matchKeyword('catch') ? this.parseCatchClause() : null; + var finalizer = this.matchKeyword('finally') ? this.parseFinallyClause() : null; + if (!handler && !finalizer) { + this.throwError(messages_1.Messages.NoCatchOrFinally); + } + return this.finalize(node, new Node.TryStatement(block, handler, finalizer)); + }; + // https://tc39.github.io/ecma262/#sec-debugger-statement + Parser.prototype.parseDebuggerStatement = function () { + var node = this.createNode(); + this.expectKeyword('debugger'); + this.consumeSemicolon(); + return this.finalize(node, new Node.DebuggerStatement()); + }; + // https://tc39.github.io/ecma262/#sec-ecmascript-language-statements-and-declarations + Parser.prototype.parseStatement = function () { + var statement; + switch (this.lookahead.type) { + case 1 /* BooleanLiteral */: + case 5 /* NullLiteral */: + case 6 /* NumericLiteral */: + case 8 /* StringLiteral */: + case 10 /* Template */: + case 9 /* RegularExpression */: + statement = this.parseExpressionStatement(); + break; + case 7 /* Punctuator */: + var value = this.lookahead.value; + if (value === '{') { + statement = this.parseBlock(); + } + else if (value === '(') { + statement = this.parseExpressionStatement(); + } + else if (value === ';') { + statement = this.parseEmptyStatement(); + } + else { + statement = this.parseExpressionStatement(); + } + break; + case 3 /* Identifier */: + statement = this.matchAsyncFunction() ? this.parseFunctionDeclaration() : this.parseLabelledStatement(); + break; + case 4 /* Keyword */: + switch (this.lookahead.value) { + case 'break': + statement = this.parseBreakStatement(); + break; + case 'continue': + statement = this.parseContinueStatement(); + break; + case 'debugger': + statement = this.parseDebuggerStatement(); + break; + case 'do': + statement = this.parseDoWhileStatement(); + break; + case 'for': + statement = this.parseForStatement(); + break; + case 'function': + statement = this.parseFunctionDeclaration(); + break; + case 'if': + statement = this.parseIfStatement(); + break; + case 'return': + statement = this.parseReturnStatement(); + break; + case 'switch': + statement = this.parseSwitchStatement(); + break; + case 'throw': + statement = this.parseThrowStatement(); + break; + case 'try': + statement = this.parseTryStatement(); + break; + case 'var': + statement = this.parseVariableStatement(); + break; + case 'while': + statement = this.parseWhileStatement(); + break; + case 'with': + statement = this.parseWithStatement(); + break; + default: + statement = this.parseExpressionStatement(); + break; + } + break; + default: + statement = this.throwUnexpectedToken(this.lookahead); + } + return statement; + }; + // https://tc39.github.io/ecma262/#sec-function-definitions + Parser.prototype.parseFunctionSourceElements = function () { + var node = this.createNode(); + this.expect('{'); + var body = this.parseDirectivePrologues(); + var previousLabelSet = this.context.labelSet; + var previousInIteration = this.context.inIteration; + var previousInSwitch = this.context.inSwitch; + var previousInFunctionBody = this.context.inFunctionBody; + this.context.labelSet = {}; + this.context.inIteration = false; + this.context.inSwitch = false; + this.context.inFunctionBody = true; + while (this.lookahead.type !== 2 /* EOF */) { + if (this.match('}')) { + break; + } + body.push(this.parseStatementListItem()); + } + this.expect('}'); + this.context.labelSet = previousLabelSet; + this.context.inIteration = previousInIteration; + this.context.inSwitch = previousInSwitch; + this.context.inFunctionBody = previousInFunctionBody; + return this.finalize(node, new Node.BlockStatement(body)); + }; + Parser.prototype.validateParam = function (options, param, name) { + var key = '$' + name; + if (this.context.strict) { + if (this.scanner.isRestrictedWord(name)) { + options.stricted = param; + options.message = messages_1.Messages.StrictParamName; + } + if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) { + options.stricted = param; + options.message = messages_1.Messages.StrictParamDupe; + } + } + else if (!options.firstRestricted) { + if (this.scanner.isRestrictedWord(name)) { + options.firstRestricted = param; + options.message = messages_1.Messages.StrictParamName; + } + else if (this.scanner.isStrictModeReservedWord(name)) { + options.firstRestricted = param; + options.message = messages_1.Messages.StrictReservedWord; + } + else if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) { + options.stricted = param; + options.message = messages_1.Messages.StrictParamDupe; + } + } + /* istanbul ignore next */ + if (typeof Object.defineProperty === 'function') { + Object.defineProperty(options.paramSet, key, { value: true, enumerable: true, writable: true, configurable: true }); + } + else { + options.paramSet[key] = true; + } + }; + Parser.prototype.parseRestElement = function (params) { + var node = this.createNode(); + this.expect('...'); + var arg = this.parsePattern(params); + if (this.match('=')) { + this.throwError(messages_1.Messages.DefaultRestParameter); + } + if (!this.match(')')) { + this.throwError(messages_1.Messages.ParameterAfterRestParameter); + } + return this.finalize(node, new Node.RestElement(arg)); + }; + Parser.prototype.parseFormalParameter = function (options) { + var params = []; + var param = this.match('...') ? this.parseRestElement(params) : this.parsePatternWithDefault(params); + for (var i = 0; i < params.length; i++) { + this.validateParam(options, params[i], params[i].value); + } + options.simple = options.simple && (param instanceof Node.Identifier); + options.params.push(param); + }; + Parser.prototype.parseFormalParameters = function (firstRestricted) { + var options; + options = { + simple: true, + params: [], + firstRestricted: firstRestricted + }; + this.expect('('); + if (!this.match(')')) { + options.paramSet = {}; + while (this.lookahead.type !== 2 /* EOF */) { + this.parseFormalParameter(options); + if (this.match(')')) { + break; + } + this.expect(','); + if (this.match(')')) { + break; + } + } + } + this.expect(')'); + return { + simple: options.simple, + params: options.params, + stricted: options.stricted, + firstRestricted: options.firstRestricted, + message: options.message + }; + }; + Parser.prototype.matchAsyncFunction = function () { + var match = this.matchContextualKeyword('async'); + if (match) { + var state = this.scanner.saveState(); + this.scanner.scanComments(); + var next = this.scanner.lex(); + this.scanner.restoreState(state); + match = (state.lineNumber === next.lineNumber) && (next.type === 4 /* Keyword */) && (next.value === 'function'); + } + return match; + }; + Parser.prototype.parseFunctionDeclaration = function (identifierIsOptional) { + var node = this.createNode(); + var isAsync = this.matchContextualKeyword('async'); + if (isAsync) { + this.nextToken(); + } + this.expectKeyword('function'); + var isGenerator = isAsync ? false : this.match('*'); + if (isGenerator) { + this.nextToken(); + } + var message; + var id = null; + var firstRestricted = null; + if (!identifierIsOptional || !this.match('(')) { + var token = this.lookahead; + id = this.parseVariableIdentifier(); + if (this.context.strict) { + if (this.scanner.isRestrictedWord(token.value)) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName); + } + } + else { + if (this.scanner.isRestrictedWord(token.value)) { + firstRestricted = token; + message = messages_1.Messages.StrictFunctionName; + } + else if (this.scanner.isStrictModeReservedWord(token.value)) { + firstRestricted = token; + message = messages_1.Messages.StrictReservedWord; + } + } + } + var previousAllowAwait = this.context.await; + var previousAllowYield = this.context.allowYield; + this.context.await = isAsync; + this.context.allowYield = !isGenerator; + var formalParameters = this.parseFormalParameters(firstRestricted); + var params = formalParameters.params; + var stricted = formalParameters.stricted; + firstRestricted = formalParameters.firstRestricted; + if (formalParameters.message) { + message = formalParameters.message; + } + var previousStrict = this.context.strict; + var previousAllowStrictDirective = this.context.allowStrictDirective; + this.context.allowStrictDirective = formalParameters.simple; + var body = this.parseFunctionSourceElements(); + if (this.context.strict && firstRestricted) { + this.throwUnexpectedToken(firstRestricted, message); + } + if (this.context.strict && stricted) { + this.tolerateUnexpectedToken(stricted, message); + } + this.context.strict = previousStrict; + this.context.allowStrictDirective = previousAllowStrictDirective; + this.context.await = previousAllowAwait; + this.context.allowYield = previousAllowYield; + return isAsync ? this.finalize(node, new Node.AsyncFunctionDeclaration(id, params, body)) : + this.finalize(node, new Node.FunctionDeclaration(id, params, body, isGenerator)); + }; + Parser.prototype.parseFunctionExpression = function () { + var node = this.createNode(); + var isAsync = this.matchContextualKeyword('async'); + if (isAsync) { + this.nextToken(); + } + this.expectKeyword('function'); + var isGenerator = isAsync ? false : this.match('*'); + if (isGenerator) { + this.nextToken(); + } + var message; + var id = null; + var firstRestricted; + var previousAllowAwait = this.context.await; + var previousAllowYield = this.context.allowYield; + this.context.await = isAsync; + this.context.allowYield = !isGenerator; + if (!this.match('(')) { + var token = this.lookahead; + id = (!this.context.strict && !isGenerator && this.matchKeyword('yield')) ? this.parseIdentifierName() : this.parseVariableIdentifier(); + if (this.context.strict) { + if (this.scanner.isRestrictedWord(token.value)) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName); + } + } + else { + if (this.scanner.isRestrictedWord(token.value)) { + firstRestricted = token; + message = messages_1.Messages.StrictFunctionName; + } + else if (this.scanner.isStrictModeReservedWord(token.value)) { + firstRestricted = token; + message = messages_1.Messages.StrictReservedWord; + } + } + } + var formalParameters = this.parseFormalParameters(firstRestricted); + var params = formalParameters.params; + var stricted = formalParameters.stricted; + firstRestricted = formalParameters.firstRestricted; + if (formalParameters.message) { + message = formalParameters.message; + } + var previousStrict = this.context.strict; + var previousAllowStrictDirective = this.context.allowStrictDirective; + this.context.allowStrictDirective = formalParameters.simple; + var body = this.parseFunctionSourceElements(); + if (this.context.strict && firstRestricted) { + this.throwUnexpectedToken(firstRestricted, message); + } + if (this.context.strict && stricted) { + this.tolerateUnexpectedToken(stricted, message); + } + this.context.strict = previousStrict; + this.context.allowStrictDirective = previousAllowStrictDirective; + this.context.await = previousAllowAwait; + this.context.allowYield = previousAllowYield; + return isAsync ? this.finalize(node, new Node.AsyncFunctionExpression(id, params, body)) : + this.finalize(node, new Node.FunctionExpression(id, params, body, isGenerator)); + }; + // https://tc39.github.io/ecma262/#sec-directive-prologues-and-the-use-strict-directive + Parser.prototype.parseDirective = function () { + var token = this.lookahead; + var node = this.createNode(); + var expr = this.parseExpression(); + var directive = (expr.type === syntax_1.Syntax.Literal) ? this.getTokenRaw(token).slice(1, -1) : null; + this.consumeSemicolon(); + return this.finalize(node, directive ? new Node.Directive(expr, directive) : new Node.ExpressionStatement(expr)); + }; + Parser.prototype.parseDirectivePrologues = function () { + var firstRestricted = null; + var body = []; + while (true) { + var token = this.lookahead; + if (token.type !== 8 /* StringLiteral */) { + break; + } + var statement = this.parseDirective(); + body.push(statement); + var directive = statement.directive; + if (typeof directive !== 'string') { + break; + } + if (directive === 'use strict') { + this.context.strict = true; + if (firstRestricted) { + this.tolerateUnexpectedToken(firstRestricted, messages_1.Messages.StrictOctalLiteral); + } + if (!this.context.allowStrictDirective) { + this.tolerateUnexpectedToken(token, messages_1.Messages.IllegalLanguageModeDirective); + } + } + else { + if (!firstRestricted && token.octal) { + firstRestricted = token; + } + } + } + return body; + }; + // https://tc39.github.io/ecma262/#sec-method-definitions + Parser.prototype.qualifiedPropertyName = function (token) { + switch (token.type) { + case 3 /* Identifier */: + case 8 /* StringLiteral */: + case 1 /* BooleanLiteral */: + case 5 /* NullLiteral */: + case 6 /* NumericLiteral */: + case 4 /* Keyword */: + return true; + case 7 /* Punctuator */: + return token.value === '['; + default: + break; + } + return false; + }; + Parser.prototype.parseGetterMethod = function () { + var node = this.createNode(); + var isGenerator = false; + var previousAllowYield = this.context.allowYield; + this.context.allowYield = !isGenerator; + var formalParameters = this.parseFormalParameters(); + if (formalParameters.params.length > 0) { + this.tolerateError(messages_1.Messages.BadGetterArity); + } + var method = this.parsePropertyMethod(formalParameters); + this.context.allowYield = previousAllowYield; + return this.finalize(node, new Node.FunctionExpression(null, formalParameters.params, method, isGenerator)); + }; + Parser.prototype.parseSetterMethod = function () { + var node = this.createNode(); + var isGenerator = false; + var previousAllowYield = this.context.allowYield; + this.context.allowYield = !isGenerator; + var formalParameters = this.parseFormalParameters(); + if (formalParameters.params.length !== 1) { + this.tolerateError(messages_1.Messages.BadSetterArity); + } + else if (formalParameters.params[0] instanceof Node.RestElement) { + this.tolerateError(messages_1.Messages.BadSetterRestParameter); + } + var method = this.parsePropertyMethod(formalParameters); + this.context.allowYield = previousAllowYield; + return this.finalize(node, new Node.FunctionExpression(null, formalParameters.params, method, isGenerator)); + }; + Parser.prototype.parseGeneratorMethod = function () { + var node = this.createNode(); + var isGenerator = true; + var previousAllowYield = this.context.allowYield; + this.context.allowYield = true; + var params = this.parseFormalParameters(); + this.context.allowYield = false; + var method = this.parsePropertyMethod(params); + this.context.allowYield = previousAllowYield; + return this.finalize(node, new Node.FunctionExpression(null, params.params, method, isGenerator)); + }; + // https://tc39.github.io/ecma262/#sec-generator-function-definitions + Parser.prototype.isStartOfExpression = function () { + var start = true; + var value = this.lookahead.value; + switch (this.lookahead.type) { + case 7 /* Punctuator */: + start = (value === '[') || (value === '(') || (value === '{') || + (value === '+') || (value === '-') || + (value === '!') || (value === '~') || + (value === '++') || (value === '--') || + (value === '/') || (value === '/='); // regular expression literal + break; + case 4 /* Keyword */: + start = (value === 'class') || (value === 'delete') || + (value === 'function') || (value === 'let') || (value === 'new') || + (value === 'super') || (value === 'this') || (value === 'typeof') || + (value === 'void') || (value === 'yield'); + break; + default: + break; + } + return start; + }; + Parser.prototype.parseYieldExpression = function () { + var node = this.createNode(); + this.expectKeyword('yield'); + var argument = null; + var delegate = false; + if (!this.hasLineTerminator) { + var previousAllowYield = this.context.allowYield; + this.context.allowYield = false; + delegate = this.match('*'); + if (delegate) { + this.nextToken(); + argument = this.parseAssignmentExpression(); + } + else if (this.isStartOfExpression()) { + argument = this.parseAssignmentExpression(); + } + this.context.allowYield = previousAllowYield; + } + return this.finalize(node, new Node.YieldExpression(argument, delegate)); + }; + // https://tc39.github.io/ecma262/#sec-class-definitions + Parser.prototype.parseClassElement = function (hasConstructor) { + var token = this.lookahead; + var node = this.createNode(); + var kind = ''; + var key = null; + var value = null; + var computed = false; + var method = false; + var isStatic = false; + var isAsync = false; + if (this.match('*')) { + this.nextToken(); + } + else { + computed = this.match('['); + key = this.parseObjectPropertyKey(); + var id = key; + if (id.name === 'static' && (this.qualifiedPropertyName(this.lookahead) || this.match('*'))) { + token = this.lookahead; + isStatic = true; + computed = this.match('['); + if (this.match('*')) { + this.nextToken(); + } + else { + key = this.parseObjectPropertyKey(); + } + } + if ((token.type === 3 /* Identifier */) && !this.hasLineTerminator && (token.value === 'async')) { + var punctuator = this.lookahead.value; + if (punctuator !== ':' && punctuator !== '(' && punctuator !== '*') { + isAsync = true; + token = this.lookahead; + key = this.parseObjectPropertyKey(); + if (token.type === 3 /* Identifier */ && token.value === 'constructor') { + this.tolerateUnexpectedToken(token, messages_1.Messages.ConstructorIsAsync); + } + } + } + } + var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead); + if (token.type === 3 /* Identifier */) { + if (token.value === 'get' && lookaheadPropertyKey) { + kind = 'get'; + computed = this.match('['); + key = this.parseObjectPropertyKey(); + this.context.allowYield = false; + value = this.parseGetterMethod(); + } + else if (token.value === 'set' && lookaheadPropertyKey) { + kind = 'set'; + computed = this.match('['); + key = this.parseObjectPropertyKey(); + value = this.parseSetterMethod(); + } + } + else if (token.type === 7 /* Punctuator */ && token.value === '*' && lookaheadPropertyKey) { + kind = 'init'; + computed = this.match('['); + key = this.parseObjectPropertyKey(); + value = this.parseGeneratorMethod(); + method = true; + } + if (!kind && key && this.match('(')) { + kind = 'init'; + value = isAsync ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction(); + method = true; + } + if (!kind) { + this.throwUnexpectedToken(this.lookahead); + } + if (kind === 'init') { + kind = 'method'; + } + if (!computed) { + if (isStatic && this.isPropertyKey(key, 'prototype')) { + this.throwUnexpectedToken(token, messages_1.Messages.StaticPrototype); + } + if (!isStatic && this.isPropertyKey(key, 'constructor')) { + if (kind !== 'method' || !method || (value && value.generator)) { + this.throwUnexpectedToken(token, messages_1.Messages.ConstructorSpecialMethod); + } + if (hasConstructor.value) { + this.throwUnexpectedToken(token, messages_1.Messages.DuplicateConstructor); + } + else { + hasConstructor.value = true; + } + kind = 'constructor'; + } + } + return this.finalize(node, new Node.MethodDefinition(key, computed, value, kind, isStatic)); + }; + Parser.prototype.parseClassElementList = function () { + var body = []; + var hasConstructor = { value: false }; + this.expect('{'); + while (!this.match('}')) { + if (this.match(';')) { + this.nextToken(); + } + else { + body.push(this.parseClassElement(hasConstructor)); + } + } + this.expect('}'); + return body; + }; + Parser.prototype.parseClassBody = function () { + var node = this.createNode(); + var elementList = this.parseClassElementList(); + return this.finalize(node, new Node.ClassBody(elementList)); + }; + Parser.prototype.parseClassDeclaration = function (identifierIsOptional) { + var node = this.createNode(); + var previousStrict = this.context.strict; + this.context.strict = true; + this.expectKeyword('class'); + var id = (identifierIsOptional && (this.lookahead.type !== 3 /* Identifier */)) ? null : this.parseVariableIdentifier(); + var superClass = null; + if (this.matchKeyword('extends')) { + this.nextToken(); + superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall); + } + var classBody = this.parseClassBody(); + this.context.strict = previousStrict; + return this.finalize(node, new Node.ClassDeclaration(id, superClass, classBody)); + }; + Parser.prototype.parseClassExpression = function () { + var node = this.createNode(); + var previousStrict = this.context.strict; + this.context.strict = true; + this.expectKeyword('class'); + var id = (this.lookahead.type === 3 /* Identifier */) ? this.parseVariableIdentifier() : null; + var superClass = null; + if (this.matchKeyword('extends')) { + this.nextToken(); + superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall); + } + var classBody = this.parseClassBody(); + this.context.strict = previousStrict; + return this.finalize(node, new Node.ClassExpression(id, superClass, classBody)); + }; + // https://tc39.github.io/ecma262/#sec-scripts + // https://tc39.github.io/ecma262/#sec-modules + Parser.prototype.parseModule = function () { + this.context.strict = true; + this.context.isModule = true; + this.scanner.isModule = true; + var node = this.createNode(); + var body = this.parseDirectivePrologues(); + while (this.lookahead.type !== 2 /* EOF */) { + body.push(this.parseStatementListItem()); + } + return this.finalize(node, new Node.Module(body)); + }; + Parser.prototype.parseScript = function () { + var node = this.createNode(); + var body = this.parseDirectivePrologues(); + while (this.lookahead.type !== 2 /* EOF */) { + body.push(this.parseStatementListItem()); + } + return this.finalize(node, new Node.Script(body)); + }; + // https://tc39.github.io/ecma262/#sec-imports + Parser.prototype.parseModuleSpecifier = function () { + var node = this.createNode(); + if (this.lookahead.type !== 8 /* StringLiteral */) { + this.throwError(messages_1.Messages.InvalidModuleSpecifier); + } + var token = this.nextToken(); + var raw = this.getTokenRaw(token); + return this.finalize(node, new Node.Literal(token.value, raw)); + }; + // import {} ...; + Parser.prototype.parseImportSpecifier = function () { + var node = this.createNode(); + var imported; + var local; + if (this.lookahead.type === 3 /* Identifier */) { + imported = this.parseVariableIdentifier(); + local = imported; + if (this.matchContextualKeyword('as')) { + this.nextToken(); + local = this.parseVariableIdentifier(); + } + } + else { + imported = this.parseIdentifierName(); + local = imported; + if (this.matchContextualKeyword('as')) { + this.nextToken(); + local = this.parseVariableIdentifier(); + } + else { + this.throwUnexpectedToken(this.nextToken()); + } + } + return this.finalize(node, new Node.ImportSpecifier(local, imported)); + }; + // {foo, bar as bas} + Parser.prototype.parseNamedImports = function () { + this.expect('{'); + var specifiers = []; + while (!this.match('}')) { + specifiers.push(this.parseImportSpecifier()); + if (!this.match('}')) { + this.expect(','); + } + } + this.expect('}'); + return specifiers; + }; + // import ...; + Parser.prototype.parseImportDefaultSpecifier = function () { + var node = this.createNode(); + var local = this.parseIdentifierName(); + return this.finalize(node, new Node.ImportDefaultSpecifier(local)); + }; + // import <* as foo> ...; + Parser.prototype.parseImportNamespaceSpecifier = function () { + var node = this.createNode(); + this.expect('*'); + if (!this.matchContextualKeyword('as')) { + this.throwError(messages_1.Messages.NoAsAfterImportNamespace); + } + this.nextToken(); + var local = this.parseIdentifierName(); + return this.finalize(node, new Node.ImportNamespaceSpecifier(local)); + }; + Parser.prototype.parseImportDeclaration = function () { + if (this.context.inFunctionBody) { + this.throwError(messages_1.Messages.IllegalImportDeclaration); + } + var node = this.createNode(); + this.expectKeyword('import'); + var src; + var specifiers = []; + if (this.lookahead.type === 8 /* StringLiteral */) { + // import 'foo'; + src = this.parseModuleSpecifier(); + } + else { + if (this.match('{')) { + // import {bar} + specifiers = specifiers.concat(this.parseNamedImports()); + } + else if (this.match('*')) { + // import * as foo + specifiers.push(this.parseImportNamespaceSpecifier()); + } + else if (this.isIdentifierName(this.lookahead) && !this.matchKeyword('default')) { + // import foo + specifiers.push(this.parseImportDefaultSpecifier()); + if (this.match(',')) { + this.nextToken(); + if (this.match('*')) { + // import foo, * as foo + specifiers.push(this.parseImportNamespaceSpecifier()); + } + else if (this.match('{')) { + // import foo, {bar} + specifiers = specifiers.concat(this.parseNamedImports()); + } + else { + this.throwUnexpectedToken(this.lookahead); + } + } + } + else { + this.throwUnexpectedToken(this.nextToken()); + } + if (!this.matchContextualKeyword('from')) { + var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause; + this.throwError(message, this.lookahead.value); + } + this.nextToken(); + src = this.parseModuleSpecifier(); + } + this.consumeSemicolon(); + return this.finalize(node, new Node.ImportDeclaration(specifiers, src)); + }; + // https://tc39.github.io/ecma262/#sec-exports + Parser.prototype.parseExportSpecifier = function () { + var node = this.createNode(); + var local = this.parseIdentifierName(); + var exported = local; + if (this.matchContextualKeyword('as')) { + this.nextToken(); + exported = this.parseIdentifierName(); + } + return this.finalize(node, new Node.ExportSpecifier(local, exported)); + }; + Parser.prototype.parseExportDeclaration = function () { + if (this.context.inFunctionBody) { + this.throwError(messages_1.Messages.IllegalExportDeclaration); + } + var node = this.createNode(); + this.expectKeyword('export'); + var exportDeclaration; + if (this.matchKeyword('default')) { + // export default ... + this.nextToken(); + if (this.matchKeyword('function')) { + // export default function foo () {} + // export default function () {} + var declaration = this.parseFunctionDeclaration(true); + exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration)); + } + else if (this.matchKeyword('class')) { + // export default class foo {} + var declaration = this.parseClassDeclaration(true); + exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration)); + } + else if (this.matchContextualKeyword('async')) { + // export default async function f () {} + // export default async function () {} + // export default async x => x + var declaration = this.matchAsyncFunction() ? this.parseFunctionDeclaration(true) : this.parseAssignmentExpression(); + exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration)); + } + else { + if (this.matchContextualKeyword('from')) { + this.throwError(messages_1.Messages.UnexpectedToken, this.lookahead.value); + } + // export default {}; + // export default []; + // export default (1 + 2); + var declaration = this.match('{') ? this.parseObjectInitializer() : + this.match('[') ? this.parseArrayInitializer() : this.parseAssignmentExpression(); + this.consumeSemicolon(); + exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration)); + } + } + else if (this.match('*')) { + // export * from 'foo'; + this.nextToken(); + if (!this.matchContextualKeyword('from')) { + var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause; + this.throwError(message, this.lookahead.value); + } + this.nextToken(); + var src = this.parseModuleSpecifier(); + this.consumeSemicolon(); + exportDeclaration = this.finalize(node, new Node.ExportAllDeclaration(src)); + } + else if (this.lookahead.type === 4 /* Keyword */) { + // export var f = 1; + var declaration = void 0; + switch (this.lookahead.value) { + case 'let': + case 'const': + declaration = this.parseLexicalDeclaration({ inFor: false }); + break; + case 'var': + case 'class': + case 'function': + declaration = this.parseStatementListItem(); + break; + default: + this.throwUnexpectedToken(this.lookahead); + } + exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(declaration, [], null)); + } + else if (this.matchAsyncFunction()) { + var declaration = this.parseFunctionDeclaration(); + exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(declaration, [], null)); + } + else { + var specifiers = []; + var source = null; + var isExportFromIdentifier = false; + this.expect('{'); + while (!this.match('}')) { + isExportFromIdentifier = isExportFromIdentifier || this.matchKeyword('default'); + specifiers.push(this.parseExportSpecifier()); + if (!this.match('}')) { + this.expect(','); + } + } + this.expect('}'); + if (this.matchContextualKeyword('from')) { + // export {default} from 'foo'; + // export {foo} from 'foo'; + this.nextToken(); + source = this.parseModuleSpecifier(); + this.consumeSemicolon(); + } + else if (isExportFromIdentifier) { + // export {default}; // missing fromClause + var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause; + this.throwError(message, this.lookahead.value); + } + else { + // export {foo}; + this.consumeSemicolon(); + } + exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(null, specifiers, source)); + } + return exportDeclaration; + }; + return Parser; + }()); + exports.Parser = Parser; + + +/***/ }, +/* 9 */ +/***/ function(module, exports) { + + "use strict"; + // Ensure the condition is true, otherwise throw an error. + // This is only to have a better contract semantic, i.e. another safety net + // to catch a logic error. The condition shall be fulfilled in normal case. + // Do NOT use this to enforce a certain condition on any user input. + Object.defineProperty(exports, "__esModule", { value: true }); + function assert(condition, message) { + /* istanbul ignore if */ + if (!condition) { + throw new Error('ASSERT: ' + message); + } + } + exports.assert = assert; + + +/***/ }, +/* 10 */ +/***/ function(module, exports) { + + "use strict"; + /* tslint:disable:max-classes-per-file */ + Object.defineProperty(exports, "__esModule", { value: true }); + var ErrorHandler = (function () { + function ErrorHandler() { + this.errors = []; + this.tolerant = false; + } + ErrorHandler.prototype.recordError = function (error) { + this.errors.push(error); + }; + ErrorHandler.prototype.tolerate = function (error) { + if (this.tolerant) { + this.recordError(error); + } + else { + throw error; + } + }; + ErrorHandler.prototype.constructError = function (msg, column) { + var error = new Error(msg); + try { + throw error; + } + catch (base) { + /* istanbul ignore else */ + if (Object.create && Object.defineProperty) { + error = Object.create(base); + Object.defineProperty(error, 'column', { value: column }); + } + } + /* istanbul ignore next */ + return error; + }; + ErrorHandler.prototype.createError = function (index, line, col, description) { + var msg = 'Line ' + line + ': ' + description; + var error = this.constructError(msg, col); + error.index = index; + error.lineNumber = line; + error.description = description; + return error; + }; + ErrorHandler.prototype.throwError = function (index, line, col, description) { + throw this.createError(index, line, col, description); + }; + ErrorHandler.prototype.tolerateError = function (index, line, col, description) { + var error = this.createError(index, line, col, description); + if (this.tolerant) { + this.recordError(error); + } + else { + throw error; + } + }; + return ErrorHandler; + }()); + exports.ErrorHandler = ErrorHandler; + + +/***/ }, +/* 11 */ +/***/ function(module, exports) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + // Error messages should be identical to V8. + exports.Messages = { + BadGetterArity: 'Getter must not have any formal parameters', + BadSetterArity: 'Setter must have exactly one formal parameter', + BadSetterRestParameter: 'Setter function argument must not be a rest parameter', + ConstructorIsAsync: 'Class constructor may not be an async method', + ConstructorSpecialMethod: 'Class constructor may not be an accessor', + DeclarationMissingInitializer: 'Missing initializer in %0 declaration', + DefaultRestParameter: 'Unexpected token =', + DuplicateBinding: 'Duplicate binding %0', + DuplicateConstructor: 'A class may only have one constructor', + DuplicateProtoProperty: 'Duplicate __proto__ fields are not allowed in object literals', + ForInOfLoopInitializer: '%0 loop variable declaration may not have an initializer', + GeneratorInLegacyContext: 'Generator declarations are not allowed in legacy contexts', + IllegalBreak: 'Illegal break statement', + IllegalContinue: 'Illegal continue statement', + IllegalExportDeclaration: 'Unexpected token', + IllegalImportDeclaration: 'Unexpected token', + IllegalLanguageModeDirective: 'Illegal \'use strict\' directive in function with non-simple parameter list', + IllegalReturn: 'Illegal return statement', + InvalidEscapedReservedWord: 'Keyword must not contain escaped characters', + InvalidHexEscapeSequence: 'Invalid hexadecimal escape sequence', + InvalidLHSInAssignment: 'Invalid left-hand side in assignment', + InvalidLHSInForIn: 'Invalid left-hand side in for-in', + InvalidLHSInForLoop: 'Invalid left-hand side in for-loop', + InvalidModuleSpecifier: 'Unexpected token', + InvalidRegExp: 'Invalid regular expression', + LetInLexicalBinding: 'let is disallowed as a lexically bound name', + MissingFromClause: 'Unexpected token', + MultipleDefaultsInSwitch: 'More than one default clause in switch statement', + NewlineAfterThrow: 'Illegal newline after throw', + NoAsAfterImportNamespace: 'Unexpected token', + NoCatchOrFinally: 'Missing catch or finally after try', + ParameterAfterRestParameter: 'Rest parameter must be last formal parameter', + Redeclaration: '%0 \'%1\' has already been declared', + StaticPrototype: 'Classes may not have static property named prototype', + StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode', + StrictDelete: 'Delete of an unqualified identifier in strict mode.', + StrictFunction: 'In strict mode code, functions can only be declared at top level or inside a block', + StrictFunctionName: 'Function name may not be eval or arguments in strict mode', + StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode', + StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode', + StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode', + StrictModeWith: 'Strict mode code may not include a with statement', + StrictOctalLiteral: 'Octal literals are not allowed in strict mode.', + StrictParamDupe: 'Strict mode function may not have duplicate parameter names', + StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode', + StrictReservedWord: 'Use of future reserved word in strict mode', + StrictVarName: 'Variable name may not be eval or arguments in strict mode', + TemplateOctalLiteral: 'Octal literals are not allowed in template strings.', + UnexpectedEOS: 'Unexpected end of input', + UnexpectedIdentifier: 'Unexpected identifier', + UnexpectedNumber: 'Unexpected number', + UnexpectedReserved: 'Unexpected reserved word', + UnexpectedString: 'Unexpected string', + UnexpectedTemplate: 'Unexpected quasi %0', + UnexpectedToken: 'Unexpected token %0', + UnexpectedTokenIllegal: 'Unexpected token ILLEGAL', + UnknownLabel: 'Undefined label \'%0\'', + UnterminatedRegExp: 'Invalid regular expression: missing /' + }; + + +/***/ }, +/* 12 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var assert_1 = __webpack_require__(9); + var character_1 = __webpack_require__(4); + var messages_1 = __webpack_require__(11); + function hexValue(ch) { + return '0123456789abcdef'.indexOf(ch.toLowerCase()); + } + function octalValue(ch) { + return '01234567'.indexOf(ch); + } + var Scanner = (function () { + function Scanner(code, handler) { + this.source = code; + this.errorHandler = handler; + this.trackComment = false; + this.isModule = false; + this.length = code.length; + this.index = 0; + this.lineNumber = (code.length > 0) ? 1 : 0; + this.lineStart = 0; + this.curlyStack = []; + } + Scanner.prototype.saveState = function () { + return { + index: this.index, + lineNumber: this.lineNumber, + lineStart: this.lineStart + }; + }; + Scanner.prototype.restoreState = function (state) { + this.index = state.index; + this.lineNumber = state.lineNumber; + this.lineStart = state.lineStart; + }; + Scanner.prototype.eof = function () { + return this.index >= this.length; + }; + Scanner.prototype.throwUnexpectedToken = function (message) { + if (message === void 0) { message = messages_1.Messages.UnexpectedTokenIllegal; } + return this.errorHandler.throwError(this.index, this.lineNumber, this.index - this.lineStart + 1, message); + }; + Scanner.prototype.tolerateUnexpectedToken = function (message) { + if (message === void 0) { message = messages_1.Messages.UnexpectedTokenIllegal; } + this.errorHandler.tolerateError(this.index, this.lineNumber, this.index - this.lineStart + 1, message); + }; + // https://tc39.github.io/ecma262/#sec-comments + Scanner.prototype.skipSingleLineComment = function (offset) { + var comments = []; + var start, loc; + if (this.trackComment) { + comments = []; + start = this.index - offset; + loc = { + start: { + line: this.lineNumber, + column: this.index - this.lineStart - offset + }, + end: {} + }; + } + while (!this.eof()) { + var ch = this.source.charCodeAt(this.index); + ++this.index; + if (character_1.Character.isLineTerminator(ch)) { + if (this.trackComment) { + loc.end = { + line: this.lineNumber, + column: this.index - this.lineStart - 1 + }; + var entry = { + multiLine: false, + slice: [start + offset, this.index - 1], + range: [start, this.index - 1], + loc: loc + }; + comments.push(entry); + } + if (ch === 13 && this.source.charCodeAt(this.index) === 10) { + ++this.index; + } + ++this.lineNumber; + this.lineStart = this.index; + return comments; + } + } + if (this.trackComment) { + loc.end = { + line: this.lineNumber, + column: this.index - this.lineStart + }; + var entry = { + multiLine: false, + slice: [start + offset, this.index], + range: [start, this.index], + loc: loc + }; + comments.push(entry); + } + return comments; + }; + Scanner.prototype.skipMultiLineComment = function () { + var comments = []; + var start, loc; + if (this.trackComment) { + comments = []; + start = this.index - 2; + loc = { + start: { + line: this.lineNumber, + column: this.index - this.lineStart - 2 + }, + end: {} + }; + } + while (!this.eof()) { + var ch = this.source.charCodeAt(this.index); + if (character_1.Character.isLineTerminator(ch)) { + if (ch === 0x0D && this.source.charCodeAt(this.index + 1) === 0x0A) { + ++this.index; + } + ++this.lineNumber; + ++this.index; + this.lineStart = this.index; + } + else if (ch === 0x2A) { + // Block comment ends with '*/'. + if (this.source.charCodeAt(this.index + 1) === 0x2F) { + this.index += 2; + if (this.trackComment) { + loc.end = { + line: this.lineNumber, + column: this.index - this.lineStart + }; + var entry = { + multiLine: true, + slice: [start + 2, this.index - 2], + range: [start, this.index], + loc: loc + }; + comments.push(entry); + } + return comments; + } + ++this.index; + } + else { + ++this.index; + } + } + // Ran off the end of the file - the whole thing is a comment + if (this.trackComment) { + loc.end = { + line: this.lineNumber, + column: this.index - this.lineStart + }; + var entry = { + multiLine: true, + slice: [start + 2, this.index], + range: [start, this.index], + loc: loc + }; + comments.push(entry); + } + this.tolerateUnexpectedToken(); + return comments; + }; + Scanner.prototype.scanComments = function () { + var comments; + if (this.trackComment) { + comments = []; + } + var start = (this.index === 0); + while (!this.eof()) { + var ch = this.source.charCodeAt(this.index); + if (character_1.Character.isWhiteSpace(ch)) { + ++this.index; + } + else if (character_1.Character.isLineTerminator(ch)) { + ++this.index; + if (ch === 0x0D && this.source.charCodeAt(this.index) === 0x0A) { + ++this.index; + } + ++this.lineNumber; + this.lineStart = this.index; + start = true; + } + else if (ch === 0x2F) { + ch = this.source.charCodeAt(this.index + 1); + if (ch === 0x2F) { + this.index += 2; + var comment = this.skipSingleLineComment(2); + if (this.trackComment) { + comments = comments.concat(comment); + } + start = true; + } + else if (ch === 0x2A) { + this.index += 2; + var comment = this.skipMultiLineComment(); + if (this.trackComment) { + comments = comments.concat(comment); + } + } + else { + break; + } + } + else if (start && ch === 0x2D) { + // U+003E is '>' + if ((this.source.charCodeAt(this.index + 1) === 0x2D) && (this.source.charCodeAt(this.index + 2) === 0x3E)) { + // '-->' is a single-line comment + this.index += 3; + var comment = this.skipSingleLineComment(3); + if (this.trackComment) { + comments = comments.concat(comment); + } + } + else { + break; + } + } + else if (ch === 0x3C && !this.isModule) { + if (this.source.slice(this.index + 1, this.index + 4) === '!--') { + this.index += 4; // `'})); +``` + +**Example** + +The following HTML string: + +```html +--- +title: Blog +--- +My awesome blog. + +

Hello world

+``` + +Results in: + +```js +{ + data: { title: 'Blog'}, + excerpt: 'My awesome blog.', + content: 'My awesome blog.\n\n

Hello world

' +} +``` + +### options.engines + +Define custom engines for parsing and/or stringifying front-matter. + +**Type**: `Object` Object of engines + +**Default**: `JSON`, `YAML` and `JavaScript` are already handled by default. + +**Engine format** + +Engines may either be an object with `parse` and (optionally) `stringify` methods, or a function that will be used for parsing only. + +**Examples** + +```js +const toml = require('toml'); + +/** + * defined as a function + */ + +const file = matter(str, { + engines: { + toml: toml.parse.bind(toml), + } +}); + +/** + * Or as an object + */ + +const file = matter(str, { + engines: { + toml: { + parse: toml.parse.bind(toml), + + // example of throwing an error to let users know stringifying is + // not supported (a TOML stringifier might exist, this is just an example) + stringify: function() { + throw new Error('cannot stringify to TOML'); + } + } + } +}); + +console.log(file); +``` + +### options.language + +**Type**: `String` + +**Default**: `yaml` + +Define the engine to use for parsing front-matter. + +```js +console.log(matter(string, {language: 'toml'})); +``` + +**Example** + +The following HTML string: + +```html +--- +title = "TOML" +description = "Front matter" +categories = "front matter toml" +--- +This is content +``` + +Results in: + +```js +{ content: 'This is content', + excerpt: '', + data: + { title: 'TOML', + description: 'Front matter', + categories: 'front matter toml' } } +``` + +**Dynamic language detection** + +Instead of defining the language on the options, gray-matter will automatically detect the language defined after the first delimiter and select the correct engine to use for parsing. + +```html +---toml +title = "TOML" +description = "Front matter" +categories = "front matter toml" +--- +This is content +``` + +### options.delimiters + +**Type**: `String` + +**Default**: `---` + +Open and close delimiters can be passed in as an array of strings. + +**Example:** + +```js +// format delims as a string +matter.read('file.md', {delims: '~~~'}); +// or an array (open/close) +matter.read('file.md', {delims: ['~~~', '~~~']}); +``` + +would parse: + +```html +~~~ +title: Home +~~~ +This is the {{title}} page. +``` + +## Deprecated options + +### options.lang + +Decrecated, please use [options.language](#optionslanguage) instead. + +### options.delims + +Decrecated, please use [options.delimiters](#optionsdelimiters) instead. + +### options.parsers + +Decrecated, please use [options.engines](#optionsengines) instead. + +## About + +
+Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +
+ +
+Running Tests + +Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: + +```sh +$ npm install && npm test +``` + +
+ +
+Building docs + +_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ + +To generate the readme, run the following command: + +```sh +$ npm install -g verbose/verb#dev verb-generate-readme && verb +``` + +
+ +### Related projects + +You might also be interested in these projects: + +* [assemble](https://www.npmjs.com/package/assemble): Get the rocks out of your socks! Assemble makes you fast at creating web projects… [more](https://github.com/assemble/assemble) | [homepage](https://github.com/assemble/assemble "Get the rocks out of your socks! Assemble makes you fast at creating web projects. Assemble is used by thousands of projects for rapid prototyping, creating themes, scaffolds, boilerplates, e-books, UI components, API documentation, blogs, building websit") +* [metalsmith](https://www.npmjs.com/package/metalsmith): An extremely simple, pluggable static site generator. | [homepage](https://github.com/segmentio/metalsmith#readme "An extremely simple, pluggable static site generator.") +* [verb](https://www.npmjs.com/package/verb): Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used… [more](https://github.com/verbose/verb) | [homepage](https://github.com/verbose/verb "Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used on hundreds of projects of all sizes to generate everything from API docs to readmes.") +* [gray-matter-loader](https://github.com/atlassian/gray-matter-loader): A webpack loader for gray-matter. [homepage](https://github.com/atlassian/gray-matter-loader#gray-matter-loader) + +### Contributors + +| **Commits** | **Contributor** | +| --- | --- | +| 174 | [jonschlinkert](https://github.com/jonschlinkert) | +| 7 | [RobLoach](https://github.com/RobLoach) | +| 5 | [heymind](https://github.com/heymind) | +| 4 | [doowb](https://github.com/doowb) | +| 3 | [aljopro](https://github.com/aljopro) | +| 2 | [reccanti](https://github.com/reccanti) | +| 2 | [onokumus](https://github.com/onokumus) | +| 2 | [moozzyk](https://github.com/moozzyk) | +| 1 | [Ajedi32](https://github.com/Ajedi32) | +| 1 | [caesar](https://github.com/caesar) | +| 1 | [ianstormtaylor](https://github.com/ianstormtaylor) | +| 1 | [qm3ster](https://github.com/qm3ster) | +| 1 | [zachwhaley](https://github.com/zachwhaley) | + +### Author + +**Jon Schlinkert** + +* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) +* [GitHub Profile](https://github.com/jonschlinkert) +* [Twitter Profile](https://twitter.com/jonschlinkert) + +### License + +Copyright © 2018, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT License](LICENSE). + +*** + +_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on April 01, 2018._ \ No newline at end of file diff --git a/scripts/node_modules/gray-matter/gray-matter.d.ts b/scripts/node_modules/gray-matter/gray-matter.d.ts new file mode 100644 index 000000000..dec9c09b2 --- /dev/null +++ b/scripts/node_modules/gray-matter/gray-matter.d.ts @@ -0,0 +1,114 @@ +/** + * Takes a string or object with `content` property, extracts + * and parses front-matter from the string, then returns an object + * with `data`, `content` and other [useful properties](#returned-object). + * + * ```js + * var matter = require('gray-matter'); + * console.log(matter('---\ntitle: Home\n---\nOther stuff')); + * //=> { data: { title: 'Home'}, content: 'Other stuff' } + * ``` + * @param {Object|String} `input` String, or object with `content` string + * @param {Object} `options` + * @return {Object} + * @api public + */ +declare function matter< + I extends matter.Input, + O extends matter.GrayMatterOption +>(input: I | { content: I }, options?: O): matter.GrayMatterFile + +declare namespace matter { + type Input = string | Buffer + interface GrayMatterOption< + I extends Input, + O extends GrayMatterOption + > { + parser?: () => void + eval?: boolean + excerpt?: boolean | ((input: I, options: O) => string) + excerpt_separator?: string + engines?: { + [index: string]: + | ((input: string) => object) + | { parse: (input: string) => object; stringify?: (data: object) => string } + } + language?: string + delimiters?: string | [string, string] + } + interface GrayMatterFile { + data: { [key: string]: any } + content: string + excerpt?: string + orig: Buffer | I + language: string + matter: string + stringify(lang: string): string + } + + /** + * Stringify an object to YAML or the specified language, and + * append it to the given string. By default, only YAML and JSON + * can be stringified. See the [engines](#engines) section to learn + * how to stringify other languages. + * + * ```js + * console.log(matter.stringify('foo bar baz', {title: 'Home'})); + * // results in: + * // --- + * // title: Home + * // --- + * // foo bar baz + * ``` + * @param {String|Object} `file` The content string to append to stringified front-matter, or a file object with `file.content` string. + * @param {Object} `data` Front matter to stringify. + * @param {Object} `options` [Options](#options) to pass to gray-matter and [js-yaml]. + * @return {String} Returns a string created by wrapping stringified yaml with delimiters, and appending that to the given string. + */ + export function stringify>( + file: string | { content: string }, + data: object, + options?: GrayMatterOption + ): string + + /** + * Synchronously read a file from the file system and parse + * front matter. Returns the same object as the [main function](#matter). + * + * ```js + * var file = matter.read('./content/blog-post.md'); + * ``` + * @param {String} `filepath` file path of the file to read. + * @param {Object} `options` [Options](#options) to pass to gray-matter. + * @return {Object} Returns [an object](#returned-object) with `data` and `content` + */ + export function read>( + fp: string, + options?: GrayMatterOption + ): matter.GrayMatterFile + + /** + * Returns true if the given `string` has front matter. + * @param {String} `string` + * @param {Object} `options` + * @return {Boolean} True if front matter exists. + */ + export function test>( + str: string, + options?: GrayMatterOption + ): boolean + + /** + * Detect the language to use, if one is defined after the + * first front-matter delimiter. + * @param {String} `string` + * @param {Object} `options` + * @return {Object} Object with `raw` (actual language string), and `name`, the language with whitespace trimmed + */ + export function language>( + str: string, + options?: GrayMatterOption + ): { name: string; raw: string } +} + +export = matter diff --git a/scripts/node_modules/gray-matter/index.js b/scripts/node_modules/gray-matter/index.js new file mode 100644 index 000000000..7d4933198 --- /dev/null +++ b/scripts/node_modules/gray-matter/index.js @@ -0,0 +1,228 @@ +'use strict'; + +const fs = require('fs'); +const sections = require('section-matter'); +const defaults = require('./lib/defaults'); +const stringify = require('./lib/stringify'); +const excerpt = require('./lib/excerpt'); +const engines = require('./lib/engines'); +const toFile = require('./lib/to-file'); +const parse = require('./lib/parse'); +const utils = require('./lib/utils'); + +/** + * Takes a string or object with `content` property, extracts + * and parses front-matter from the string, then returns an object + * with `data`, `content` and other [useful properties](#returned-object). + * + * ```js + * const matter = require('gray-matter'); + * console.log(matter('---\ntitle: Home\n---\nOther stuff')); + * //=> { data: { title: 'Home'}, content: 'Other stuff' } + * ``` + * @param {Object|String} `input` String, or object with `content` string + * @param {Object} `options` + * @return {Object} + * @api public + */ + +function matter(input, options) { + if (input === '') { + return { data: {}, content: input, excerpt: '', orig: input }; + } + + let file = toFile(input); + const cached = matter.cache[file.content]; + + if (!options) { + if (cached) { + file = Object.assign({}, cached); + file.orig = cached.orig; + return file; + } + + // only cache if there are no options passed. if we cache when options + // are passed, we would need to also cache options values, which would + // negate any performance benefits of caching + matter.cache[file.content] = file; + } + + return parseMatter(file, options); +} + +/** + * Parse front matter + */ + +function parseMatter(file, options) { + const opts = defaults(options); + const open = opts.delimiters[0]; + const close = '\n' + opts.delimiters[1]; + let str = file.content; + + if (opts.language) { + file.language = opts.language; + } + + // get the length of the opening delimiter + const openLen = open.length; + if (!utils.startsWith(str, open, openLen)) { + excerpt(file, opts); + return file; + } + + // if the next character after the opening delimiter is + // a character from the delimiter, then it's not a front- + // matter delimiter + if (str.charAt(openLen) === open.slice(-1)) { + return file; + } + + // strip the opening delimiter + str = str.slice(openLen); + const len = str.length; + + // use the language defined after first delimiter, if it exists + const language = matter.language(str, opts); + if (language.name) { + file.language = language.name; + str = str.slice(language.raw.length); + } + + // get the index of the closing delimiter + let closeIndex = str.indexOf(close); + if (closeIndex === -1) { + closeIndex = len; + } + + // get the raw front-matter block + file.matter = str.slice(0, closeIndex); + + const block = file.matter.replace(/^\s*#[^\n]+/gm, '').trim(); + if (block === '') { + file.isEmpty = true; + file.empty = file.content; + file.data = {}; + } else { + + // create file.data by parsing the raw file.matter block + file.data = parse(file.language, file.matter, opts); + } + + // update file.content + if (closeIndex === len) { + file.content = ''; + } else { + file.content = str.slice(closeIndex + close.length); + if (file.content[0] === '\r') { + file.content = file.content.slice(1); + } + if (file.content[0] === '\n') { + file.content = file.content.slice(1); + } + } + + excerpt(file, opts); + + if (opts.sections === true || typeof opts.section === 'function') { + sections(file, opts.section); + } + return file; +} + +/** + * Expose engines + */ + +matter.engines = engines; + +/** + * Stringify an object to YAML or the specified language, and + * append it to the given string. By default, only YAML and JSON + * can be stringified. See the [engines](#engines) section to learn + * how to stringify other languages. + * + * ```js + * console.log(matter.stringify('foo bar baz', {title: 'Home'})); + * // results in: + * // --- + * // title: Home + * // --- + * // foo bar baz + * ``` + * @param {String|Object} `file` The content string to append to stringified front-matter, or a file object with `file.content` string. + * @param {Object} `data` Front matter to stringify. + * @param {Object} `options` [Options](#options) to pass to gray-matter and [js-yaml]. + * @return {String} Returns a string created by wrapping stringified yaml with delimiters, and appending that to the given string. + * @api public + */ + +matter.stringify = function(file, data, options) { + if (typeof file === 'string') file = matter(file, options); + return stringify(file, data, options); +}; + +/** + * Synchronously read a file from the file system and parse + * front matter. Returns the same object as the [main function](#matter). + * + * ```js + * const file = matter.read('./content/blog-post.md'); + * ``` + * @param {String} `filepath` file path of the file to read. + * @param {Object} `options` [Options](#options) to pass to gray-matter. + * @return {Object} Returns [an object](#returned-object) with `data` and `content` + * @api public + */ + +matter.read = function(filepath, options) { + const str = fs.readFileSync(filepath, 'utf8'); + const file = matter(str, options); + file.path = filepath; + return file; +}; + +/** + * Returns true if the given `string` has front matter. + * @param {String} `string` + * @param {Object} `options` + * @return {Boolean} True if front matter exists. + * @api public + */ + +matter.test = function(str, options) { + return utils.startsWith(str, defaults(options).delimiters[0]); +}; + +/** + * Detect the language to use, if one is defined after the + * first front-matter delimiter. + * @param {String} `string` + * @param {Object} `options` + * @return {Object} Object with `raw` (actual language string), and `name`, the language with whitespace trimmed + */ + +matter.language = function(str, options) { + const opts = defaults(options); + const open = opts.delimiters[0]; + + if (matter.test(str)) { + str = str.slice(open.length); + } + + const language = str.slice(0, str.search(/\r?\n/)); + return { + raw: language, + name: language ? language.trim() : '' + }; +}; + +/** + * Expose `matter` + */ + +matter.cache = {}; +matter.clearCache = function() { + matter.cache = {}; +}; +module.exports = matter; diff --git a/scripts/node_modules/gray-matter/lib/defaults.js b/scripts/node_modules/gray-matter/lib/defaults.js new file mode 100644 index 000000000..81d9e41ec --- /dev/null +++ b/scripts/node_modules/gray-matter/lib/defaults.js @@ -0,0 +1,18 @@ +'use strict'; + +const engines = require('./engines'); +const utils = require('./utils'); + +module.exports = function(options) { + const opts = Object.assign({}, options); + + // ensure that delimiters are an array + opts.delimiters = utils.arrayify(opts.delims || opts.delimiters || '---'); + if (opts.delimiters.length === 1) { + opts.delimiters.push(opts.delimiters[0]); + } + + opts.language = (opts.language || opts.lang || 'yaml').toLowerCase(); + opts.engines = Object.assign({}, engines, opts.parsers, opts.engines); + return opts; +}; diff --git a/scripts/node_modules/gray-matter/lib/engine.js b/scripts/node_modules/gray-matter/lib/engine.js new file mode 100644 index 000000000..d8f6c416f --- /dev/null +++ b/scripts/node_modules/gray-matter/lib/engine.js @@ -0,0 +1,30 @@ +'use strict'; + +module.exports = function(name, options) { + let engine = options.engines[name] || options.engines[aliase(name)]; + if (typeof engine === 'undefined') { + throw new Error('gray-matter engine "' + name + '" is not registered'); + } + if (typeof engine === 'function') { + engine = { parse: engine }; + } + return engine; +}; + +function aliase(name) { + switch (name.toLowerCase()) { + case 'js': + case 'javascript': + return 'javascript'; + case 'coffee': + case 'coffeescript': + case 'cson': + return 'coffee'; + case 'yaml': + case 'yml': + return 'yaml'; + default: { + return name; + } + } +} diff --git a/scripts/node_modules/gray-matter/lib/engines.js b/scripts/node_modules/gray-matter/lib/engines.js new file mode 100644 index 000000000..38f993db0 --- /dev/null +++ b/scripts/node_modules/gray-matter/lib/engines.js @@ -0,0 +1,54 @@ +'use strict'; + +const yaml = require('js-yaml'); + +/** + * Default engines + */ + +const engines = exports = module.exports; + +/** + * YAML + */ + +engines.yaml = { + parse: yaml.safeLoad.bind(yaml), + stringify: yaml.safeDump.bind(yaml) +}; + +/** + * JSON + */ + +engines.json = { + parse: JSON.parse.bind(JSON), + stringify: function(obj, options) { + const opts = Object.assign({replacer: null, space: 2}, options); + return JSON.stringify(obj, opts.replacer, opts.space); + } +}; + +/** + * JavaScript + */ + +engines.javascript = { + parse: function parse(str, options, wrap) { + /* eslint no-eval: 0 */ + try { + if (wrap !== false) { + str = '(function() {\nreturn ' + str.trim() + ';\n}());'; + } + return eval(str) || {}; + } catch (err) { + if (wrap !== false && /(unexpected|identifier)/i.test(err.message)) { + return parse(str, options, false); + } + throw new SyntaxError(err); + } + }, + stringify: function() { + throw new Error('stringifying JavaScript is not supported'); + } +}; diff --git a/scripts/node_modules/gray-matter/lib/excerpt.js b/scripts/node_modules/gray-matter/lib/excerpt.js new file mode 100644 index 000000000..14d990472 --- /dev/null +++ b/scripts/node_modules/gray-matter/lib/excerpt.js @@ -0,0 +1,32 @@ +'use strict'; + +const defaults = require('./defaults'); + +module.exports = function(file, options) { + const opts = defaults(options); + + if (file.data == null) { + file.data = {}; + } + + if (typeof opts.excerpt === 'function') { + return opts.excerpt(file, opts); + } + + const sep = file.data.excerpt_separator || opts.excerpt_separator; + if (sep == null && (opts.excerpt === false || opts.excerpt == null)) { + return file; + } + + const delimiter = typeof opts.excerpt === 'string' + ? opts.excerpt + : (sep || opts.delimiters[0]); + + // if enabled, get the excerpt defined after front-matter + const idx = file.content.indexOf(delimiter); + if (idx !== -1) { + file.excerpt = file.content.slice(0, idx); + } + + return file; +}; diff --git a/scripts/node_modules/gray-matter/lib/parse.js b/scripts/node_modules/gray-matter/lib/parse.js new file mode 100644 index 000000000..e10ea9beb --- /dev/null +++ b/scripts/node_modules/gray-matter/lib/parse.js @@ -0,0 +1,13 @@ +'use strict'; + +const getEngine = require('./engine'); +const defaults = require('./defaults'); + +module.exports = function(language, str, options) { + const opts = defaults(options); + const engine = getEngine(language, opts); + if (typeof engine.parse !== 'function') { + throw new TypeError('expected "' + language + '.parse" to be a function'); + } + return engine.parse(str, opts); +}; diff --git a/scripts/node_modules/gray-matter/lib/stringify.js b/scripts/node_modules/gray-matter/lib/stringify.js new file mode 100644 index 000000000..b4c70a49c --- /dev/null +++ b/scripts/node_modules/gray-matter/lib/stringify.js @@ -0,0 +1,56 @@ +'use strict'; + +const typeOf = require('kind-of'); +const getEngine = require('./engine'); +const defaults = require('./defaults'); + +module.exports = function(file, data, options) { + if (data == null && options == null) { + switch (typeOf(file)) { + case 'object': + data = file.data; + options = {}; + break; + case 'string': + return file; + default: { + throw new TypeError('expected file to be a string or object'); + } + } + } + + const str = file.content; + const opts = defaults(options); + if (data == null) { + if (!opts.data) return file; + data = opts.data; + } + + const language = file.language || opts.language; + const engine = getEngine(language, opts); + if (typeof engine.stringify !== 'function') { + throw new TypeError('expected "' + language + '.stringify" to be a function'); + } + + data = Object.assign({}, file.data, data); + const open = opts.delimiters[0]; + const close = opts.delimiters[1]; + const matter = engine.stringify(data, options).trim(); + let buf = ''; + + if (matter !== '{}') { + buf = newline(open) + newline(matter) + newline(close); + } + + if (typeof file.excerpt === 'string' && file.excerpt !== '') { + if (str.indexOf(file.excerpt.trim()) === -1) { + buf += newline(file.excerpt) + newline(close); + } + } + + return buf + newline(str); +}; + +function newline(str) { + return str.slice(-1) !== '\n' ? str + '\n' : str; +} diff --git a/scripts/node_modules/gray-matter/lib/to-file.js b/scripts/node_modules/gray-matter/lib/to-file.js new file mode 100644 index 000000000..799bb5d9e --- /dev/null +++ b/scripts/node_modules/gray-matter/lib/to-file.js @@ -0,0 +1,43 @@ +'use strict'; + +const typeOf = require('kind-of'); +const stringify = require('./stringify'); +const utils = require('./utils'); + +/** + * Normalize the given value to ensure an object is returned + * with the expected properties. + */ + +module.exports = function(file) { + if (typeOf(file) !== 'object') { + file = { content: file }; + } + + if (typeOf(file.data) !== 'object') { + file.data = {}; + } + + // if file was passed as an object, ensure that + // "file.content" is set + if (file.contents && file.content == null) { + file.content = file.contents; + } + + // set non-enumerable properties on the file object + utils.define(file, 'orig', utils.toBuffer(file.content)); + utils.define(file, 'language', file.language || ''); + utils.define(file, 'matter', file.matter || ''); + utils.define(file, 'stringify', function(data, options) { + if (options && options.language) { + file.language = options.language; + } + return stringify(file, data, options); + }); + + // strip BOM and ensure that "file.content" is a string + file.content = utils.toString(file.content); + file.isEmpty = false; + file.excerpt = ''; + return file; +}; diff --git a/scripts/node_modules/gray-matter/lib/utils.js b/scripts/node_modules/gray-matter/lib/utils.js new file mode 100644 index 000000000..96e7ce020 --- /dev/null +++ b/scripts/node_modules/gray-matter/lib/utils.js @@ -0,0 +1,66 @@ +'use strict'; + +const stripBom = require('strip-bom-string'); +const typeOf = require('kind-of'); + +exports.define = function(obj, key, val) { + Reflect.defineProperty(obj, key, { + enumerable: false, + configurable: true, + writable: true, + value: val + }); +}; + +/** + * Returns true if `val` is a buffer + */ + +exports.isBuffer = function(val) { + return typeOf(val) === 'buffer'; +}; + +/** + * Returns true if `val` is an object + */ + +exports.isObject = function(val) { + return typeOf(val) === 'object'; +}; + +/** + * Cast `input` to a buffer + */ + +exports.toBuffer = function(input) { + return typeof input === 'string' ? Buffer.from(input) : input; +}; + +/** + * Cast `val` to a string. + */ + +exports.toString = function(input) { + if (exports.isBuffer(input)) return stripBom(String(input)); + if (typeof input !== 'string') { + throw new TypeError('expected input to be a string or buffer'); + } + return stripBom(input); +}; + +/** + * Cast `val` to an array. + */ + +exports.arrayify = function(val) { + return val ? (Array.isArray(val) ? val : [val]) : []; +}; + +/** + * Returns true if `str` starts with `substr`. + */ + +exports.startsWith = function(str, substr, len) { + if (typeof len !== 'number') len = substr.length; + return str.slice(0, len) === substr; +}; diff --git a/scripts/node_modules/gray-matter/package.json b/scripts/node_modules/gray-matter/package.json new file mode 100644 index 000000000..c5a1fff75 --- /dev/null +++ b/scripts/node_modules/gray-matter/package.json @@ -0,0 +1,127 @@ +{ + "name": "gray-matter", + "description": "Parse front-matter from a string or file. Fast, reliable and easy to use. Parses YAML front matter by default, but also has support for YAML, JSON, TOML or Coffee Front-Matter, with options to set custom delimiters. Used by metalsmith, assemble, verb and many other projects.", + "version": "4.0.3", + "homepage": "https://github.com/jonschlinkert/gray-matter", + "author": "Jon Schlinkert (https://github.com/jonschlinkert)", + "contributors": [ + "Andrew Meyer (https://github.com/Ajedi32)", + "Brian Woodward (https://twitter.com/doowb)", + "Caesar Schinas (https://caesarschinas.com)", + "Ian Storm Taylor (http://ianstormtaylor.com)", + "Jon Schlinkert (http://twitter.com/jonschlinkert)", + "Osman Nuri Okumuş (http://onokumus.com)", + "Pawel Kadluczka (http://blog.3d-logic.com)", + "Rob Loach (http://robloach.net)", + "(https://github.com/heymind)", + "Zach Whaley (http://zachwhaleys.website)" + ], + "repository": "jonschlinkert/gray-matter", + "bugs": { + "url": "https://github.com/jonschlinkert/gray-matter/issues" + }, + "license": "MIT", + "files": [ + "gray-matter.d.ts", + "index.js", + "lib" + ], + "main": "index.js", + "engines": { + "node": ">=6.0" + }, + "scripts": { + "test": "mocha" + }, + "dependencies": { + "js-yaml": "^3.13.1", + "kind-of": "^6.0.2", + "section-matter": "^1.0.0", + "strip-bom-string": "^1.0.0" + }, + "devDependencies": { + "ansi-green": "^0.1.1", + "benchmarked": "^2.0.0", + "coffeescript": "^2.2.3", + "delimiter-regex": "^2.0.0", + "extend-shallow": "^3.0.2", + "front-matter": "^2.3.0", + "gulp-format-md": "^1.0.0", + "minimist": "^1.2.0", + "mocha": "^6.1.4", + "toml": "^2.3.3", + "vinyl": "^2.1.0", + "write": "^1.0.3" + }, + "keywords": [ + "assemble", + "coffee", + "coffee-script", + "data", + "docs", + "documentation", + "extract", + "extracting", + "front", + "front-matter", + "frontmatter", + "generate", + "generator", + "gh-pages", + "gray", + "javascript", + "jekyll", + "js", + "JSON", + "markdown", + "matter", + "parse", + "parser", + "parsing", + "site", + "static", + "template", + "toml", + "yaml", + "yfm" + ], + "browser": { + "fs": false + }, + "typings": "gray-matter.d.ts", + "eslintConfig": { + "rules": { + "no-console": 0 + } + }, + "verb": { + "toc": false, + "layout": "default", + "tasks": [ + "readme" + ], + "plugins": [ + "gulp-format-md" + ], + "helpers": { + "examples": "./examples/helper.js" + }, + "lint": { + "reflinks": true + }, + "related": { + "list": [ + "assemble", + "metalsmith", + "verb" + ] + }, + "reflinks": [ + "coffe-script", + "generate", + "js-yaml", + "toml", + "update" + ] + } +} diff --git a/scripts/node_modules/is-extendable/LICENSE b/scripts/node_modules/is-extendable/LICENSE new file mode 100644 index 000000000..65f90aca8 --- /dev/null +++ b/scripts/node_modules/is-extendable/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015, Jon Schlinkert. + +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/scripts/node_modules/is-extendable/README.md b/scripts/node_modules/is-extendable/README.md new file mode 100644 index 000000000..e4cfaebcb --- /dev/null +++ b/scripts/node_modules/is-extendable/README.md @@ -0,0 +1,72 @@ +# is-extendable [![NPM version](https://badge.fury.io/js/is-extendable.svg)](http://badge.fury.io/js/is-extendable) + +> Returns true if a value is any of the object types: array, regexp, plain object, function or date. This is useful for determining if a value can be extended, e.g. "can the value have keys?" + +## Install + +Install with [npm](https://www.npmjs.com/) + +```sh +$ npm i is-extendable --save +``` + +## Usage + +```js +var isExtendable = require('is-extendable'); +``` + +Returns true if the value is any of the following: + +* `array` +* `regexp` +* `plain object` +* `function` +* `date` +* `error` + +## Notes + +All objects in JavaScript can have keys, but it's a pain to check for this, since we ether need to verify that the value is not `null` or `undefined` and: + +* the value is not a primitive, or +* that the object is an `object`, `function` + +Also note that an `extendable` object is not the same as an [extensible object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isExtensible), which is one that (in es6) is not sealed, frozen, or marked as non-extensible using `preventExtensions`. + +## Related projects + +* [assign-deep](https://github.com/jonschlinkert/assign-deep): Deeply assign the enumerable properties of source objects to a destination object. +* [extend-shallow](https://github.com/jonschlinkert/extend-shallow): Extend an object with the properties of additional objects. node.js/javascript util. +* [isobject](https://github.com/jonschlinkert/isobject): Returns true if the value is an object and not an array or null. +* [is-plain-object](https://github.com/jonschlinkert/is-plain-object): Returns true if an object was created by the `Object` constructor. +* [is-equal-shallow](https://github.com/jonschlinkert/is-equal-shallow): Does a shallow comparison of two objects, returning false if the keys or values differ. +* [kind-of](https://github.com/jonschlinkert/kind-of): Get the native type of a value. + +## Running tests + +Install dev dependencies: + +```sh +$ npm i -d && npm test +``` + +## Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/is-extendable/issues/new) + +## Author + +**Jon Schlinkert** + ++ [github/jonschlinkert](https://github.com/jonschlinkert) ++ [twitter/jonschlinkert](http://twitter.com/jonschlinkert) + +## License + +Copyright © 2015 Jon Schlinkert +Released under the MIT license. + +*** + +_This file was generated by [verb-cli](https://github.com/assemble/verb-cli) on July 04, 2015._ \ No newline at end of file diff --git a/scripts/node_modules/is-extendable/index.js b/scripts/node_modules/is-extendable/index.js new file mode 100644 index 000000000..4ee71a44a --- /dev/null +++ b/scripts/node_modules/is-extendable/index.js @@ -0,0 +1,13 @@ +/*! + * is-extendable + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + +'use strict'; + +module.exports = function isExtendable(val) { + return typeof val !== 'undefined' && val !== null + && (typeof val === 'object' || typeof val === 'function'); +}; diff --git a/scripts/node_modules/is-extendable/package.json b/scripts/node_modules/is-extendable/package.json new file mode 100644 index 000000000..5dd006ead --- /dev/null +++ b/scripts/node_modules/is-extendable/package.json @@ -0,0 +1,51 @@ +{ + "name": "is-extendable", + "description": "Returns true if a value is any of the object types: array, regexp, plain object, function or date. This is useful for determining if a value can be extended, e.g. \"can the value have keys?\"", + "version": "0.1.1", + "homepage": "https://github.com/jonschlinkert/is-extendable", + "author": "Jon Schlinkert (https://github.com/jonschlinkert)", + "repository": "jonschlinkert/is-extendable", + "bugs": { + "url": "https://github.com/jonschlinkert/is-extendable/issues" + }, + "license": "MIT", + "files": [ + "index.js" + ], + "main": "index.js", + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "mocha" + }, + "devDependencies": { + "mocha": "*" + }, + "keywords": [ + "array", + "assign", + "check", + "date", + "extend", + "extensible", + "function", + "is", + "object", + "regex", + "test" + ], + "verbiage": { + "related": { + "list": [ + "isobject", + "is-plain-object", + "kind-of", + "is-extendable", + "is-equal-shallow", + "extend-shallow", + "assign-deep" + ] + } + } +} diff --git a/scripts/node_modules/js-yaml/CHANGELOG.md b/scripts/node_modules/js-yaml/CHANGELOG.md new file mode 100644 index 000000000..b4baa4eab --- /dev/null +++ b/scripts/node_modules/js-yaml/CHANGELOG.md @@ -0,0 +1,557 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + + +## [3.14.1] - 2020-12-07 +### Security +- Fix possible code execution in (already unsafe) `.load()` (in &anchor). + + +## [3.14.0] - 2020-05-22 +### Changed +- Support `safe/loadAll(input, options)` variant of call. +- CI: drop outdated nodejs versions. +- Dev deps bump. + +### Fixed +- Quote `=` in plain scalars #519. +- Check the node type for `!` tag in case user manually specifies it. +- Verify that there are no null-bytes in input. +- Fix wrong quote position when writing condensed flow, #526. + + +## [3.13.1] - 2019-04-05 +### Security +- Fix possible code execution in (already unsafe) `.load()`, #480. + + +## [3.13.0] - 2019-03-20 +### Security +- Security fix: `safeLoad()` can hang when arrays with nested refs + used as key. Now throws exception for nested arrays. #475. + + +## [3.12.2] - 2019-02-26 +### Fixed +- Fix `noArrayIndent` option for root level, #468. + + +## [3.12.1] - 2019-01-05 +### Added +- Added `noArrayIndent` option, #432. + + +## [3.12.0] - 2018-06-02 +### Changed +- Support arrow functions without a block statement, #421. + + +## [3.11.0] - 2018-03-05 +### Added +- Add arrow functions suport for `!!js/function`. + +### Fixed +- Fix dump in bin/octal/hex formats for negative integers, #399. + + +## [3.10.0] - 2017-09-10 +### Fixed +- Fix `condenseFlow` output (quote keys for sure, instead of spaces), #371, #370. +- Dump astrals as codepoints instead of surrogate pair, #368. + + +## [3.9.1] - 2017-07-08 +### Fixed +- Ensure stack is present for custom errors in node 7.+, #351. + + +## [3.9.0] - 2017-07-08 +### Added +- Add `condenseFlow` option (to create pretty URL query params), #346. + +### Fixed +- Support array return from safeLoadAll/loadAll, #350. + + +## [3.8.4] - 2017-05-08 +### Fixed +- Dumper: prevent space after dash for arrays that wrap, #343. + + +## [3.8.3] - 2017-04-05 +### Fixed +- Should not allow numbers to begin and end with underscore, #335. + + +## [3.8.2] - 2017-03-02 +### Fixed +- Fix `!!float 123` (integers) parse, #333. +- Don't allow leading zeros in floats (except 0, 0.xxx). +- Allow positive exponent without sign in floats. + + +## [3.8.1] - 2017-02-07 +### Changed +- Maintenance: update browserified build. + + +## [3.8.0] - 2017-02-07 +### Fixed +- Fix reported position for `duplicated mapping key` errors. + Now points to block start instead of block end. + (#243, thanks to @shockey). + + +## [3.7.0] - 2016-11-12 +### Added +- Support polymorphism for tags (#300, thanks to @monken). + +### Fixed +- Fix parsing of quotes followed by newlines (#304, thanks to @dplepage). + + +## [3.6.1] - 2016-05-11 +### Fixed +- Fix output cut on a pipe, #286. + + +## [3.6.0] - 2016-04-16 +### Fixed +- Dumper rewrite, fix multiple bugs with trailing `\n`. + Big thanks to @aepsilon! +- Loader: fix leading/trailing newlines in block scalars, @aepsilon. + + +## [3.5.5] - 2016-03-17 +### Fixed +- Date parse fix: don't allow dates with on digit in month and day, #268. + + +## [3.5.4] - 2016-03-09 +### Added +- `noCompatMode` for dumper, to disable quoting YAML 1.1 values. + + +## [3.5.3] - 2016-02-11 +### Changed +- Maintenance release. + + +## [3.5.2] - 2016-01-11 +### Changed +- Maintenance: missed comma in bower config. + + +## [3.5.1] - 2016-01-11 +### Changed +- Removed `inherit` dependency, #239. +- Better browserify workaround for esprima load. +- Demo rewrite. + + +## [3.5.0] - 2016-01-10 +### Fixed +- Dumper. Fold strings only, #217. +- Dumper. `norefs` option, to clone linked objects, #229. +- Loader. Throw a warning for duplicate keys, #166. +- Improved browserify support (mark `esprima` & `Buffer` excluded). + + +## [3.4.6] - 2015-11-26 +### Changed +- Use standalone `inherit` to keep browserified files clear. + + +## [3.4.5] - 2015-11-23 +### Added +- Added `lineWidth` option to dumper. + + +## [3.4.4] - 2015-11-21 +### Fixed +- Fixed floats dump (missed dot for scientific format), #220. +- Allow non-printable characters inside quoted scalars, #192. + + +## [3.4.3] - 2015-10-10 +### Changed +- Maintenance release - deps bump (esprima, argparse). + + +## [3.4.2] - 2015-09-09 +### Fixed +- Fixed serialization of duplicated entries in sequences, #205. + Thanks to @vogelsgesang. + + +## [3.4.1] - 2015-09-05 +### Fixed +- Fixed stacktrace handling in generated errors, for browsers (FF/IE). + + +## [3.4.0] - 2015-08-23 +### Changed +- Don't throw on warnings anymore. Use `onWarning` option to catch. +- Throw error on unknown tags (was warning before). +- Reworked internals of error class. + +### Fixed +- Fixed multiline keys dump, #197. Thanks to @tcr. +- Fixed heading line breaks in some scalars (regression). + + +## [3.3.1] - 2015-05-13 +### Added +- Added `.sortKeys` dumper option, thanks to @rjmunro. + +### Fixed +- Fixed astral characters support, #191. + + +## [3.3.0] - 2015-04-26 +### Changed +- Significantly improved long strings formatting in dumper, thanks to @isaacs. +- Strip BOM if exists. + + +## [3.2.7] - 2015-02-19 +### Changed +- Maintenance release. +- Updated dependencies. +- HISTORY.md -> CHANGELOG.md + + +## [3.2.6] - 2015-02-07 +### Fixed +- Fixed encoding of UTF-16 surrogate pairs. (e.g. "\U0001F431" CAT FACE). +- Fixed demo dates dump (#113, thanks to @Hypercubed). + + +## [3.2.5] - 2014-12-28 +### Fixed +- Fixed resolving of all built-in types on empty nodes. +- Fixed invalid warning on empty lines within quoted scalars and flow collections. +- Fixed bug: Tag on an empty node didn't resolve in some cases. + + +## [3.2.4] - 2014-12-19 +### Fixed +- Fixed resolving of !!null tag on an empty node. + + +## [3.2.3] - 2014-11-08 +### Fixed +- Implemented dumping of objects with circular and cross references. +- Partially fixed aliasing of constructed objects. (see issue #141 for details) + + +## [3.2.2] - 2014-09-07 +### Fixed +- Fixed infinite loop on unindented block scalars. +- Rewritten base64 encode/decode in binary type, to keep code licence clear. + + +## [3.2.1] - 2014-08-24 +### Fixed +- Nothig new. Just fix npm publish error. + + +## [3.2.0] - 2014-08-24 +### Added +- Added input piping support to CLI. + +### Fixed +- Fixed typo, that could cause hand on initial indent (#139). + + +## [3.1.0] - 2014-07-07 +### Changed +- 1.5x-2x speed boost. +- Removed deprecated `require('xxx.yml')` support. +- Significant code cleanup and refactoring. +- Internal API changed. If you used custom types - see updated examples. + Others are not affected. +- Even if the input string has no trailing line break character, + it will be parsed as if it has one. +- Added benchmark scripts. +- Moved bower files to /dist folder +- Bugfixes. + + +## [3.0.2] - 2014-02-27 +### Fixed +- Fixed bug: "constructor" string parsed as `null`. + + +## [3.0.1] - 2013-12-22 +### Fixed +- Fixed parsing of literal scalars. (issue #108) +- Prevented adding unnecessary spaces in object dumps. (issue #68) +- Fixed dumping of objects with very long (> 1024 in length) keys. + + +## [3.0.0] - 2013-12-16 +### Changed +- Refactored code. Changed API for custom types. +- Removed output colors in CLI, dump json by default. +- Removed big dependencies from browser version (esprima, buffer). Load `esprima` manually, if `!!js/function` needed. `!!bin` now returns Array in browser +- AMD support. +- Don't quote dumped strings because of `-` & `?` (if not first char). +- __Deprecated__ loading yaml files via `require()`, as not recommended + behaviour for node. + + +## [2.1.3] - 2013-10-16 +### Fixed +- Fix wrong loading of empty block scalars. + + +## [2.1.2] - 2013-10-07 +### Fixed +- Fix unwanted line breaks in folded scalars. + + +## [2.1.1] - 2013-10-02 +### Fixed +- Dumper now respects deprecated booleans syntax from YAML 1.0/1.1 +- Fixed reader bug in JSON-like sequences/mappings. + + +## [2.1.0] - 2013-06-05 +### Added +- Add standard YAML schemas: Failsafe (`FAILSAFE_SCHEMA`), + JSON (`JSON_SCHEMA`) and Core (`CORE_SCHEMA`). +- Add `skipInvalid` dumper option. + +### Changed +- Rename `DEFAULT_SCHEMA` to `DEFAULT_FULL_SCHEMA` + and `SAFE_SCHEMA` to `DEFAULT_SAFE_SCHEMA`. +- Use `safeLoad` for `require` extension. + +### Fixed +- Bug fix: export `NIL` constant from the public interface. + + +## [2.0.5] - 2013-04-26 +### Security +- Close security issue in !!js/function constructor. + Big thanks to @nealpoole for security audit. + + +## [2.0.4] - 2013-04-08 +### Changed +- Updated .npmignore to reduce package size + + +## [2.0.3] - 2013-02-26 +### Fixed +- Fixed dumping of empty arrays ans objects. ([] and {} instead of null) + + +## [2.0.2] - 2013-02-15 +### Fixed +- Fixed input validation: tabs are printable characters. + + +## [2.0.1] - 2013-02-09 +### Fixed +- Fixed error, when options not passed to function cass + + +## [2.0.0] - 2013-02-09 +### Changed +- Full rewrite. New architecture. Fast one-stage parsing. +- Changed custom types API. +- Added YAML dumper. + + +## [1.0.3] - 2012-11-05 +### Fixed +- Fixed utf-8 files loading. + + +## [1.0.2] - 2012-08-02 +### Fixed +- Pull out hand-written shims. Use ES5-Shims for old browsers support. See #44. +- Fix timstamps incorectly parsed in local time when no time part specified. + + +## [1.0.1] - 2012-07-07 +### Fixed +- Fixes `TypeError: 'undefined' is not an object` under Safari. Thanks Phuong. +- Fix timestamps incorrectly parsed in local time. Thanks @caolan. Closes #46. + + +## [1.0.0] - 2012-07-01 +### Changed +- `y`, `yes`, `n`, `no`, `on`, `off` are not converted to Booleans anymore. + Fixes #42. +- `require(filename)` now returns a single document and throws an Error if + file contains more than one document. +- CLI was merged back from js-yaml.bin + + +## [0.3.7] - 2012-02-28 +### Fixed +- Fix export of `addConstructor()`. Closes #39. + + +## [0.3.6] - 2012-02-22 +### Changed +- Removed AMD parts - too buggy to use. Need help to rewrite from scratch + +### Fixed +- Removed YUI compressor warning (renamed `double` variable). Closes #40. + + +## [0.3.5] - 2012-01-10 +### Fixed +- Workagound for .npmignore fuckup under windows. Thanks to airportyh. + + +## [0.3.4] - 2011-12-24 +### Fixed +- Fixes str[] for oldIEs support. +- Adds better has change support for browserified demo. +- improves compact output of Error. Closes #33. + + +## [0.3.3] - 2011-12-20 +### Added +- adds `compact` stringification of Errors. + +### Changed +- jsyaml executable moved to separate module. + + +## [0.3.2] - 2011-12-16 +### Added +- Added jsyaml executable. +- Added !!js/function support. Closes #12. + +### Fixed +- Fixes ug with block style scalars. Closes #26. +- All sources are passing JSLint now. +- Fixes bug in Safari. Closes #28. +- Fixes bug in Opers. Closes #29. +- Improves browser support. Closes #20. + + +## [0.3.1] - 2011-11-18 +### Added +- Added AMD support for browserified version. +- Added permalinks for online demo YAML snippets. Now we have YPaste service, lol. +- Added !!js/regexp and !!js/undefined types. Partially solves #12. + +### Changed +- Wrapped browserified js-yaml into closure. + +### Fixed +- Fixed the resolvement of non-specific tags. Closes #17. +- Fixed !!set mapping. +- Fixed month parse in dates. Closes #19. + + +## [0.3.0] - 2011-11-09 +### Added +- Added browserified version. Closes #13. +- Added live demo of browserified version. +- Ported some of the PyYAML tests. See #14. + +### Fixed +- Removed JS.Class dependency. Closes #3. +- Fixed timestamp bug when fraction was given. + + +## [0.2.2] - 2011-11-06 +### Fixed +- Fixed crash on docs without ---. Closes #8. +- Fixed multiline string parse +- Fixed tests/comments for using array as key + + +## [0.2.1] - 2011-11-02 +### Fixed +- Fixed short file read (<4k). Closes #9. + + +## [0.2.0] - 2011-11-02 +### Changed +- First public release + + +[3.14.1]: https://github.com/nodeca/js-yaml/compare/3.14.0...3.14.1 +[3.14.0]: https://github.com/nodeca/js-yaml/compare/3.13.1...3.14.0 +[3.13.1]: https://github.com/nodeca/js-yaml/compare/3.13.0...3.13.1 +[3.13.0]: https://github.com/nodeca/js-yaml/compare/3.12.2...3.13.0 +[3.12.2]: https://github.com/nodeca/js-yaml/compare/3.12.1...3.12.2 +[3.12.1]: https://github.com/nodeca/js-yaml/compare/3.12.0...3.12.1 +[3.12.0]: https://github.com/nodeca/js-yaml/compare/3.11.0...3.12.0 +[3.11.0]: https://github.com/nodeca/js-yaml/compare/3.10.0...3.11.0 +[3.10.0]: https://github.com/nodeca/js-yaml/compare/3.9.1...3.10.0 +[3.9.1]: https://github.com/nodeca/js-yaml/compare/3.9.0...3.9.1 +[3.9.0]: https://github.com/nodeca/js-yaml/compare/3.8.4...3.9.0 +[3.8.4]: https://github.com/nodeca/js-yaml/compare/3.8.3...3.8.4 +[3.8.3]: https://github.com/nodeca/js-yaml/compare/3.8.2...3.8.3 +[3.8.2]: https://github.com/nodeca/js-yaml/compare/3.8.1...3.8.2 +[3.8.1]: https://github.com/nodeca/js-yaml/compare/3.8.0...3.8.1 +[3.8.0]: https://github.com/nodeca/js-yaml/compare/3.7.0...3.8.0 +[3.7.0]: https://github.com/nodeca/js-yaml/compare/3.6.1...3.7.0 +[3.6.1]: https://github.com/nodeca/js-yaml/compare/3.6.0...3.6.1 +[3.6.0]: https://github.com/nodeca/js-yaml/compare/3.5.5...3.6.0 +[3.5.5]: https://github.com/nodeca/js-yaml/compare/3.5.4...3.5.5 +[3.5.4]: https://github.com/nodeca/js-yaml/compare/3.5.3...3.5.4 +[3.5.3]: https://github.com/nodeca/js-yaml/compare/3.5.2...3.5.3 +[3.5.2]: https://github.com/nodeca/js-yaml/compare/3.5.1...3.5.2 +[3.5.1]: https://github.com/nodeca/js-yaml/compare/3.5.0...3.5.1 +[3.5.0]: https://github.com/nodeca/js-yaml/compare/3.4.6...3.5.0 +[3.4.6]: https://github.com/nodeca/js-yaml/compare/3.4.5...3.4.6 +[3.4.5]: https://github.com/nodeca/js-yaml/compare/3.4.4...3.4.5 +[3.4.4]: https://github.com/nodeca/js-yaml/compare/3.4.3...3.4.4 +[3.4.3]: https://github.com/nodeca/js-yaml/compare/3.4.2...3.4.3 +[3.4.2]: https://github.com/nodeca/js-yaml/compare/3.4.1...3.4.2 +[3.4.1]: https://github.com/nodeca/js-yaml/compare/3.4.0...3.4.1 +[3.4.0]: https://github.com/nodeca/js-yaml/compare/3.3.1...3.4.0 +[3.3.1]: https://github.com/nodeca/js-yaml/compare/3.3.0...3.3.1 +[3.3.0]: https://github.com/nodeca/js-yaml/compare/3.2.7...3.3.0 +[3.2.7]: https://github.com/nodeca/js-yaml/compare/3.2.6...3.2.7 +[3.2.6]: https://github.com/nodeca/js-yaml/compare/3.2.5...3.2.6 +[3.2.5]: https://github.com/nodeca/js-yaml/compare/3.2.4...3.2.5 +[3.2.4]: https://github.com/nodeca/js-yaml/compare/3.2.3...3.2.4 +[3.2.3]: https://github.com/nodeca/js-yaml/compare/3.2.2...3.2.3 +[3.2.2]: https://github.com/nodeca/js-yaml/compare/3.2.1...3.2.2 +[3.2.1]: https://github.com/nodeca/js-yaml/compare/3.2.0...3.2.1 +[3.2.0]: https://github.com/nodeca/js-yaml/compare/3.1.0...3.2.0 +[3.1.0]: https://github.com/nodeca/js-yaml/compare/3.0.2...3.1.0 +[3.0.2]: https://github.com/nodeca/js-yaml/compare/3.0.1...3.0.2 +[3.0.1]: https://github.com/nodeca/js-yaml/compare/3.0.0...3.0.1 +[3.0.0]: https://github.com/nodeca/js-yaml/compare/2.1.3...3.0.0 +[2.1.3]: https://github.com/nodeca/js-yaml/compare/2.1.2...2.1.3 +[2.1.2]: https://github.com/nodeca/js-yaml/compare/2.1.1...2.1.2 +[2.1.1]: https://github.com/nodeca/js-yaml/compare/2.1.0...2.1.1 +[2.1.0]: https://github.com/nodeca/js-yaml/compare/2.0.5...2.1.0 +[2.0.5]: https://github.com/nodeca/js-yaml/compare/2.0.4...2.0.5 +[2.0.4]: https://github.com/nodeca/js-yaml/compare/2.0.3...2.0.4 +[2.0.3]: https://github.com/nodeca/js-yaml/compare/2.0.2...2.0.3 +[2.0.2]: https://github.com/nodeca/js-yaml/compare/2.0.1...2.0.2 +[2.0.1]: https://github.com/nodeca/js-yaml/compare/2.0.0...2.0.1 +[2.0.0]: https://github.com/nodeca/js-yaml/compare/1.0.3...2.0.0 +[1.0.3]: https://github.com/nodeca/js-yaml/compare/1.0.2...1.0.3 +[1.0.2]: https://github.com/nodeca/js-yaml/compare/1.0.1...1.0.2 +[1.0.1]: https://github.com/nodeca/js-yaml/compare/1.0.0...1.0.1 +[1.0.0]: https://github.com/nodeca/js-yaml/compare/0.3.7...1.0.0 +[0.3.7]: https://github.com/nodeca/js-yaml/compare/0.3.6...0.3.7 +[0.3.6]: https://github.com/nodeca/js-yaml/compare/0.3.5...0.3.6 +[0.3.5]: https://github.com/nodeca/js-yaml/compare/0.3.4...0.3.5 +[0.3.4]: https://github.com/nodeca/js-yaml/compare/0.3.3...0.3.4 +[0.3.3]: https://github.com/nodeca/js-yaml/compare/0.3.2...0.3.3 +[0.3.2]: https://github.com/nodeca/js-yaml/compare/0.3.1...0.3.2 +[0.3.1]: https://github.com/nodeca/js-yaml/compare/0.3.0...0.3.1 +[0.3.0]: https://github.com/nodeca/js-yaml/compare/0.2.2...0.3.0 +[0.2.2]: https://github.com/nodeca/js-yaml/compare/0.2.1...0.2.2 +[0.2.1]: https://github.com/nodeca/js-yaml/compare/0.2.0...0.2.1 +[0.2.0]: https://github.com/nodeca/js-yaml/releases/tag/0.2.0 diff --git a/scripts/node_modules/js-yaml/LICENSE b/scripts/node_modules/js-yaml/LICENSE new file mode 100644 index 000000000..09d3a29e9 --- /dev/null +++ b/scripts/node_modules/js-yaml/LICENSE @@ -0,0 +1,21 @@ +(The MIT License) + +Copyright (C) 2011-2015 by Vitaly Puzrin + +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/scripts/node_modules/js-yaml/README.md b/scripts/node_modules/js-yaml/README.md new file mode 100644 index 000000000..246e56355 --- /dev/null +++ b/scripts/node_modules/js-yaml/README.md @@ -0,0 +1,299 @@ +JS-YAML - YAML 1.2 parser / writer for JavaScript +================================================= + +[![Build Status](https://travis-ci.org/nodeca/js-yaml.svg?branch=master)](https://travis-ci.org/nodeca/js-yaml) +[![NPM version](https://img.shields.io/npm/v/js-yaml.svg)](https://www.npmjs.org/package/js-yaml) + +__[Online Demo](http://nodeca.github.com/js-yaml/)__ + + +This is an implementation of [YAML](http://yaml.org/), a human-friendly data +serialization language. Started as [PyYAML](http://pyyaml.org/) port, it was +completely rewritten from scratch. Now it's very fast, and supports 1.2 spec. + + +Installation +------------ + +### YAML module for node.js + +``` +npm install js-yaml +``` + + +### CLI executable + +If you want to inspect your YAML files from CLI, install js-yaml globally: + +``` +npm install -g js-yaml +``` + +#### Usage + +``` +usage: js-yaml [-h] [-v] [-c] [-t] file + +Positional arguments: + file File with YAML document(s) + +Optional arguments: + -h, --help Show this help message and exit. + -v, --version Show program's version number and exit. + -c, --compact Display errors in compact mode + -t, --trace Show stack trace on error +``` + + +### Bundled YAML library for browsers + +``` html + + + + +``` + +Browser support was done mostly for the online demo. If you find any errors - feel +free to send pull requests with fixes. Also note, that IE and other old browsers +needs [es5-shims](https://github.com/kriskowal/es5-shim) to operate. + +Notes: + +1. We have no resources to support browserified version. Don't expect it to be + well tested. Don't expect fast fixes if something goes wrong there. +2. `!!js/function` in browser bundle will not work by default. If you really need + it - load `esprima` parser first (via amd or directly). +3. `!!bin` in browser will return `Array`, because browsers do not support + node.js `Buffer` and adding Buffer shims is completely useless on practice. + + +API +--- + +Here we cover the most 'useful' methods. If you need advanced details (creating +your own tags), see [wiki](https://github.com/nodeca/js-yaml/wiki) and +[examples](https://github.com/nodeca/js-yaml/tree/master/examples) for more +info. + +``` javascript +const yaml = require('js-yaml'); +const fs = require('fs'); + +// Get document, or throw exception on error +try { + const doc = yaml.safeLoad(fs.readFileSync('/home/ixti/example.yml', 'utf8')); + console.log(doc); +} catch (e) { + console.log(e); +} +``` + + +### safeLoad (string [ , options ]) + +**Recommended loading way.** Parses `string` as single YAML document. Returns either a +plain object, a string or `undefined`, or throws `YAMLException` on error. By default, does +not support regexps, functions and undefined. This method is safe for untrusted data. + +options: + +- `filename` _(default: null)_ - string to be used as a file path in + error/warning messages. +- `onWarning` _(default: null)_ - function to call on warning messages. + Loader will call this function with an instance of `YAMLException` for each warning. +- `schema` _(default: `DEFAULT_SAFE_SCHEMA`)_ - specifies a schema to use. + - `FAILSAFE_SCHEMA` - only strings, arrays and plain objects: + http://www.yaml.org/spec/1.2/spec.html#id2802346 + - `JSON_SCHEMA` - all JSON-supported types: + http://www.yaml.org/spec/1.2/spec.html#id2803231 + - `CORE_SCHEMA` - same as `JSON_SCHEMA`: + http://www.yaml.org/spec/1.2/spec.html#id2804923 + - `DEFAULT_SAFE_SCHEMA` - all supported YAML types, without unsafe ones + (`!!js/undefined`, `!!js/regexp` and `!!js/function`): + http://yaml.org/type/ + - `DEFAULT_FULL_SCHEMA` - all supported YAML types. +- `json` _(default: false)_ - compatibility with JSON.parse behaviour. If true, then duplicate keys in a mapping will override values rather than throwing an error. + +NOTE: This function **does not** understand multi-document sources, it throws +exception on those. + +NOTE: JS-YAML **does not** support schema-specific tag resolution restrictions. +So, the JSON schema is not as strictly defined in the YAML specification. +It allows numbers in any notation, use `Null` and `NULL` as `null`, etc. +The core schema also has no such restrictions. It allows binary notation for integers. + + +### load (string [ , options ]) + +**Use with care with untrusted sources**. The same as `safeLoad()` but uses +`DEFAULT_FULL_SCHEMA` by default - adds some JavaScript-specific types: +`!!js/function`, `!!js/regexp` and `!!js/undefined`. For untrusted sources, you +must additionally validate object structure to avoid injections: + +``` javascript +const untrusted_code = '"toString": ! "function (){very_evil_thing();}"'; + +// I'm just converting that string, what could possibly go wrong? +require('js-yaml').load(untrusted_code) + '' +``` + + +### safeLoadAll (string [, iterator] [, options ]) + +Same as `safeLoad()`, but understands multi-document sources. Applies +`iterator` to each document if specified, or returns array of documents. + +``` javascript +const yaml = require('js-yaml'); + +yaml.safeLoadAll(data, function (doc) { + console.log(doc); +}); +``` + + +### loadAll (string [, iterator] [ , options ]) + +Same as `safeLoadAll()` but uses `DEFAULT_FULL_SCHEMA` by default. + + +### safeDump (object [ , options ]) + +Serializes `object` as a YAML document. Uses `DEFAULT_SAFE_SCHEMA`, so it will +throw an exception if you try to dump regexps or functions. However, you can +disable exceptions by setting the `skipInvalid` option to `true`. + +options: + +- `indent` _(default: 2)_ - indentation width to use (in spaces). +- `noArrayIndent` _(default: false)_ - when true, will not add an indentation level to array elements +- `skipInvalid` _(default: false)_ - do not throw on invalid types (like function + in the safe schema) and skip pairs and single values with such types. +- `flowLevel` (default: -1) - specifies level of nesting, when to switch from + block to flow style for collections. -1 means block style everwhere +- `styles` - "tag" => "style" map. Each tag may have own set of styles. +- `schema` _(default: `DEFAULT_SAFE_SCHEMA`)_ specifies a schema to use. +- `sortKeys` _(default: `false`)_ - if `true`, sort keys when dumping YAML. If a + function, use the function to sort the keys. +- `lineWidth` _(default: `80`)_ - set max line width. +- `noRefs` _(default: `false`)_ - if `true`, don't convert duplicate objects into references +- `noCompatMode` _(default: `false`)_ - if `true` don't try to be compatible with older + yaml versions. Currently: don't quote "yes", "no" and so on, as required for YAML 1.1 +- `condenseFlow` _(default: `false`)_ - if `true` flow sequences will be condensed, omitting the space between `a, b`. Eg. `'[a,b]'`, and omitting the space between `key: value` and quoting the key. Eg. `'{"a":b}'` Can be useful when using yaml for pretty URL query params as spaces are %-encoded. + +The following table show availlable styles (e.g. "canonical", +"binary"...) available for each tag (.e.g. !!null, !!int ...). Yaml +output is shown on the right side after `=>` (default setting) or `->`: + +``` none +!!null + "canonical" -> "~" + "lowercase" => "null" + "uppercase" -> "NULL" + "camelcase" -> "Null" + +!!int + "binary" -> "0b1", "0b101010", "0b1110001111010" + "octal" -> "01", "052", "016172" + "decimal" => "1", "42", "7290" + "hexadecimal" -> "0x1", "0x2A", "0x1C7A" + +!!bool + "lowercase" => "true", "false" + "uppercase" -> "TRUE", "FALSE" + "camelcase" -> "True", "False" + +!!float + "lowercase" => ".nan", '.inf' + "uppercase" -> ".NAN", '.INF' + "camelcase" -> ".NaN", '.Inf' +``` + +Example: + +``` javascript +safeDump (object, { + 'styles': { + '!!null': 'canonical' // dump null as ~ + }, + 'sortKeys': true // sort object keys +}); +``` + +### dump (object [ , options ]) + +Same as `safeDump()` but without limits (uses `DEFAULT_FULL_SCHEMA` by default). + + +Supported YAML types +-------------------- + +The list of standard YAML tags and corresponding JavaScipt types. See also +[YAML tag discussion](http://pyyaml.org/wiki/YAMLTagDiscussion) and +[YAML types repository](http://yaml.org/type/). + +``` +!!null '' # null +!!bool 'yes' # bool +!!int '3...' # number +!!float '3.14...' # number +!!binary '...base64...' # buffer +!!timestamp 'YYYY-...' # date +!!omap [ ... ] # array of key-value pairs +!!pairs [ ... ] # array or array pairs +!!set { ... } # array of objects with given keys and null values +!!str '...' # string +!!seq [ ... ] # array +!!map { ... } # object +``` + +**JavaScript-specific tags** + +``` +!!js/regexp /pattern/gim # RegExp +!!js/undefined '' # Undefined +!!js/function 'function () {...}' # Function +``` + +Caveats +------- + +Note, that you use arrays or objects as key in JS-YAML. JS does not allow objects +or arrays as keys, and stringifies (by calling `toString()` method) them at the +moment of adding them. + +``` yaml +--- +? [ foo, bar ] +: - baz +? { foo: bar } +: - baz + - baz +``` + +``` javascript +{ "foo,bar": ["baz"], "[object Object]": ["baz", "baz"] } +``` + +Also, reading of properties on implicit block mapping keys is not supported yet. +So, the following YAML document cannot be loaded. + +``` yaml +&anchor foo: + foo: bar + *anchor: duplicate key + baz: bat + *anchor: duplicate key +``` + + +js-yaml for enterprise +---------------------- + +Available as part of the Tidelift Subscription + +The maintainers of js-yaml and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-js-yaml?utm_source=npm-js-yaml&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/scripts/node_modules/js-yaml/bin/js-yaml.js b/scripts/node_modules/js-yaml/bin/js-yaml.js new file mode 100755 index 000000000..e79186be6 --- /dev/null +++ b/scripts/node_modules/js-yaml/bin/js-yaml.js @@ -0,0 +1,132 @@ +#!/usr/bin/env node + + +'use strict'; + +/*eslint-disable no-console*/ + + +// stdlib +var fs = require('fs'); + + +// 3rd-party +var argparse = require('argparse'); + + +// internal +var yaml = require('..'); + + +//////////////////////////////////////////////////////////////////////////////// + + +var cli = new argparse.ArgumentParser({ + prog: 'js-yaml', + version: require('../package.json').version, + addHelp: true +}); + + +cli.addArgument([ '-c', '--compact' ], { + help: 'Display errors in compact mode', + action: 'storeTrue' +}); + + +// deprecated (not needed after we removed output colors) +// option suppressed, but not completely removed for compatibility +cli.addArgument([ '-j', '--to-json' ], { + help: argparse.Const.SUPPRESS, + dest: 'json', + action: 'storeTrue' +}); + + +cli.addArgument([ '-t', '--trace' ], { + help: 'Show stack trace on error', + action: 'storeTrue' +}); + +cli.addArgument([ 'file' ], { + help: 'File to read, utf-8 encoded without BOM', + nargs: '?', + defaultValue: '-' +}); + + +//////////////////////////////////////////////////////////////////////////////// + + +var options = cli.parseArgs(); + + +//////////////////////////////////////////////////////////////////////////////// + +function readFile(filename, encoding, callback) { + if (options.file === '-') { + // read from stdin + + var chunks = []; + + process.stdin.on('data', function (chunk) { + chunks.push(chunk); + }); + + process.stdin.on('end', function () { + return callback(null, Buffer.concat(chunks).toString(encoding)); + }); + } else { + fs.readFile(filename, encoding, callback); + } +} + +readFile(options.file, 'utf8', function (error, input) { + var output, isYaml; + + if (error) { + if (error.code === 'ENOENT') { + console.error('File not found: ' + options.file); + process.exit(2); + } + + console.error( + options.trace && error.stack || + error.message || + String(error)); + + process.exit(1); + } + + try { + output = JSON.parse(input); + isYaml = false; + } catch (err) { + if (err instanceof SyntaxError) { + try { + output = []; + yaml.loadAll(input, function (doc) { output.push(doc); }, {}); + isYaml = true; + + if (output.length === 0) output = null; + else if (output.length === 1) output = output[0]; + + } catch (e) { + if (options.trace && err.stack) console.error(e.stack); + else console.error(e.toString(options.compact)); + + process.exit(1); + } + } else { + console.error( + options.trace && err.stack || + err.message || + String(err)); + + process.exit(1); + } + } + + if (isYaml) console.log(JSON.stringify(output, null, ' ')); + else console.log(yaml.dump(output)); +}); diff --git a/scripts/node_modules/js-yaml/dist/js-yaml.js b/scripts/node_modules/js-yaml/dist/js-yaml.js new file mode 100644 index 000000000..787832074 --- /dev/null +++ b/scripts/node_modules/js-yaml/dist/js-yaml.js @@ -0,0 +1,3989 @@ +/*! js-yaml 3.14.1 https://github.com/nodeca/js-yaml */(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.jsyaml = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i */ +var CHAR_QUESTION = 0x3F; /* ? */ +var CHAR_COMMERCIAL_AT = 0x40; /* @ */ +var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ +var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ +var CHAR_GRAVE_ACCENT = 0x60; /* ` */ +var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ +var CHAR_VERTICAL_LINE = 0x7C; /* | */ +var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ + +var ESCAPE_SEQUENCES = {}; + +ESCAPE_SEQUENCES[0x00] = '\\0'; +ESCAPE_SEQUENCES[0x07] = '\\a'; +ESCAPE_SEQUENCES[0x08] = '\\b'; +ESCAPE_SEQUENCES[0x09] = '\\t'; +ESCAPE_SEQUENCES[0x0A] = '\\n'; +ESCAPE_SEQUENCES[0x0B] = '\\v'; +ESCAPE_SEQUENCES[0x0C] = '\\f'; +ESCAPE_SEQUENCES[0x0D] = '\\r'; +ESCAPE_SEQUENCES[0x1B] = '\\e'; +ESCAPE_SEQUENCES[0x22] = '\\"'; +ESCAPE_SEQUENCES[0x5C] = '\\\\'; +ESCAPE_SEQUENCES[0x85] = '\\N'; +ESCAPE_SEQUENCES[0xA0] = '\\_'; +ESCAPE_SEQUENCES[0x2028] = '\\L'; +ESCAPE_SEQUENCES[0x2029] = '\\P'; + +var DEPRECATED_BOOLEANS_SYNTAX = [ + 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', + 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' +]; + +function compileStyleMap(schema, map) { + var result, keys, index, length, tag, style, type; + + if (map === null) return {}; + + result = {}; + keys = Object.keys(map); + + for (index = 0, length = keys.length; index < length; index += 1) { + tag = keys[index]; + style = String(map[tag]); + + if (tag.slice(0, 2) === '!!') { + tag = 'tag:yaml.org,2002:' + tag.slice(2); + } + type = schema.compiledTypeMap['fallback'][tag]; + + if (type && _hasOwnProperty.call(type.styleAliases, style)) { + style = type.styleAliases[style]; + } + + result[tag] = style; + } + + return result; +} + +function encodeHex(character) { + var string, handle, length; + + string = character.toString(16).toUpperCase(); + + if (character <= 0xFF) { + handle = 'x'; + length = 2; + } else if (character <= 0xFFFF) { + handle = 'u'; + length = 4; + } else if (character <= 0xFFFFFFFF) { + handle = 'U'; + length = 8; + } else { + throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF'); + } + + return '\\' + handle + common.repeat('0', length - string.length) + string; +} + +function State(options) { + this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; + this.indent = Math.max(1, (options['indent'] || 2)); + this.noArrayIndent = options['noArrayIndent'] || false; + this.skipInvalid = options['skipInvalid'] || false; + this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); + this.styleMap = compileStyleMap(this.schema, options['styles'] || null); + this.sortKeys = options['sortKeys'] || false; + this.lineWidth = options['lineWidth'] || 80; + this.noRefs = options['noRefs'] || false; + this.noCompatMode = options['noCompatMode'] || false; + this.condenseFlow = options['condenseFlow'] || false; + + this.implicitTypes = this.schema.compiledImplicit; + this.explicitTypes = this.schema.compiledExplicit; + + this.tag = null; + this.result = ''; + + this.duplicates = []; + this.usedDuplicates = null; +} + +// Indents every line in a string. Empty lines (\n only) are not indented. +function indentString(string, spaces) { + var ind = common.repeat(' ', spaces), + position = 0, + next = -1, + result = '', + line, + length = string.length; + + while (position < length) { + next = string.indexOf('\n', position); + if (next === -1) { + line = string.slice(position); + position = length; + } else { + line = string.slice(position, next + 1); + position = next + 1; + } + + if (line.length && line !== '\n') result += ind; + + result += line; + } + + return result; +} + +function generateNextLine(state, level) { + return '\n' + common.repeat(' ', state.indent * level); +} + +function testImplicitResolving(state, str) { + var index, length, type; + + for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { + type = state.implicitTypes[index]; + + if (type.resolve(str)) { + return true; + } + } + + return false; +} + +// [33] s-white ::= s-space | s-tab +function isWhitespace(c) { + return c === CHAR_SPACE || c === CHAR_TAB; +} + +// Returns true if the character can be printed without escaping. +// From YAML 1.2: "any allowed characters known to be non-printable +// should also be escaped. [However,] This isn’t mandatory" +// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. +function isPrintable(c) { + return (0x00020 <= c && c <= 0x00007E) + || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) + || ((0x0E000 <= c && c <= 0x00FFFD) && c !== 0xFEFF /* BOM */) + || (0x10000 <= c && c <= 0x10FFFF); +} + +// [34] ns-char ::= nb-char - s-white +// [27] nb-char ::= c-printable - b-char - c-byte-order-mark +// [26] b-char ::= b-line-feed | b-carriage-return +// [24] b-line-feed ::= #xA /* LF */ +// [25] b-carriage-return ::= #xD /* CR */ +// [3] c-byte-order-mark ::= #xFEFF +function isNsChar(c) { + return isPrintable(c) && !isWhitespace(c) + // byte-order-mark + && c !== 0xFEFF + // b-char + && c !== CHAR_CARRIAGE_RETURN + && c !== CHAR_LINE_FEED; +} + +// Simplified test for values allowed after the first character in plain style. +function isPlainSafe(c, prev) { + // Uses a subset of nb-char - c-flow-indicator - ":" - "#" + // where nb-char ::= c-printable - b-char - c-byte-order-mark. + return isPrintable(c) && c !== 0xFEFF + // - c-flow-indicator + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + // - ":" - "#" + // /* An ns-char preceding */ "#" + && c !== CHAR_COLON + && ((c !== CHAR_SHARP) || (prev && isNsChar(prev))); +} + +// Simplified test for values allowed as the first character in plain style. +function isPlainSafeFirst(c) { + // Uses a subset of ns-char - c-indicator + // where ns-char = nb-char - s-white. + return isPrintable(c) && c !== 0xFEFF + && !isWhitespace(c) // - s-white + // - (c-indicator ::= + // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” + && c !== CHAR_MINUS + && c !== CHAR_QUESTION + && c !== CHAR_COLON + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” + && c !== CHAR_SHARP + && c !== CHAR_AMPERSAND + && c !== CHAR_ASTERISK + && c !== CHAR_EXCLAMATION + && c !== CHAR_VERTICAL_LINE + && c !== CHAR_EQUALS + && c !== CHAR_GREATER_THAN + && c !== CHAR_SINGLE_QUOTE + && c !== CHAR_DOUBLE_QUOTE + // | “%” | “@” | “`”) + && c !== CHAR_PERCENT + && c !== CHAR_COMMERCIAL_AT + && c !== CHAR_GRAVE_ACCENT; +} + +// Determines whether block indentation indicator is required. +function needIndentIndicator(string) { + var leadingSpaceRe = /^\n* /; + return leadingSpaceRe.test(string); +} + +var STYLE_PLAIN = 1, + STYLE_SINGLE = 2, + STYLE_LITERAL = 3, + STYLE_FOLDED = 4, + STYLE_DOUBLE = 5; + +// Determines which scalar styles are possible and returns the preferred style. +// lineWidth = -1 => no limit. +// Pre-conditions: str.length > 0. +// Post-conditions: +// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. +// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). +// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). +function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) { + var i; + var char, prev_char; + var hasLineBreak = false; + var hasFoldableLine = false; // only checked if shouldTrackWidth + var shouldTrackWidth = lineWidth !== -1; + var previousLineBreak = -1; // count the first line correctly + var plain = isPlainSafeFirst(string.charCodeAt(0)) + && !isWhitespace(string.charCodeAt(string.length - 1)); + + if (singleLineOnly) { + // Case: no block styles. + // Check for disallowed characters to rule out plain and single. + for (i = 0; i < string.length; i++) { + char = string.charCodeAt(i); + if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + prev_char = i > 0 ? string.charCodeAt(i - 1) : null; + plain = plain && isPlainSafe(char, prev_char); + } + } else { + // Case: block styles permitted. + for (i = 0; i < string.length; i++) { + char = string.charCodeAt(i); + if (char === CHAR_LINE_FEED) { + hasLineBreak = true; + // Check if any line can be folded. + if (shouldTrackWidth) { + hasFoldableLine = hasFoldableLine || + // Foldable line = too long, and not more-indented. + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' '); + previousLineBreak = i; + } + } else if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + prev_char = i > 0 ? string.charCodeAt(i - 1) : null; + plain = plain && isPlainSafe(char, prev_char); + } + // in case the end is missing a \n + hasFoldableLine = hasFoldableLine || (shouldTrackWidth && + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' ')); + } + // Although every style can represent \n without escaping, prefer block styles + // for multiline, since they're more readable and they don't add empty lines. + // Also prefer folding a super-long line. + if (!hasLineBreak && !hasFoldableLine) { + // Strings interpretable as another type have to be quoted; + // e.g. the string 'true' vs. the boolean true. + return plain && !testAmbiguousType(string) + ? STYLE_PLAIN : STYLE_SINGLE; + } + // Edge case: block indentation indicator can only have one digit. + if (indentPerLevel > 9 && needIndentIndicator(string)) { + return STYLE_DOUBLE; + } + // At this point we know block styles are valid. + // Prefer literal style unless we want to fold. + return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; +} + +// Note: line breaking/folding is implemented for only the folded style. +// NB. We drop the last trailing newline (if any) of a returned block scalar +// since the dumper adds its own newline. This always works: +// • No ending newline => unaffected; already using strip "-" chomping. +// • Ending newline => removed then restored. +// Importantly, this keeps the "+" chomp indicator from gaining an extra line. +function writeScalar(state, string, level, iskey) { + state.dump = (function () { + if (string.length === 0) { + return "''"; + } + if (!state.noCompatMode && + DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) { + return "'" + string + "'"; + } + + var indent = state.indent * Math.max(1, level); // no 0-indent scalars + // As indentation gets deeper, let the width decrease monotonically + // to the lower bound min(state.lineWidth, 40). + // Note that this implies + // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. + // state.lineWidth > 40 + state.indent: width decreases until the lower bound. + // This behaves better than a constant minimum width which disallows narrower options, + // or an indent threshold which causes the width to suddenly increase. + var lineWidth = state.lineWidth === -1 + ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); + + // Without knowing if keys are implicit/explicit, assume implicit for safety. + var singleLineOnly = iskey + // No block styles in flow mode. + || (state.flowLevel > -1 && level >= state.flowLevel); + function testAmbiguity(string) { + return testImplicitResolving(state, string); + } + + switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) { + case STYLE_PLAIN: + return string; + case STYLE_SINGLE: + return "'" + string.replace(/'/g, "''") + "'"; + case STYLE_LITERAL: + return '|' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(string, indent)); + case STYLE_FOLDED: + return '>' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); + case STYLE_DOUBLE: + return '"' + escapeString(string, lineWidth) + '"'; + default: + throw new YAMLException('impossible error: invalid scalar style'); + } + }()); +} + +// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. +function blockHeader(string, indentPerLevel) { + var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; + + // note the special case: the string '\n' counts as a "trailing" empty line. + var clip = string[string.length - 1] === '\n'; + var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); + var chomp = keep ? '+' : (clip ? '' : '-'); + + return indentIndicator + chomp + '\n'; +} + +// (See the note for writeScalar.) +function dropEndingNewline(string) { + return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; +} + +// Note: a long line without a suitable break point will exceed the width limit. +// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. +function foldString(string, width) { + // In folded style, $k$ consecutive newlines output as $k+1$ newlines— + // unless they're before or after a more-indented line, or at the very + // beginning or end, in which case $k$ maps to $k$. + // Therefore, parse each chunk as newline(s) followed by a content line. + var lineRe = /(\n+)([^\n]*)/g; + + // first line (possibly an empty line) + var result = (function () { + var nextLF = string.indexOf('\n'); + nextLF = nextLF !== -1 ? nextLF : string.length; + lineRe.lastIndex = nextLF; + return foldLine(string.slice(0, nextLF), width); + }()); + // If we haven't reached the first content line yet, don't add an extra \n. + var prevMoreIndented = string[0] === '\n' || string[0] === ' '; + var moreIndented; + + // rest of the lines + var match; + while ((match = lineRe.exec(string))) { + var prefix = match[1], line = match[2]; + moreIndented = (line[0] === ' '); + result += prefix + + (!prevMoreIndented && !moreIndented && line !== '' + ? '\n' : '') + + foldLine(line, width); + prevMoreIndented = moreIndented; + } + + return result; +} + +// Greedy line breaking. +// Picks the longest line under the limit each time, +// otherwise settles for the shortest line over the limit. +// NB. More-indented lines *cannot* be folded, as that would add an extra \n. +function foldLine(line, width) { + if (line === '' || line[0] === ' ') return line; + + // Since a more-indented line adds a \n, breaks can't be followed by a space. + var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. + var match; + // start is an inclusive index. end, curr, and next are exclusive. + var start = 0, end, curr = 0, next = 0; + var result = ''; + + // Invariants: 0 <= start <= length-1. + // 0 <= curr <= next <= max(0, length-2). curr - start <= width. + // Inside the loop: + // A match implies length >= 2, so curr and next are <= length-2. + while ((match = breakRe.exec(line))) { + next = match.index; + // maintain invariant: curr - start <= width + if (next - start > width) { + end = (curr > start) ? curr : next; // derive end <= length-2 + result += '\n' + line.slice(start, end); + // skip the space that was output as \n + start = end + 1; // derive start <= length-1 + } + curr = next; + } + + // By the invariants, start <= length-1, so there is something left over. + // It is either the whole string or a part starting from non-whitespace. + result += '\n'; + // Insert a break if the remainder is too long and there is a break available. + if (line.length - start > width && curr > start) { + result += line.slice(start, curr) + '\n' + line.slice(curr + 1); + } else { + result += line.slice(start); + } + + return result.slice(1); // drop extra \n joiner +} + +// Escapes a double-quoted string. +function escapeString(string) { + var result = ''; + var char, nextChar; + var escapeSeq; + + for (var i = 0; i < string.length; i++) { + char = string.charCodeAt(i); + // Check for surrogate pairs (reference Unicode 3.0 section "3.7 Surrogates"). + if (char >= 0xD800 && char <= 0xDBFF/* high surrogate */) { + nextChar = string.charCodeAt(i + 1); + if (nextChar >= 0xDC00 && nextChar <= 0xDFFF/* low surrogate */) { + // Combine the surrogate pair and store it escaped. + result += encodeHex((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000); + // Advance index one extra since we already used that char here. + i++; continue; + } + } + escapeSeq = ESCAPE_SEQUENCES[char]; + result += !escapeSeq && isPrintable(char) + ? string[i] + : escapeSeq || encodeHex(char); + } + + return result; +} + +function writeFlowSequence(state, level, object) { + var _result = '', + _tag = state.tag, + index, + length; + + for (index = 0, length = object.length; index < length; index += 1) { + // Write only valid elements. + if (writeNode(state, level, object[index], false, false)) { + if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : ''); + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = '[' + _result + ']'; +} + +function writeBlockSequence(state, level, object, compact) { + var _result = '', + _tag = state.tag, + index, + length; + + for (index = 0, length = object.length; index < length; index += 1) { + // Write only valid elements. + if (writeNode(state, level + 1, object[index], true, true)) { + if (!compact || index !== 0) { + _result += generateNextLine(state, level); + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + _result += '-'; + } else { + _result += '- '; + } + + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = _result || '[]'; // Empty sequence if no valid values. +} + +function writeFlowMapping(state, level, object) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + pairBuffer; + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + + pairBuffer = ''; + if (index !== 0) pairBuffer += ', '; + + if (state.condenseFlow) pairBuffer += '"'; + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (!writeNode(state, level, objectKey, false, false)) { + continue; // Skip this pair because of invalid key; + } + + if (state.dump.length > 1024) pairBuffer += '? '; + + pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); + + if (!writeNode(state, level, objectValue, false, false)) { + continue; // Skip this pair because of invalid value. + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = '{' + _result + '}'; +} + +function writeBlockMapping(state, level, object, compact) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + explicitPair, + pairBuffer; + + // Allow sorting keys so that the output file is deterministic + if (state.sortKeys === true) { + // Default sorting + objectKeyList.sort(); + } else if (typeof state.sortKeys === 'function') { + // Custom sort function + objectKeyList.sort(state.sortKeys); + } else if (state.sortKeys) { + // Something is wrong + throw new YAMLException('sortKeys must be a boolean or a function'); + } + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + pairBuffer = ''; + + if (!compact || index !== 0) { + pairBuffer += generateNextLine(state, level); + } + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (!writeNode(state, level + 1, objectKey, true, true, true)) { + continue; // Skip this pair because of invalid key. + } + + explicitPair = (state.tag !== null && state.tag !== '?') || + (state.dump && state.dump.length > 1024); + + if (explicitPair) { + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += '?'; + } else { + pairBuffer += '? '; + } + } + + pairBuffer += state.dump; + + if (explicitPair) { + pairBuffer += generateNextLine(state, level); + } + + if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { + continue; // Skip this pair because of invalid value. + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += ':'; + } else { + pairBuffer += ': '; + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = _result || '{}'; // Empty mapping if no valid pairs. +} + +function detectType(state, object, explicit) { + var _result, typeList, index, length, type, style; + + typeList = explicit ? state.explicitTypes : state.implicitTypes; + + for (index = 0, length = typeList.length; index < length; index += 1) { + type = typeList[index]; + + if ((type.instanceOf || type.predicate) && + (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && + (!type.predicate || type.predicate(object))) { + + state.tag = explicit ? type.tag : '?'; + + if (type.represent) { + style = state.styleMap[type.tag] || type.defaultStyle; + + if (_toString.call(type.represent) === '[object Function]') { + _result = type.represent(object, style); + } else if (_hasOwnProperty.call(type.represent, style)) { + _result = type.represent[style](object, style); + } else { + throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); + } + + state.dump = _result; + } + + return true; + } + } + + return false; +} + +// Serializes `object` and writes it to global `result`. +// Returns true on success, or false on invalid object. +// +function writeNode(state, level, object, block, compact, iskey) { + state.tag = null; + state.dump = object; + + if (!detectType(state, object, false)) { + detectType(state, object, true); + } + + var type = _toString.call(state.dump); + + if (block) { + block = (state.flowLevel < 0 || state.flowLevel > level); + } + + var objectOrArray = type === '[object Object]' || type === '[object Array]', + duplicateIndex, + duplicate; + + if (objectOrArray) { + duplicateIndex = state.duplicates.indexOf(object); + duplicate = duplicateIndex !== -1; + } + + if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { + compact = false; + } + + if (duplicate && state.usedDuplicates[duplicateIndex]) { + state.dump = '*ref_' + duplicateIndex; + } else { + if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { + state.usedDuplicates[duplicateIndex] = true; + } + if (type === '[object Object]') { + if (block && (Object.keys(state.dump).length !== 0)) { + writeBlockMapping(state, level, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowMapping(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object Array]') { + var arrayLevel = (state.noArrayIndent && (level > 0)) ? level - 1 : level; + if (block && (state.dump.length !== 0)) { + writeBlockSequence(state, arrayLevel, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowSequence(state, arrayLevel, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object String]') { + if (state.tag !== '?') { + writeScalar(state, state.dump, level, iskey); + } + } else { + if (state.skipInvalid) return false; + throw new YAMLException('unacceptable kind of an object to dump ' + type); + } + + if (state.tag !== null && state.tag !== '?') { + state.dump = '!<' + state.tag + '> ' + state.dump; + } + } + + return true; +} + +function getDuplicateReferences(object, state) { + var objects = [], + duplicatesIndexes = [], + index, + length; + + inspectNode(object, objects, duplicatesIndexes); + + for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { + state.duplicates.push(objects[duplicatesIndexes[index]]); + } + state.usedDuplicates = new Array(length); +} + +function inspectNode(object, objects, duplicatesIndexes) { + var objectKeyList, + index, + length; + + if (object !== null && typeof object === 'object') { + index = objects.indexOf(object); + if (index !== -1) { + if (duplicatesIndexes.indexOf(index) === -1) { + duplicatesIndexes.push(index); + } + } else { + objects.push(object); + + if (Array.isArray(object)) { + for (index = 0, length = object.length; index < length; index += 1) { + inspectNode(object[index], objects, duplicatesIndexes); + } + } else { + objectKeyList = Object.keys(object); + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); + } + } + } + } +} + +function dump(input, options) { + options = options || {}; + + var state = new State(options); + + if (!state.noRefs) getDuplicateReferences(input, state); + + if (writeNode(state, 0, input, true, true)) return state.dump + '\n'; + + return ''; +} + +function safeDump(input, options) { + return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +} + +module.exports.dump = dump; +module.exports.safeDump = safeDump; + +},{"./common":2,"./exception":4,"./schema/default_full":9,"./schema/default_safe":10}],4:[function(require,module,exports){ +// YAML error class. http://stackoverflow.com/questions/8458984 +// +'use strict'; + +function YAMLException(reason, mark) { + // Super constructor + Error.call(this); + + this.name = 'YAMLException'; + this.reason = reason; + this.mark = mark; + this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : ''); + + // Include stack trace in error object + if (Error.captureStackTrace) { + // Chrome and NodeJS + Error.captureStackTrace(this, this.constructor); + } else { + // FF, IE 10+ and Safari 6+. Fallback for others + this.stack = (new Error()).stack || ''; + } +} + + +// Inherit from Error +YAMLException.prototype = Object.create(Error.prototype); +YAMLException.prototype.constructor = YAMLException; + + +YAMLException.prototype.toString = function toString(compact) { + var result = this.name + ': '; + + result += this.reason || '(unknown reason)'; + + if (!compact && this.mark) { + result += ' ' + this.mark.toString(); + } + + return result; +}; + + +module.exports = YAMLException; + +},{}],5:[function(require,module,exports){ +'use strict'; + +/*eslint-disable max-len,no-use-before-define*/ + +var common = require('./common'); +var YAMLException = require('./exception'); +var Mark = require('./mark'); +var DEFAULT_SAFE_SCHEMA = require('./schema/default_safe'); +var DEFAULT_FULL_SCHEMA = require('./schema/default_full'); + + +var _hasOwnProperty = Object.prototype.hasOwnProperty; + + +var CONTEXT_FLOW_IN = 1; +var CONTEXT_FLOW_OUT = 2; +var CONTEXT_BLOCK_IN = 3; +var CONTEXT_BLOCK_OUT = 4; + + +var CHOMPING_CLIP = 1; +var CHOMPING_STRIP = 2; +var CHOMPING_KEEP = 3; + + +var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; +var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; +var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; +var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; +var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; + + +function _class(obj) { return Object.prototype.toString.call(obj); } + +function is_EOL(c) { + return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); +} + +function is_WHITE_SPACE(c) { + return (c === 0x09/* Tab */) || (c === 0x20/* Space */); +} + +function is_WS_OR_EOL(c) { + return (c === 0x09/* Tab */) || + (c === 0x20/* Space */) || + (c === 0x0A/* LF */) || + (c === 0x0D/* CR */); +} + +function is_FLOW_INDICATOR(c) { + return c === 0x2C/* , */ || + c === 0x5B/* [ */ || + c === 0x5D/* ] */ || + c === 0x7B/* { */ || + c === 0x7D/* } */; +} + +function fromHexCode(c) { + var lc; + + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + /*eslint-disable no-bitwise*/ + lc = c | 0x20; + + if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { + return lc - 0x61 + 10; + } + + return -1; +} + +function escapedHexLen(c) { + if (c === 0x78/* x */) { return 2; } + if (c === 0x75/* u */) { return 4; } + if (c === 0x55/* U */) { return 8; } + return 0; +} + +function fromDecimalCode(c) { + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + return -1; +} + +function simpleEscapeSequence(c) { + /* eslint-disable indent */ + return (c === 0x30/* 0 */) ? '\x00' : + (c === 0x61/* a */) ? '\x07' : + (c === 0x62/* b */) ? '\x08' : + (c === 0x74/* t */) ? '\x09' : + (c === 0x09/* Tab */) ? '\x09' : + (c === 0x6E/* n */) ? '\x0A' : + (c === 0x76/* v */) ? '\x0B' : + (c === 0x66/* f */) ? '\x0C' : + (c === 0x72/* r */) ? '\x0D' : + (c === 0x65/* e */) ? '\x1B' : + (c === 0x20/* Space */) ? ' ' : + (c === 0x22/* " */) ? '\x22' : + (c === 0x2F/* / */) ? '/' : + (c === 0x5C/* \ */) ? '\x5C' : + (c === 0x4E/* N */) ? '\x85' : + (c === 0x5F/* _ */) ? '\xA0' : + (c === 0x4C/* L */) ? '\u2028' : + (c === 0x50/* P */) ? '\u2029' : ''; +} + +function charFromCodepoint(c) { + if (c <= 0xFFFF) { + return String.fromCharCode(c); + } + // Encode UTF-16 surrogate pair + // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF + return String.fromCharCode( + ((c - 0x010000) >> 10) + 0xD800, + ((c - 0x010000) & 0x03FF) + 0xDC00 + ); +} + +var simpleEscapeCheck = new Array(256); // integer, for fast access +var simpleEscapeMap = new Array(256); +for (var i = 0; i < 256; i++) { + simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; + simpleEscapeMap[i] = simpleEscapeSequence(i); +} + + +function State(input, options) { + this.input = input; + + this.filename = options['filename'] || null; + this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; + this.onWarning = options['onWarning'] || null; + this.legacy = options['legacy'] || false; + this.json = options['json'] || false; + this.listener = options['listener'] || null; + + this.implicitTypes = this.schema.compiledImplicit; + this.typeMap = this.schema.compiledTypeMap; + + this.length = input.length; + this.position = 0; + this.line = 0; + this.lineStart = 0; + this.lineIndent = 0; + + this.documents = []; + + /* + this.version; + this.checkLineBreaks; + this.tagMap; + this.anchorMap; + this.tag; + this.anchor; + this.kind; + this.result;*/ + +} + + +function generateError(state, message) { + return new YAMLException( + message, + new Mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart))); +} + +function throwError(state, message) { + throw generateError(state, message); +} + +function throwWarning(state, message) { + if (state.onWarning) { + state.onWarning.call(null, generateError(state, message)); + } +} + + +var directiveHandlers = { + + YAML: function handleYamlDirective(state, name, args) { + + var match, major, minor; + + if (state.version !== null) { + throwError(state, 'duplication of %YAML directive'); + } + + if (args.length !== 1) { + throwError(state, 'YAML directive accepts exactly one argument'); + } + + match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); + + if (match === null) { + throwError(state, 'ill-formed argument of the YAML directive'); + } + + major = parseInt(match[1], 10); + minor = parseInt(match[2], 10); + + if (major !== 1) { + throwError(state, 'unacceptable YAML version of the document'); + } + + state.version = args[0]; + state.checkLineBreaks = (minor < 2); + + if (minor !== 1 && minor !== 2) { + throwWarning(state, 'unsupported YAML version of the document'); + } + }, + + TAG: function handleTagDirective(state, name, args) { + + var handle, prefix; + + if (args.length !== 2) { + throwError(state, 'TAG directive accepts exactly two arguments'); + } + + handle = args[0]; + prefix = args[1]; + + if (!PATTERN_TAG_HANDLE.test(handle)) { + throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); + } + + if (_hasOwnProperty.call(state.tagMap, handle)) { + throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); + } + + if (!PATTERN_TAG_URI.test(prefix)) { + throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); + } + + state.tagMap[handle] = prefix; + } +}; + + +function captureSegment(state, start, end, checkJson) { + var _position, _length, _character, _result; + + if (start < end) { + _result = state.input.slice(start, end); + + if (checkJson) { + for (_position = 0, _length = _result.length; _position < _length; _position += 1) { + _character = _result.charCodeAt(_position); + if (!(_character === 0x09 || + (0x20 <= _character && _character <= 0x10FFFF))) { + throwError(state, 'expected valid JSON character'); + } + } + } else if (PATTERN_NON_PRINTABLE.test(_result)) { + throwError(state, 'the stream contains non-printable characters'); + } + + state.result += _result; + } +} + +function mergeMappings(state, destination, source, overridableKeys) { + var sourceKeys, key, index, quantity; + + if (!common.isObject(source)) { + throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); + } + + sourceKeys = Object.keys(source); + + for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { + key = sourceKeys[index]; + + if (!_hasOwnProperty.call(destination, key)) { + destination[key] = source[key]; + overridableKeys[key] = true; + } + } +} + +function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) { + var index, quantity; + + // The output is a plain object here, so keys can only be strings. + // We need to convert keyNode to a string, but doing so can hang the process + // (deeply nested arrays that explode exponentially using aliases). + if (Array.isArray(keyNode)) { + keyNode = Array.prototype.slice.call(keyNode); + + for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { + if (Array.isArray(keyNode[index])) { + throwError(state, 'nested arrays are not supported inside keys'); + } + + if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { + keyNode[index] = '[object Object]'; + } + } + } + + // Avoid code execution in load() via toString property + // (still use its own toString for arrays, timestamps, + // and whatever user schema extensions happen to have @@toStringTag) + if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { + keyNode = '[object Object]'; + } + + + keyNode = String(keyNode); + + if (_result === null) { + _result = {}; + } + + if (keyTag === 'tag:yaml.org,2002:merge') { + if (Array.isArray(valueNode)) { + for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { + mergeMappings(state, _result, valueNode[index], overridableKeys); + } + } else { + mergeMappings(state, _result, valueNode, overridableKeys); + } + } else { + if (!state.json && + !_hasOwnProperty.call(overridableKeys, keyNode) && + _hasOwnProperty.call(_result, keyNode)) { + state.line = startLine || state.line; + state.position = startPos || state.position; + throwError(state, 'duplicated mapping key'); + } + _result[keyNode] = valueNode; + delete overridableKeys[keyNode]; + } + + return _result; +} + +function readLineBreak(state) { + var ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x0A/* LF */) { + state.position++; + } else if (ch === 0x0D/* CR */) { + state.position++; + if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { + state.position++; + } + } else { + throwError(state, 'a line break is expected'); + } + + state.line += 1; + state.lineStart = state.position; +} + +function skipSeparationSpace(state, allowComments, checkIndent) { + var lineBreaks = 0, + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (allowComments && ch === 0x23/* # */) { + do { + ch = state.input.charCodeAt(++state.position); + } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); + } + + if (is_EOL(ch)) { + readLineBreak(state); + + ch = state.input.charCodeAt(state.position); + lineBreaks++; + state.lineIndent = 0; + + while (ch === 0x20/* Space */) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + } else { + break; + } + } + + if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { + throwWarning(state, 'deficient indentation'); + } + + return lineBreaks; +} + +function testDocumentSeparator(state) { + var _position = state.position, + ch; + + ch = state.input.charCodeAt(_position); + + // Condition state.position === state.lineStart is tested + // in parent on each call, for efficiency. No needs to test here again. + if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && + ch === state.input.charCodeAt(_position + 1) && + ch === state.input.charCodeAt(_position + 2)) { + + _position += 3; + + ch = state.input.charCodeAt(_position); + + if (ch === 0 || is_WS_OR_EOL(ch)) { + return true; + } + } + + return false; +} + +function writeFoldedLines(state, count) { + if (count === 1) { + state.result += ' '; + } else if (count > 1) { + state.result += common.repeat('\n', count - 1); + } +} + + +function readPlainScalar(state, nodeIndent, withinFlowCollection) { + var preceding, + following, + captureStart, + captureEnd, + hasPendingContent, + _line, + _lineStart, + _lineIndent, + _kind = state.kind, + _result = state.result, + ch; + + ch = state.input.charCodeAt(state.position); + + if (is_WS_OR_EOL(ch) || + is_FLOW_INDICATOR(ch) || + ch === 0x23/* # */ || + ch === 0x26/* & */ || + ch === 0x2A/* * */ || + ch === 0x21/* ! */ || + ch === 0x7C/* | */ || + ch === 0x3E/* > */ || + ch === 0x27/* ' */ || + ch === 0x22/* " */ || + ch === 0x25/* % */ || + ch === 0x40/* @ */ || + ch === 0x60/* ` */) { + return false; + } + + if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + return false; + } + } + + state.kind = 'scalar'; + state.result = ''; + captureStart = captureEnd = state.position; + hasPendingContent = false; + + while (ch !== 0) { + if (ch === 0x3A/* : */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + break; + } + + } else if (ch === 0x23/* # */) { + preceding = state.input.charCodeAt(state.position - 1); + + if (is_WS_OR_EOL(preceding)) { + break; + } + + } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || + withinFlowCollection && is_FLOW_INDICATOR(ch)) { + break; + + } else if (is_EOL(ch)) { + _line = state.line; + _lineStart = state.lineStart; + _lineIndent = state.lineIndent; + skipSeparationSpace(state, false, -1); + + if (state.lineIndent >= nodeIndent) { + hasPendingContent = true; + ch = state.input.charCodeAt(state.position); + continue; + } else { + state.position = captureEnd; + state.line = _line; + state.lineStart = _lineStart; + state.lineIndent = _lineIndent; + break; + } + } + + if (hasPendingContent) { + captureSegment(state, captureStart, captureEnd, false); + writeFoldedLines(state, state.line - _line); + captureStart = captureEnd = state.position; + hasPendingContent = false; + } + + if (!is_WHITE_SPACE(ch)) { + captureEnd = state.position + 1; + } + + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, captureEnd, false); + + if (state.result) { + return true; + } + + state.kind = _kind; + state.result = _result; + return false; +} + +function readSingleQuotedScalar(state, nodeIndent) { + var ch, + captureStart, captureEnd; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x27/* ' */) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x27/* ' */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x27/* ' */) { + captureStart = state.position; + state.position++; + captureEnd = state.position; + } else { + return true; + } + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a single quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a single quoted scalar'); +} + +function readDoubleQuotedScalar(state, nodeIndent) { + var captureStart, + captureEnd, + hexLength, + hexResult, + tmp, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x22/* " */) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x22/* " */) { + captureSegment(state, captureStart, state.position, true); + state.position++; + return true; + + } else if (ch === 0x5C/* \ */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (is_EOL(ch)) { + skipSeparationSpace(state, false, nodeIndent); + + // TODO: rework to inline fn with no type cast? + } else if (ch < 256 && simpleEscapeCheck[ch]) { + state.result += simpleEscapeMap[ch]; + state.position++; + + } else if ((tmp = escapedHexLen(ch)) > 0) { + hexLength = tmp; + hexResult = 0; + + for (; hexLength > 0; hexLength--) { + ch = state.input.charCodeAt(++state.position); + + if ((tmp = fromHexCode(ch)) >= 0) { + hexResult = (hexResult << 4) + tmp; + + } else { + throwError(state, 'expected hexadecimal character'); + } + } + + state.result += charFromCodepoint(hexResult); + + state.position++; + + } else { + throwError(state, 'unknown escape sequence'); + } + + captureStart = captureEnd = state.position; + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a double quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a double quoted scalar'); +} + +function readFlowCollection(state, nodeIndent) { + var readNext = true, + _line, + _tag = state.tag, + _result, + _anchor = state.anchor, + following, + terminator, + isPair, + isExplicitPair, + isMapping, + overridableKeys = {}, + keyNode, + keyTag, + valueNode, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x5B/* [ */) { + terminator = 0x5D;/* ] */ + isMapping = false; + _result = []; + } else if (ch === 0x7B/* { */) { + terminator = 0x7D;/* } */ + isMapping = true; + _result = {}; + } else { + return false; + } + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(++state.position); + + while (ch !== 0) { + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === terminator) { + state.position++; + state.tag = _tag; + state.anchor = _anchor; + state.kind = isMapping ? 'mapping' : 'sequence'; + state.result = _result; + return true; + } else if (!readNext) { + throwError(state, 'missed comma between flow collection entries'); + } + + keyTag = keyNode = valueNode = null; + isPair = isExplicitPair = false; + + if (ch === 0x3F/* ? */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following)) { + isPair = isExplicitPair = true; + state.position++; + skipSeparationSpace(state, true, nodeIndent); + } + } + + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + keyTag = state.tag; + keyNode = state.result; + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { + isPair = true; + ch = state.input.charCodeAt(++state.position); + skipSeparationSpace(state, true, nodeIndent); + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + valueNode = state.result; + } + + if (isMapping) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode); + } else if (isPair) { + _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode)); + } else { + _result.push(keyNode); + } + + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x2C/* , */) { + readNext = true; + ch = state.input.charCodeAt(++state.position); + } else { + readNext = false; + } + } + + throwError(state, 'unexpected end of the stream within a flow collection'); +} + +function readBlockScalar(state, nodeIndent) { + var captureStart, + folding, + chomping = CHOMPING_CLIP, + didReadContent = false, + detectedIndent = false, + textIndent = nodeIndent, + emptyLines = 0, + atMoreIndented = false, + tmp, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x7C/* | */) { + folding = false; + } else if (ch === 0x3E/* > */) { + folding = true; + } else { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + + while (ch !== 0) { + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { + if (CHOMPING_CLIP === chomping) { + chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; + } else { + throwError(state, 'repeat of a chomping mode identifier'); + } + + } else if ((tmp = fromDecimalCode(ch)) >= 0) { + if (tmp === 0) { + throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); + } else if (!detectedIndent) { + textIndent = nodeIndent + tmp - 1; + detectedIndent = true; + } else { + throwError(state, 'repeat of an indentation width identifier'); + } + + } else { + break; + } + } + + if (is_WHITE_SPACE(ch)) { + do { ch = state.input.charCodeAt(++state.position); } + while (is_WHITE_SPACE(ch)); + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (!is_EOL(ch) && (ch !== 0)); + } + } + + while (ch !== 0) { + readLineBreak(state); + state.lineIndent = 0; + + ch = state.input.charCodeAt(state.position); + + while ((!detectedIndent || state.lineIndent < textIndent) && + (ch === 0x20/* Space */)) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + + if (!detectedIndent && state.lineIndent > textIndent) { + textIndent = state.lineIndent; + } + + if (is_EOL(ch)) { + emptyLines++; + continue; + } + + // End of the scalar. + if (state.lineIndent < textIndent) { + + // Perform the chomping. + if (chomping === CHOMPING_KEEP) { + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } else if (chomping === CHOMPING_CLIP) { + if (didReadContent) { // i.e. only if the scalar is not empty. + state.result += '\n'; + } + } + + // Break this `while` cycle and go to the funciton's epilogue. + break; + } + + // Folded style: use fancy rules to handle line breaks. + if (folding) { + + // Lines starting with white space characters (more-indented lines) are not folded. + if (is_WHITE_SPACE(ch)) { + atMoreIndented = true; + // except for the first content line (cf. Example 8.1) + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + + // End of more-indented block. + } else if (atMoreIndented) { + atMoreIndented = false; + state.result += common.repeat('\n', emptyLines + 1); + + // Just one line break - perceive as the same line. + } else if (emptyLines === 0) { + if (didReadContent) { // i.e. only if we have already read some scalar content. + state.result += ' '; + } + + // Several line breaks - perceive as different lines. + } else { + state.result += common.repeat('\n', emptyLines); + } + + // Literal style: just add exact number of line breaks between content lines. + } else { + // Keep all line breaks except the header line break. + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } + + didReadContent = true; + detectedIndent = true; + emptyLines = 0; + captureStart = state.position; + + while (!is_EOL(ch) && (ch !== 0)) { + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, state.position, false); + } + + return true; +} + +function readBlockSequence(state, nodeIndent) { + var _line, + _tag = state.tag, + _anchor = state.anchor, + _result = [], + following, + detected = false, + ch; + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + + if (ch !== 0x2D/* - */) { + break; + } + + following = state.input.charCodeAt(state.position + 1); + + if (!is_WS_OR_EOL(following)) { + break; + } + + detected = true; + state.position++; + + if (skipSeparationSpace(state, true, -1)) { + if (state.lineIndent <= nodeIndent) { + _result.push(null); + ch = state.input.charCodeAt(state.position); + continue; + } + } + + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); + _result.push(state.result); + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a sequence entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } + + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'sequence'; + state.result = _result; + return true; + } + return false; +} + +function readBlockMapping(state, nodeIndent, flowIndent) { + var following, + allowCompact, + _line, + _pos, + _tag = state.tag, + _anchor = state.anchor, + _result = {}, + overridableKeys = {}, + keyTag = null, + keyNode = null, + valueNode = null, + atExplicitKey = false, + detected = false, + ch; + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + following = state.input.charCodeAt(state.position + 1); + _line = state.line; // Save the current line. + _pos = state.position; + + // + // Explicit notation case. There are two separate blocks: + // first for the key (denoted by "?") and second for the value (denoted by ":") + // + if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { + + if (ch === 0x3F/* ? */) { + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = true; + allowCompact = true; + + } else if (atExplicitKey) { + // i.e. 0x3A/* : */ === character after the explicit key. + atExplicitKey = false; + allowCompact = true; + + } else { + throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); + } + + state.position += 1; + ch = following; + + // + // Implicit notation case. Flow-style node as the key first, then ":", and the value. + // + } else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { + + if (state.line === _line) { + ch = state.input.charCodeAt(state.position); + + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (ch === 0x3A/* : */) { + ch = state.input.charCodeAt(++state.position); + + if (!is_WS_OR_EOL(ch)) { + throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); + } + + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = false; + allowCompact = false; + keyTag = state.tag; + keyNode = state.result; + + } else if (detected) { + throwError(state, 'can not read an implicit mapping pair; a colon is missed'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + + } else if (detected) { + throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + + } else { + break; // Reading is done. Go to the epilogue. + } + + // + // Common reading code for both explicit and implicit notations. + // + if (state.line === _line || state.lineIndent > nodeIndent) { + if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { + if (atExplicitKey) { + keyNode = state.result; + } else { + valueNode = state.result; + } + } + + if (!atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _pos); + keyTag = keyNode = valueNode = null; + } + + skipSeparationSpace(state, true, -1); + ch = state.input.charCodeAt(state.position); + } + + if (state.lineIndent > nodeIndent && (ch !== 0)) { + throwError(state, 'bad indentation of a mapping entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } + + // + // Epilogue. + // + + // Special case: last mapping's node contains only the key in explicit notation. + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); + } + + // Expose the resulting mapping. + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'mapping'; + state.result = _result; + } + + return detected; +} + +function readTagProperty(state) { + var _position, + isVerbatim = false, + isNamed = false, + tagHandle, + tagName, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x21/* ! */) return false; + + if (state.tag !== null) { + throwError(state, 'duplication of a tag property'); + } + + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x3C/* < */) { + isVerbatim = true; + ch = state.input.charCodeAt(++state.position); + + } else if (ch === 0x21/* ! */) { + isNamed = true; + tagHandle = '!!'; + ch = state.input.charCodeAt(++state.position); + + } else { + tagHandle = '!'; + } + + _position = state.position; + + if (isVerbatim) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && ch !== 0x3E/* > */); + + if (state.position < state.length) { + tagName = state.input.slice(_position, state.position); + ch = state.input.charCodeAt(++state.position); + } else { + throwError(state, 'unexpected end of the stream within a verbatim tag'); + } + } else { + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + + if (ch === 0x21/* ! */) { + if (!isNamed) { + tagHandle = state.input.slice(_position - 1, state.position + 1); + + if (!PATTERN_TAG_HANDLE.test(tagHandle)) { + throwError(state, 'named tag handle cannot contain such characters'); + } + + isNamed = true; + _position = state.position + 1; + } else { + throwError(state, 'tag suffix cannot contain exclamation marks'); + } + } + + ch = state.input.charCodeAt(++state.position); + } + + tagName = state.input.slice(_position, state.position); + + if (PATTERN_FLOW_INDICATORS.test(tagName)) { + throwError(state, 'tag suffix cannot contain flow indicator characters'); + } + } + + if (tagName && !PATTERN_TAG_URI.test(tagName)) { + throwError(state, 'tag name cannot contain such characters: ' + tagName); + } + + if (isVerbatim) { + state.tag = tagName; + + } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) { + state.tag = state.tagMap[tagHandle] + tagName; + + } else if (tagHandle === '!') { + state.tag = '!' + tagName; + + } else if (tagHandle === '!!') { + state.tag = 'tag:yaml.org,2002:' + tagName; + + } else { + throwError(state, 'undeclared tag handle "' + tagHandle + '"'); + } + + return true; +} + +function readAnchorProperty(state) { + var _position, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x26/* & */) return false; + + if (state.anchor !== null) { + throwError(state, 'duplication of an anchor property'); + } + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an anchor node must contain at least one character'); + } + + state.anchor = state.input.slice(_position, state.position); + return true; +} + +function readAlias(state) { + var _position, alias, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x2A/* * */) return false; + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an alias node must contain at least one character'); + } + + alias = state.input.slice(_position, state.position); + + if (!_hasOwnProperty.call(state.anchorMap, alias)) { + throwError(state, 'unidentified alias "' + alias + '"'); + } + + state.result = state.anchorMap[alias]; + skipSeparationSpace(state, true, -1); + return true; +} + +function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { + var allowBlockStyles, + allowBlockScalars, + allowBlockCollections, + indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } + } + + if (indentStatus === 1) { + while (readTagProperty(state) || readAnchorProperty(state)) { + if (skipSeparationSpace(state, true, -1)) { + atNewLine = true; + allowBlockCollections = allowBlockStyles; + + if (state.lineIndent > parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } else { + allowBlockCollections = false; + } + } + } + + if (allowBlockCollections) { + allowBlockCollections = atNewLine || allowCompact; + } + + if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { + if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { + flowIndent = parentIndent; + } else { + flowIndent = parentIndent + 1; + } + + blockIndent = state.position - state.lineStart; + + if (indentStatus === 1) { + if (allowBlockCollections && + (readBlockSequence(state, blockIndent) || + readBlockMapping(state, blockIndent, flowIndent)) || + readFlowCollection(state, flowIndent)) { + hasContent = true; + } else { + if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || + readSingleQuotedScalar(state, flowIndent) || + readDoubleQuotedScalar(state, flowIndent)) { + hasContent = true; + + } else if (readAlias(state)) { + hasContent = true; + + if (state.tag !== null || state.anchor !== null) { + throwError(state, 'alias node should not have any properties'); + } + + } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { + hasContent = true; + + if (state.tag === null) { + state.tag = '?'; + } + } + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } else if (indentStatus === 0) { + // Special case: block sequences are allowed to have same indentation level as the parent. + // http://www.yaml.org/spec/1.2/spec.html#id2799784 + hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); + } + } + + if (state.tag !== null && state.tag !== '!') { + if (state.tag === '?') { + // Implicit resolving is not allowed for non-scalar types, and '?' + // non-specific tag is only automatically assigned to plain scalars. + // + // We only need to check kind conformity in case user explicitly assigns '?' + // tag, for example like this: "! [0]" + // + if (state.result !== null && state.kind !== 'scalar') { + throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); + } + + for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { + type = state.implicitTypes[typeIndex]; + + if (type.resolve(state.result)) { // `state.result` updated in resolver if matched + state.result = type.construct(state.result); + state.tag = type.tag; + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + break; + } + } + } else if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) { + type = state.typeMap[state.kind || 'fallback'][state.tag]; + + if (state.result !== null && type.kind !== state.kind) { + throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); + } + + if (!type.resolve(state.result)) { // `state.result` updated in resolver if matched + throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); + } else { + state.result = type.construct(state.result); + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } else { + throwError(state, 'unknown tag !<' + state.tag + '>'); + } + } + + if (state.listener !== null) { + state.listener('close', state); + } + return state.tag !== null || state.anchor !== null || hasContent; +} + +function readDocument(state) { + var documentStart = state.position, + _position, + directiveName, + directiveArgs, + hasDirectives = false, + ch; + + state.version = null; + state.checkLineBreaks = state.legacy; + state.tagMap = {}; + state.anchorMap = {}; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if (state.lineIndent > 0 || ch !== 0x25/* % */) { + break; + } + + hasDirectives = true; + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveName = state.input.slice(_position, state.position); + directiveArgs = []; + + if (directiveName.length < 1) { + throwError(state, 'directive name must not be less than one character in length'); + } + + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && !is_EOL(ch)); + break; + } + + if (is_EOL(ch)) break; + + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveArgs.push(state.input.slice(_position, state.position)); + } + + if (ch !== 0) readLineBreak(state); + + if (_hasOwnProperty.call(directiveHandlers, directiveName)) { + directiveHandlers[directiveName](state, directiveName, directiveArgs); + } else { + throwWarning(state, 'unknown document directive "' + directiveName + '"'); + } + } + + skipSeparationSpace(state, true, -1); + + if (state.lineIndent === 0 && + state.input.charCodeAt(state.position) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + + } else if (hasDirectives) { + throwError(state, 'directives end mark is expected'); + } + + composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); + skipSeparationSpace(state, true, -1); + + if (state.checkLineBreaks && + PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { + throwWarning(state, 'non-ASCII line breaks are interpreted as content'); + } + + state.documents.push(state.result); + + if (state.position === state.lineStart && testDocumentSeparator(state)) { + + if (state.input.charCodeAt(state.position) === 0x2E/* . */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + } + return; + } + + if (state.position < (state.length - 1)) { + throwError(state, 'end of the stream or a document separator is expected'); + } else { + return; + } +} + + +function loadDocuments(input, options) { + input = String(input); + options = options || {}; + + if (input.length !== 0) { + + // Add tailing `\n` if not exists + if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && + input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { + input += '\n'; + } + + // Strip BOM + if (input.charCodeAt(0) === 0xFEFF) { + input = input.slice(1); + } + } + + var state = new State(input, options); + + var nullpos = input.indexOf('\0'); + + if (nullpos !== -1) { + state.position = nullpos; + throwError(state, 'null byte is not allowed in input'); + } + + // Use 0 as string terminator. That significantly simplifies bounds check. + state.input += '\0'; + + while (state.input.charCodeAt(state.position) === 0x20/* Space */) { + state.lineIndent += 1; + state.position += 1; + } + + while (state.position < (state.length - 1)) { + readDocument(state); + } + + return state.documents; +} + + +function loadAll(input, iterator, options) { + if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { + options = iterator; + iterator = null; + } + + var documents = loadDocuments(input, options); + + if (typeof iterator !== 'function') { + return documents; + } + + for (var index = 0, length = documents.length; index < length; index += 1) { + iterator(documents[index]); + } +} + + +function load(input, options) { + var documents = loadDocuments(input, options); + + if (documents.length === 0) { + /*eslint-disable no-undefined*/ + return undefined; + } else if (documents.length === 1) { + return documents[0]; + } + throw new YAMLException('expected a single document in the stream, but found more'); +} + + +function safeLoadAll(input, iterator, options) { + if (typeof iterator === 'object' && iterator !== null && typeof options === 'undefined') { + options = iterator; + iterator = null; + } + + return loadAll(input, iterator, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +} + + +function safeLoad(input, options) { + return load(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +} + + +module.exports.loadAll = loadAll; +module.exports.load = load; +module.exports.safeLoadAll = safeLoadAll; +module.exports.safeLoad = safeLoad; + +},{"./common":2,"./exception":4,"./mark":6,"./schema/default_full":9,"./schema/default_safe":10}],6:[function(require,module,exports){ +'use strict'; + + +var common = require('./common'); + + +function Mark(name, buffer, position, line, column) { + this.name = name; + this.buffer = buffer; + this.position = position; + this.line = line; + this.column = column; +} + + +Mark.prototype.getSnippet = function getSnippet(indent, maxLength) { + var head, start, tail, end, snippet; + + if (!this.buffer) return null; + + indent = indent || 4; + maxLength = maxLength || 75; + + head = ''; + start = this.position; + + while (start > 0 && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) { + start -= 1; + if (this.position - start > (maxLength / 2 - 1)) { + head = ' ... '; + start += 5; + break; + } + } + + tail = ''; + end = this.position; + + while (end < this.buffer.length && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end)) === -1) { + end += 1; + if (end - this.position > (maxLength / 2 - 1)) { + tail = ' ... '; + end -= 5; + break; + } + } + + snippet = this.buffer.slice(start, end); + + return common.repeat(' ', indent) + head + snippet + tail + '\n' + + common.repeat(' ', indent + this.position - start + head.length) + '^'; +}; + + +Mark.prototype.toString = function toString(compact) { + var snippet, where = ''; + + if (this.name) { + where += 'in "' + this.name + '" '; + } + + where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1); + + if (!compact) { + snippet = this.getSnippet(); + + if (snippet) { + where += ':\n' + snippet; + } + } + + return where; +}; + + +module.exports = Mark; + +},{"./common":2}],7:[function(require,module,exports){ +'use strict'; + +/*eslint-disable max-len*/ + +var common = require('./common'); +var YAMLException = require('./exception'); +var Type = require('./type'); + + +function compileList(schema, name, result) { + var exclude = []; + + schema.include.forEach(function (includedSchema) { + result = compileList(includedSchema, name, result); + }); + + schema[name].forEach(function (currentType) { + result.forEach(function (previousType, previousIndex) { + if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) { + exclude.push(previousIndex); + } + }); + + result.push(currentType); + }); + + return result.filter(function (type, index) { + return exclude.indexOf(index) === -1; + }); +} + + +function compileMap(/* lists... */) { + var result = { + scalar: {}, + sequence: {}, + mapping: {}, + fallback: {} + }, index, length; + + function collectType(type) { + result[type.kind][type.tag] = result['fallback'][type.tag] = type; + } + + for (index = 0, length = arguments.length; index < length; index += 1) { + arguments[index].forEach(collectType); + } + return result; +} + + +function Schema(definition) { + this.include = definition.include || []; + this.implicit = definition.implicit || []; + this.explicit = definition.explicit || []; + + this.implicit.forEach(function (type) { + if (type.loadKind && type.loadKind !== 'scalar') { + throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); + } + }); + + this.compiledImplicit = compileList(this, 'implicit', []); + this.compiledExplicit = compileList(this, 'explicit', []); + this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit); +} + + +Schema.DEFAULT = null; + + +Schema.create = function createSchema() { + var schemas, types; + + switch (arguments.length) { + case 1: + schemas = Schema.DEFAULT; + types = arguments[0]; + break; + + case 2: + schemas = arguments[0]; + types = arguments[1]; + break; + + default: + throw new YAMLException('Wrong number of arguments for Schema.create function'); + } + + schemas = common.toArray(schemas); + types = common.toArray(types); + + if (!schemas.every(function (schema) { return schema instanceof Schema; })) { + throw new YAMLException('Specified list of super schemas (or a single Schema object) contains a non-Schema object.'); + } + + if (!types.every(function (type) { return type instanceof Type; })) { + throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + } + + return new Schema({ + include: schemas, + explicit: types + }); +}; + + +module.exports = Schema; + +},{"./common":2,"./exception":4,"./type":13}],8:[function(require,module,exports){ +// Standard YAML's Core schema. +// http://www.yaml.org/spec/1.2/spec.html#id2804923 +// +// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. +// So, Core schema has no distinctions from JSON schema is JS-YAML. + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = new Schema({ + include: [ + require('./json') + ] +}); + +},{"../schema":7,"./json":12}],9:[function(require,module,exports){ +// JS-YAML's default schema for `load` function. +// It is not described in the YAML specification. +// +// This schema is based on JS-YAML's default safe schema and includes +// JavaScript-specific types: !!js/undefined, !!js/regexp and !!js/function. +// +// Also this schema is used as default base schema at `Schema.create` function. + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = Schema.DEFAULT = new Schema({ + include: [ + require('./default_safe') + ], + explicit: [ + require('../type/js/undefined'), + require('../type/js/regexp'), + require('../type/js/function') + ] +}); + +},{"../schema":7,"../type/js/function":18,"../type/js/regexp":19,"../type/js/undefined":20,"./default_safe":10}],10:[function(require,module,exports){ +// JS-YAML's default schema for `safeLoad` function. +// It is not described in the YAML specification. +// +// This schema is based on standard YAML's Core schema and includes most of +// extra types described at YAML tag repository. (http://yaml.org/type/) + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = new Schema({ + include: [ + require('./core') + ], + implicit: [ + require('../type/timestamp'), + require('../type/merge') + ], + explicit: [ + require('../type/binary'), + require('../type/omap'), + require('../type/pairs'), + require('../type/set') + ] +}); + +},{"../schema":7,"../type/binary":14,"../type/merge":22,"../type/omap":24,"../type/pairs":25,"../type/set":27,"../type/timestamp":29,"./core":8}],11:[function(require,module,exports){ +// Standard YAML's Failsafe schema. +// http://www.yaml.org/spec/1.2/spec.html#id2802346 + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = new Schema({ + explicit: [ + require('../type/str'), + require('../type/seq'), + require('../type/map') + ] +}); + +},{"../schema":7,"../type/map":21,"../type/seq":26,"../type/str":28}],12:[function(require,module,exports){ +// Standard YAML's JSON schema. +// http://www.yaml.org/spec/1.2/spec.html#id2803231 +// +// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. +// So, this schema is not such strict as defined in the YAML specification. +// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc. + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = new Schema({ + include: [ + require('./failsafe') + ], + implicit: [ + require('../type/null'), + require('../type/bool'), + require('../type/int'), + require('../type/float') + ] +}); + +},{"../schema":7,"../type/bool":15,"../type/float":16,"../type/int":17,"../type/null":23,"./failsafe":11}],13:[function(require,module,exports){ +'use strict'; + +var YAMLException = require('./exception'); + +var TYPE_CONSTRUCTOR_OPTIONS = [ + 'kind', + 'resolve', + 'construct', + 'instanceOf', + 'predicate', + 'represent', + 'defaultStyle', + 'styleAliases' +]; + +var YAML_NODE_KINDS = [ + 'scalar', + 'sequence', + 'mapping' +]; + +function compileStyleAliases(map) { + var result = {}; + + if (map !== null) { + Object.keys(map).forEach(function (style) { + map[style].forEach(function (alias) { + result[String(alias)] = style; + }); + }); + } + + return result; +} + +function Type(tag, options) { + options = options || {}; + + Object.keys(options).forEach(function (name) { + if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { + throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); + } + }); + + // TODO: Add tag format check. + this.tag = tag; + this.kind = options['kind'] || null; + this.resolve = options['resolve'] || function () { return true; }; + this.construct = options['construct'] || function (data) { return data; }; + this.instanceOf = options['instanceOf'] || null; + this.predicate = options['predicate'] || null; + this.represent = options['represent'] || null; + this.defaultStyle = options['defaultStyle'] || null; + this.styleAliases = compileStyleAliases(options['styleAliases'] || null); + + if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { + throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); + } +} + +module.exports = Type; + +},{"./exception":4}],14:[function(require,module,exports){ +'use strict'; + +/*eslint-disable no-bitwise*/ + +var NodeBuffer; + +try { + // A trick for browserified version, to not include `Buffer` shim + var _require = require; + NodeBuffer = _require('buffer').Buffer; +} catch (__) {} + +var Type = require('../type'); + + +// [ 64, 65, 66 ] -> [ padding, CR, LF ] +var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; + + +function resolveYamlBinary(data) { + if (data === null) return false; + + var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; + + // Convert one by one. + for (idx = 0; idx < max; idx++) { + code = map.indexOf(data.charAt(idx)); + + // Skip CR/LF + if (code > 64) continue; + + // Fail on illegal characters + if (code < 0) return false; + + bitlen += 6; + } + + // If there are any bits left, source was corrupted + return (bitlen % 8) === 0; +} + +function constructYamlBinary(data) { + var idx, tailbits, + input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan + max = input.length, + map = BASE64_MAP, + bits = 0, + result = []; + + // Collect by 6*4 bits (3 bytes) + + for (idx = 0; idx < max; idx++) { + if ((idx % 4 === 0) && idx) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } + + bits = (bits << 6) | map.indexOf(input.charAt(idx)); + } + + // Dump tail + + tailbits = (max % 4) * 6; + + if (tailbits === 0) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } else if (tailbits === 18) { + result.push((bits >> 10) & 0xFF); + result.push((bits >> 2) & 0xFF); + } else if (tailbits === 12) { + result.push((bits >> 4) & 0xFF); + } + + // Wrap into Buffer for NodeJS and leave Array for browser + if (NodeBuffer) { + // Support node 6.+ Buffer API when available + return NodeBuffer.from ? NodeBuffer.from(result) : new NodeBuffer(result); + } + + return result; +} + +function representYamlBinary(object /*, style*/) { + var result = '', bits = 0, idx, tail, + max = object.length, + map = BASE64_MAP; + + // Convert every three bytes to 4 ASCII characters. + + for (idx = 0; idx < max; idx++) { + if ((idx % 3 === 0) && idx) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } + + bits = (bits << 8) + object[idx]; + } + + // Dump tail + + tail = max % 3; + + if (tail === 0) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } else if (tail === 2) { + result += map[(bits >> 10) & 0x3F]; + result += map[(bits >> 4) & 0x3F]; + result += map[(bits << 2) & 0x3F]; + result += map[64]; + } else if (tail === 1) { + result += map[(bits >> 2) & 0x3F]; + result += map[(bits << 4) & 0x3F]; + result += map[64]; + result += map[64]; + } + + return result; +} + +function isBinary(object) { + return NodeBuffer && NodeBuffer.isBuffer(object); +} + +module.exports = new Type('tag:yaml.org,2002:binary', { + kind: 'scalar', + resolve: resolveYamlBinary, + construct: constructYamlBinary, + predicate: isBinary, + represent: representYamlBinary +}); + +},{"../type":13}],15:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +function resolveYamlBoolean(data) { + if (data === null) return false; + + var max = data.length; + + return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || + (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); +} + +function constructYamlBoolean(data) { + return data === 'true' || + data === 'True' || + data === 'TRUE'; +} + +function isBoolean(object) { + return Object.prototype.toString.call(object) === '[object Boolean]'; +} + +module.exports = new Type('tag:yaml.org,2002:bool', { + kind: 'scalar', + resolve: resolveYamlBoolean, + construct: constructYamlBoolean, + predicate: isBoolean, + represent: { + lowercase: function (object) { return object ? 'true' : 'false'; }, + uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, + camelcase: function (object) { return object ? 'True' : 'False'; } + }, + defaultStyle: 'lowercase' +}); + +},{"../type":13}],16:[function(require,module,exports){ +'use strict'; + +var common = require('../common'); +var Type = require('../type'); + +var YAML_FLOAT_PATTERN = new RegExp( + // 2.5e4, 2.5 and integers + '^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + + // .2e4, .2 + // special case, seems not from spec + '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + + // 20:59 + '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' + + // .inf + '|[-+]?\\.(?:inf|Inf|INF)' + + // .nan + '|\\.(?:nan|NaN|NAN))$'); + +function resolveYamlFloat(data) { + if (data === null) return false; + + if (!YAML_FLOAT_PATTERN.test(data) || + // Quick hack to not allow integers end with `_` + // Probably should update regexp & check speed + data[data.length - 1] === '_') { + return false; + } + + return true; +} + +function constructYamlFloat(data) { + var value, sign, base, digits; + + value = data.replace(/_/g, '').toLowerCase(); + sign = value[0] === '-' ? -1 : 1; + digits = []; + + if ('+-'.indexOf(value[0]) >= 0) { + value = value.slice(1); + } + + if (value === '.inf') { + return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; + + } else if (value === '.nan') { + return NaN; + + } else if (value.indexOf(':') >= 0) { + value.split(':').forEach(function (v) { + digits.unshift(parseFloat(v, 10)); + }); + + value = 0.0; + base = 1; + + digits.forEach(function (d) { + value += d * base; + base *= 60; + }); + + return sign * value; + + } + return sign * parseFloat(value, 10); +} + + +var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; + +function representYamlFloat(object, style) { + var res; + + if (isNaN(object)) { + switch (style) { + case 'lowercase': return '.nan'; + case 'uppercase': return '.NAN'; + case 'camelcase': return '.NaN'; + } + } else if (Number.POSITIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '.inf'; + case 'uppercase': return '.INF'; + case 'camelcase': return '.Inf'; + } + } else if (Number.NEGATIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '-.inf'; + case 'uppercase': return '-.INF'; + case 'camelcase': return '-.Inf'; + } + } else if (common.isNegativeZero(object)) { + return '-0.0'; + } + + res = object.toString(10); + + // JS stringifier can build scientific format without dots: 5e-100, + // while YAML requres dot: 5.e-100. Fix it with simple hack + + return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; +} + +function isFloat(object) { + return (Object.prototype.toString.call(object) === '[object Number]') && + (object % 1 !== 0 || common.isNegativeZero(object)); +} + +module.exports = new Type('tag:yaml.org,2002:float', { + kind: 'scalar', + resolve: resolveYamlFloat, + construct: constructYamlFloat, + predicate: isFloat, + represent: representYamlFloat, + defaultStyle: 'lowercase' +}); + +},{"../common":2,"../type":13}],17:[function(require,module,exports){ +'use strict'; + +var common = require('../common'); +var Type = require('../type'); + +function isHexCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || + ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || + ((0x61/* a */ <= c) && (c <= 0x66/* f */)); +} + +function isOctCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); +} + +function isDecCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); +} + +function resolveYamlInteger(data) { + if (data === null) return false; + + var max = data.length, + index = 0, + hasDigits = false, + ch; + + if (!max) return false; + + ch = data[index]; + + // sign + if (ch === '-' || ch === '+') { + ch = data[++index]; + } + + if (ch === '0') { + // 0 + if (index + 1 === max) return true; + ch = data[++index]; + + // base 2, base 8, base 16 + + if (ch === 'b') { + // base 2 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (ch !== '0' && ch !== '1') return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + + if (ch === 'x') { + // base 16 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isHexCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + // base 8 + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isOctCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + // base 10 (except 0) or base 60 + + // value should not start with `_`; + if (ch === '_') return false; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (ch === ':') break; + if (!isDecCode(data.charCodeAt(index))) { + return false; + } + hasDigits = true; + } + + // Should have digits and should not end with `_` + if (!hasDigits || ch === '_') return false; + + // if !base60 - done; + if (ch !== ':') return true; + + // base60 almost not used, no needs to optimize + return /^(:[0-5]?[0-9])+$/.test(data.slice(index)); +} + +function constructYamlInteger(data) { + var value = data, sign = 1, ch, base, digits = []; + + if (value.indexOf('_') !== -1) { + value = value.replace(/_/g, ''); + } + + ch = value[0]; + + if (ch === '-' || ch === '+') { + if (ch === '-') sign = -1; + value = value.slice(1); + ch = value[0]; + } + + if (value === '0') return 0; + + if (ch === '0') { + if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); + if (value[1] === 'x') return sign * parseInt(value, 16); + return sign * parseInt(value, 8); + } + + if (value.indexOf(':') !== -1) { + value.split(':').forEach(function (v) { + digits.unshift(parseInt(v, 10)); + }); + + value = 0; + base = 1; + + digits.forEach(function (d) { + value += (d * base); + base *= 60; + }); + + return sign * value; + + } + + return sign * parseInt(value, 10); +} + +function isInteger(object) { + return (Object.prototype.toString.call(object)) === '[object Number]' && + (object % 1 === 0 && !common.isNegativeZero(object)); +} + +module.exports = new Type('tag:yaml.org,2002:int', { + kind: 'scalar', + resolve: resolveYamlInteger, + construct: constructYamlInteger, + predicate: isInteger, + represent: { + binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, + octal: function (obj) { return obj >= 0 ? '0' + obj.toString(8) : '-0' + obj.toString(8).slice(1); }, + decimal: function (obj) { return obj.toString(10); }, + /* eslint-disable max-len */ + hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } + }, + defaultStyle: 'decimal', + styleAliases: { + binary: [ 2, 'bin' ], + octal: [ 8, 'oct' ], + decimal: [ 10, 'dec' ], + hexadecimal: [ 16, 'hex' ] + } +}); + +},{"../common":2,"../type":13}],18:[function(require,module,exports){ +'use strict'; + +var esprima; + +// Browserified version does not have esprima +// +// 1. For node.js just require module as deps +// 2. For browser try to require mudule via external AMD system. +// If not found - try to fallback to window.esprima. If not +// found too - then fail to parse. +// +try { + // workaround to exclude package from browserify list. + var _require = require; + esprima = _require('esprima'); +} catch (_) { + /* eslint-disable no-redeclare */ + /* global window */ + if (typeof window !== 'undefined') esprima = window.esprima; +} + +var Type = require('../../type'); + +function resolveJavascriptFunction(data) { + if (data === null) return false; + + try { + var source = '(' + data + ')', + ast = esprima.parse(source, { range: true }); + + if (ast.type !== 'Program' || + ast.body.length !== 1 || + ast.body[0].type !== 'ExpressionStatement' || + (ast.body[0].expression.type !== 'ArrowFunctionExpression' && + ast.body[0].expression.type !== 'FunctionExpression')) { + return false; + } + + return true; + } catch (err) { + return false; + } +} + +function constructJavascriptFunction(data) { + /*jslint evil:true*/ + + var source = '(' + data + ')', + ast = esprima.parse(source, { range: true }), + params = [], + body; + + if (ast.type !== 'Program' || + ast.body.length !== 1 || + ast.body[0].type !== 'ExpressionStatement' || + (ast.body[0].expression.type !== 'ArrowFunctionExpression' && + ast.body[0].expression.type !== 'FunctionExpression')) { + throw new Error('Failed to resolve function'); + } + + ast.body[0].expression.params.forEach(function (param) { + params.push(param.name); + }); + + body = ast.body[0].expression.body.range; + + // Esprima's ranges include the first '{' and the last '}' characters on + // function expressions. So cut them out. + if (ast.body[0].expression.body.type === 'BlockStatement') { + /*eslint-disable no-new-func*/ + return new Function(params, source.slice(body[0] + 1, body[1] - 1)); + } + // ES6 arrow functions can omit the BlockStatement. In that case, just return + // the body. + /*eslint-disable no-new-func*/ + return new Function(params, 'return ' + source.slice(body[0], body[1])); +} + +function representJavascriptFunction(object /*, style*/) { + return object.toString(); +} + +function isFunction(object) { + return Object.prototype.toString.call(object) === '[object Function]'; +} + +module.exports = new Type('tag:yaml.org,2002:js/function', { + kind: 'scalar', + resolve: resolveJavascriptFunction, + construct: constructJavascriptFunction, + predicate: isFunction, + represent: representJavascriptFunction +}); + +},{"../../type":13}],19:[function(require,module,exports){ +'use strict'; + +var Type = require('../../type'); + +function resolveJavascriptRegExp(data) { + if (data === null) return false; + if (data.length === 0) return false; + + var regexp = data, + tail = /\/([gim]*)$/.exec(data), + modifiers = ''; + + // if regexp starts with '/' it can have modifiers and must be properly closed + // `/foo/gim` - modifiers tail can be maximum 3 chars + if (regexp[0] === '/') { + if (tail) modifiers = tail[1]; + + if (modifiers.length > 3) return false; + // if expression starts with /, is should be properly terminated + if (regexp[regexp.length - modifiers.length - 1] !== '/') return false; + } + + return true; +} + +function constructJavascriptRegExp(data) { + var regexp = data, + tail = /\/([gim]*)$/.exec(data), + modifiers = ''; + + // `/foo/gim` - tail can be maximum 4 chars + if (regexp[0] === '/') { + if (tail) modifiers = tail[1]; + regexp = regexp.slice(1, regexp.length - modifiers.length - 1); + } + + return new RegExp(regexp, modifiers); +} + +function representJavascriptRegExp(object /*, style*/) { + var result = '/' + object.source + '/'; + + if (object.global) result += 'g'; + if (object.multiline) result += 'm'; + if (object.ignoreCase) result += 'i'; + + return result; +} + +function isRegExp(object) { + return Object.prototype.toString.call(object) === '[object RegExp]'; +} + +module.exports = new Type('tag:yaml.org,2002:js/regexp', { + kind: 'scalar', + resolve: resolveJavascriptRegExp, + construct: constructJavascriptRegExp, + predicate: isRegExp, + represent: representJavascriptRegExp +}); + +},{"../../type":13}],20:[function(require,module,exports){ +'use strict'; + +var Type = require('../../type'); + +function resolveJavascriptUndefined() { + return true; +} + +function constructJavascriptUndefined() { + /*eslint-disable no-undefined*/ + return undefined; +} + +function representJavascriptUndefined() { + return ''; +} + +function isUndefined(object) { + return typeof object === 'undefined'; +} + +module.exports = new Type('tag:yaml.org,2002:js/undefined', { + kind: 'scalar', + resolve: resolveJavascriptUndefined, + construct: constructJavascriptUndefined, + predicate: isUndefined, + represent: representJavascriptUndefined +}); + +},{"../../type":13}],21:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +module.exports = new Type('tag:yaml.org,2002:map', { + kind: 'mapping', + construct: function (data) { return data !== null ? data : {}; } +}); + +},{"../type":13}],22:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +function resolveYamlMerge(data) { + return data === '<<' || data === null; +} + +module.exports = new Type('tag:yaml.org,2002:merge', { + kind: 'scalar', + resolve: resolveYamlMerge +}); + +},{"../type":13}],23:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +function resolveYamlNull(data) { + if (data === null) return true; + + var max = data.length; + + return (max === 1 && data === '~') || + (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); +} + +function constructYamlNull() { + return null; +} + +function isNull(object) { + return object === null; +} + +module.exports = new Type('tag:yaml.org,2002:null', { + kind: 'scalar', + resolve: resolveYamlNull, + construct: constructYamlNull, + predicate: isNull, + represent: { + canonical: function () { return '~'; }, + lowercase: function () { return 'null'; }, + uppercase: function () { return 'NULL'; }, + camelcase: function () { return 'Null'; } + }, + defaultStyle: 'lowercase' +}); + +},{"../type":13}],24:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +var _hasOwnProperty = Object.prototype.hasOwnProperty; +var _toString = Object.prototype.toString; + +function resolveYamlOmap(data) { + if (data === null) return true; + + var objectKeys = [], index, length, pair, pairKey, pairHasKey, + object = data; + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + pairHasKey = false; + + if (_toString.call(pair) !== '[object Object]') return false; + + for (pairKey in pair) { + if (_hasOwnProperty.call(pair, pairKey)) { + if (!pairHasKey) pairHasKey = true; + else return false; + } + } + + if (!pairHasKey) return false; + + if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); + else return false; + } + + return true; +} + +function constructYamlOmap(data) { + return data !== null ? data : []; +} + +module.exports = new Type('tag:yaml.org,2002:omap', { + kind: 'sequence', + resolve: resolveYamlOmap, + construct: constructYamlOmap +}); + +},{"../type":13}],25:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +var _toString = Object.prototype.toString; + +function resolveYamlPairs(data) { + if (data === null) return true; + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + if (_toString.call(pair) !== '[object Object]') return false; + + keys = Object.keys(pair); + + if (keys.length !== 1) return false; + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return true; +} + +function constructYamlPairs(data) { + if (data === null) return []; + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + keys = Object.keys(pair); + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return result; +} + +module.exports = new Type('tag:yaml.org,2002:pairs', { + kind: 'sequence', + resolve: resolveYamlPairs, + construct: constructYamlPairs +}); + +},{"../type":13}],26:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +module.exports = new Type('tag:yaml.org,2002:seq', { + kind: 'sequence', + construct: function (data) { return data !== null ? data : []; } +}); + +},{"../type":13}],27:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +var _hasOwnProperty = Object.prototype.hasOwnProperty; + +function resolveYamlSet(data) { + if (data === null) return true; + + var key, object = data; + + for (key in object) { + if (_hasOwnProperty.call(object, key)) { + if (object[key] !== null) return false; + } + } + + return true; +} + +function constructYamlSet(data) { + return data !== null ? data : {}; +} + +module.exports = new Type('tag:yaml.org,2002:set', { + kind: 'mapping', + resolve: resolveYamlSet, + construct: constructYamlSet +}); + +},{"../type":13}],28:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +module.exports = new Type('tag:yaml.org,2002:str', { + kind: 'scalar', + construct: function (data) { return data !== null ? data : ''; } +}); + +},{"../type":13}],29:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +var YAML_DATE_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9])' + // [2] month + '-([0-9][0-9])$'); // [3] day + +var YAML_TIMESTAMP_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9]?)' + // [2] month + '-([0-9][0-9]?)' + // [3] day + '(?:[Tt]|[ \\t]+)' + // ... + '([0-9][0-9]?)' + // [4] hour + ':([0-9][0-9])' + // [5] minute + ':([0-9][0-9])' + // [6] second + '(?:\\.([0-9]*))?' + // [7] fraction + '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour + '(?::([0-9][0-9]))?))?$'); // [11] tz_minute + +function resolveYamlTimestamp(data) { + if (data === null) return false; + if (YAML_DATE_REGEXP.exec(data) !== null) return true; + if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; + return false; +} + +function constructYamlTimestamp(data) { + var match, year, month, day, hour, minute, second, fraction = 0, + delta = null, tz_hour, tz_minute, date; + + match = YAML_DATE_REGEXP.exec(data); + if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); + + if (match === null) throw new Error('Date resolve error'); + + // match: [1] year [2] month [3] day + + year = +(match[1]); + month = +(match[2]) - 1; // JS month starts with 0 + day = +(match[3]); + + if (!match[4]) { // no hour + return new Date(Date.UTC(year, month, day)); + } + + // match: [4] hour [5] minute [6] second [7] fraction + + hour = +(match[4]); + minute = +(match[5]); + second = +(match[6]); + + if (match[7]) { + fraction = match[7].slice(0, 3); + while (fraction.length < 3) { // milli-seconds + fraction += '0'; + } + fraction = +fraction; + } + + // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute + + if (match[9]) { + tz_hour = +(match[10]); + tz_minute = +(match[11] || 0); + delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds + if (match[9] === '-') delta = -delta; + } + + date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); + + if (delta) date.setTime(date.getTime() - delta); + + return date; +} + +function representYamlTimestamp(object /*, style*/) { + return object.toISOString(); +} + +module.exports = new Type('tag:yaml.org,2002:timestamp', { + kind: 'scalar', + resolve: resolveYamlTimestamp, + construct: constructYamlTimestamp, + instanceOf: Date, + represent: representYamlTimestamp +}); + +},{"../type":13}],"/":[function(require,module,exports){ +'use strict'; + + +var yaml = require('./lib/js-yaml.js'); + + +module.exports = yaml; + +},{"./lib/js-yaml.js":1}]},{},[])("/") +}); diff --git a/scripts/node_modules/js-yaml/dist/js-yaml.min.js b/scripts/node_modules/js-yaml/dist/js-yaml.min.js new file mode 100644 index 000000000..1b6ecc16b --- /dev/null +++ b/scripts/node_modules/js-yaml/dist/js-yaml.min.js @@ -0,0 +1 @@ +/*! js-yaml 3.14.1 https://github.com/nodeca/js-yaml */!function(e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).jsyaml=e()}(function(){return function i(r,o,a){function s(t,e){if(!o[t]){if(!r[t]){var n="function"==typeof require&&require;if(!e&&n)return n(t,!0);if(c)return c(t,!0);throw(n=new Error("Cannot find module '"+t+"'")).code="MODULE_NOT_FOUND",n}n=o[t]={exports:{}},r[t][0].call(n.exports,function(e){return s(r[t][1][e]||e)},n,n.exports,i,r,o,a)}return o[t].exports}for(var c="function"==typeof require&&require,e=0;e=i.flowLevel;switch(V(r,n,i.indent,t,function(e){return function(e,t){for(var n=0,i=e.implicitTypes.length;n"+z(r,i.indent)+J(U(function(t,n){var e,i=/(\n+)([^\n]*)/g,r=function(){var e=-1!==(e=t.indexOf("\n"))?e:t.length;return i.lastIndex=e,Q(t.slice(0,e),n)}(),o="\n"===t[0]||" "===t[0];for(;e=i.exec(t);){var a=e[1],s=e[2];e=" "===s[0],r+=a+(o||e||""===s?"":"\n")+Q(s,n),o=e}return r}(r,t),e));case G:return'"'+function(e){for(var t,n,i,r="",o=0;ot&&o tag resolver accepts not "'+o+'" style');i=r.represent[o](t,o)}e.dump=i}return 1}}function ee(e,t,n,i,r,o){e.tag=null,e.dump=n,X(e,n,!1)||X(e,n,!0);var a=l.call(e.dump);i=i&&(e.flowLevel<0||e.flowLevel>t);var s,c,u="[object Object]"===a||"[object Array]"===a;if(u&&(c=-1!==(s=e.duplicates.indexOf(n))),(null!==e.tag&&"?"!==e.tag||c||2!==e.indent&&0 "+e.dump)}return 1}function te(e,t){var n,i,r=[],o=[];for(!function e(t,n,i){var r,o,a;if(null!==t&&"object"==typeof t)if(-1!==(o=n.indexOf(t)))-1===i.indexOf(o)&&i.push(o);else if(n.push(t),Array.isArray(t))for(o=0,a=t.length;o>10),56320+(c-65536&1023)),e.position++}else N(e,"unknown escape sequence");n=i=e.position}else S(u)?(L(e,n,i,!0),B(e,Y(e,!1,t)),n=i=e.position):e.position===e.lineStart&&R(e)?N(e,"unexpected end of the document within a double quoted scalar"):(e.position++,i=e.position)}N(e,"unexpected end of the stream within a double quoted scalar")}}function K(e,t){var n,i,r=e.tag,o=e.anchor,a=[],s=!1;for(null!==e.anchor&&(e.anchorMap[e.anchor]=a),i=e.input.charCodeAt(e.position);0!==i&&45===i&&O(e.input.charCodeAt(e.position+1));)if(s=!0,e.position++,Y(e,!0,-1)&&e.lineIndent<=t)a.push(null),i=e.input.charCodeAt(e.position);else if(n=e.line,P(e,t,x,!1,!0),a.push(e.result),Y(e,!0,-1),i=e.input.charCodeAt(e.position),(e.line===n||e.lineIndent>t)&&0!==i)N(e,"bad indentation of a sequence entry");else if(e.lineIndentt?p=1:e.lineIndent===t?p=0:e.lineIndentt?p=1:e.lineIndent===t?p=0:e.lineIndentt)&&(P(e,t,A,!0,r)&&(m?d=e.result:h=e.result),m||(U(e,l,p,f,d,h,o,a),f=d=h=null),Y(e,!0,-1),s=e.input.charCodeAt(e.position)),e.lineIndent>t&&0!==s)N(e,"bad indentation of a mapping entry");else if(e.lineIndentc&&(c=e.lineIndent),S(p))u++;else{if(e.lineIndent=t){a=!0,f=e.input.charCodeAt(e.position);continue}e.position=o,e.line=s,e.lineStart=c,e.lineIndent=u;break}}a&&(L(e,r,o,!1),B(e,e.line-s),r=o=e.position,a=!1),I(f)||(o=e.position+1),f=e.input.charCodeAt(++e.position)}if(L(e,r,o,!1),e.result)return 1;e.kind=l,e.result=p}}(e,i,g===n)&&(d=!0,null===e.tag&&(e.tag="?")):(d=!0,null===e.tag&&null===e.anchor||N(e,"alias node should not have any properties")),null!==e.anchor&&(e.anchorMap[e.anchor]=e.result)):0===p&&(d=s&&K(e,r))),null!==e.tag&&"!"!==e.tag)if("?"===e.tag){for(null!==e.result&&"scalar"!==e.kind&&N(e,'unacceptable node kind for ! tag; it should be "scalar", not "'+e.kind+'"'),c=0,u=e.implicitTypes.length;c tag; it should be "'+l.kind+'", not "'+e.kind+'"'),l.resolve(e.result)?(e.result=l.construct(e.result),null!==e.anchor&&(e.anchorMap[e.anchor]=e.result)):N(e,"cannot resolve a node with !<"+e.tag+"> explicit tag")):N(e,"unknown tag !<"+e.tag+">");return null!==e.listener&&e.listener("close",e),null!==e.tag||null!==e.anchor||d}function $(e,t){t=t||{},0!==(e=String(e)).length&&(10!==e.charCodeAt(e.length-1)&&13!==e.charCodeAt(e.length-1)&&(e+="\n"),65279===e.charCodeAt(0)&&(e=e.slice(1)));var n=new F(e,t),e=e.indexOf("\0");for(-1!==e&&(n.position=e,N(n,"null byte is not allowed in input")),n.input+="\0";32===n.input.charCodeAt(n.position);)n.lineIndent+=1,n.position+=1;for(;n.positiont/2-1){n=" ... ",i+=5;break}for(r="",o=this.position;ot/2-1){r=" ... ",o-=5;break}return a=this.buffer.slice(i,o),s.repeat(" ",e)+n+a+r+"\n"+s.repeat(" ",e+this.position-i+n.length)+"^"},i.prototype.toString=function(e){var t="";return this.name&&(t+='in "'+this.name+'" '),t+="at line "+(this.line+1)+", column "+(this.column+1),e||(e=this.getSnippet())&&(t+=":\n"+e),t},t.exports=i},{"./common":2}],7:[function(e,t,n){"use strict";var r=e("./common"),o=e("./exception"),a=e("./type");function s(e,t,i){var r=[];return e.include.forEach(function(e){i=s(e,t,i)}),e[t].forEach(function(n){i.forEach(function(e,t){e.tag===n.tag&&e.kind===n.kind&&r.push(t)}),i.push(n)}),i.filter(function(e,t){return-1===r.indexOf(t)})}function c(e){this.include=e.include||[],this.implicit=e.implicit||[],this.explicit=e.explicit||[],this.implicit.forEach(function(e){if(e.loadKind&&"scalar"!==e.loadKind)throw new o("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.")}),this.compiledImplicit=s(this,"implicit",[]),this.compiledExplicit=s(this,"explicit",[]),this.compiledTypeMap=function(){var e,t,n={scalar:{},sequence:{},mapping:{},fallback:{}};function i(e){n[e.kind][e.tag]=n.fallback[e.tag]=e}for(e=0,t=arguments.length;e>16&255),o.push(r>>8&255),o.push(255&r)),r=r<<6|i.indexOf(t.charAt(a));return 0==(e=n%4*6)?(o.push(r>>16&255),o.push(r>>8&255),o.push(255&r)):18==e?(o.push(r>>10&255),o.push(r>>2&255)):12==e&&o.push(r>>4&255),s?s.from?s.from(o):new s(o):o},predicate:function(e){return s&&s.isBuffer(e)},represent:function(e){for(var t,n="",i=0,r=e.length,o=c,a=0;a>18&63],n+=o[i>>12&63],n+=o[i>>6&63],n+=o[63&i]),i=(i<<8)+e[a];return 0==(t=r%3)?(n+=o[i>>18&63],n+=o[i>>12&63],n+=o[i>>6&63],n+=o[63&i]):2==t?(n+=o[i>>10&63],n+=o[i>>4&63],n+=o[i<<2&63],n+=o[64]):1==t&&(n+=o[i>>2&63],n+=o[i<<4&63],n+=o[64],n+=o[64]),n}})},{"../type":13}],15:[function(e,t,n){"use strict";e=e("../type");t.exports=new e("tag:yaml.org,2002:bool",{kind:"scalar",resolve:function(e){if(null===e)return!1;var t=e.length;return 4===t&&("true"===e||"True"===e||"TRUE"===e)||5===t&&("false"===e||"False"===e||"FALSE"===e)},construct:function(e){return"true"===e||"True"===e||"TRUE"===e},predicate:function(e){return"[object Boolean]"===Object.prototype.toString.call(e)},represent:{lowercase:function(e){return e?"true":"false"},uppercase:function(e){return e?"TRUE":"FALSE"},camelcase:function(e){return e?"True":"False"}},defaultStyle:"lowercase"})},{"../type":13}],16:[function(e,t,n){"use strict";var i=e("../common"),e=e("../type"),r=new RegExp("^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");var o=/^[-+]?[0-9]+e/;t.exports=new e("tag:yaml.org,2002:float",{kind:"scalar",resolve:function(e){return null!==e&&!(!r.test(e)||"_"===e[e.length-1])},construct:function(e){var t,n=e.replace(/_/g,"").toLowerCase(),e="-"===n[0]?-1:1,i=[];return 0<="+-".indexOf(n[0])&&(n=n.slice(1)),".inf"===n?1==e?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:".nan"===n?NaN:0<=n.indexOf(":")?(n.split(":").forEach(function(e){i.unshift(parseFloat(e,10))}),n=0,t=1,i.forEach(function(e){n+=e*t,t*=60}),e*n):e*parseFloat(n,10)},predicate:function(e){return"[object Number]"===Object.prototype.toString.call(e)&&(e%1!=0||i.isNegativeZero(e))},represent:function(e,t){if(isNaN(e))switch(t){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===e)switch(t){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===e)switch(t){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(i.isNegativeZero(e))return"-0.0";return e=e.toString(10),o.test(e)?e.replace("e",".e"):e},defaultStyle:"lowercase"})},{"../common":2,"../type":13}],17:[function(e,t,n){"use strict";var i=e("../common"),e=e("../type");t.exports=new e("tag:yaml.org,2002:int",{kind:"scalar",resolve:function(e){if(null===e)return!1;var t,n,i,r,o=e.length,a=0,s=!1;if(!o)return!1;if("-"!==(t=e[a])&&"+"!==t||(t=e[++a]),"0"===t){if(a+1===o)return!0;if("b"===(t=e[++a])){for(a++;a */ +var CHAR_QUESTION = 0x3F; /* ? */ +var CHAR_COMMERCIAL_AT = 0x40; /* @ */ +var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ +var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ +var CHAR_GRAVE_ACCENT = 0x60; /* ` */ +var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ +var CHAR_VERTICAL_LINE = 0x7C; /* | */ +var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ + +var ESCAPE_SEQUENCES = {}; + +ESCAPE_SEQUENCES[0x00] = '\\0'; +ESCAPE_SEQUENCES[0x07] = '\\a'; +ESCAPE_SEQUENCES[0x08] = '\\b'; +ESCAPE_SEQUENCES[0x09] = '\\t'; +ESCAPE_SEQUENCES[0x0A] = '\\n'; +ESCAPE_SEQUENCES[0x0B] = '\\v'; +ESCAPE_SEQUENCES[0x0C] = '\\f'; +ESCAPE_SEQUENCES[0x0D] = '\\r'; +ESCAPE_SEQUENCES[0x1B] = '\\e'; +ESCAPE_SEQUENCES[0x22] = '\\"'; +ESCAPE_SEQUENCES[0x5C] = '\\\\'; +ESCAPE_SEQUENCES[0x85] = '\\N'; +ESCAPE_SEQUENCES[0xA0] = '\\_'; +ESCAPE_SEQUENCES[0x2028] = '\\L'; +ESCAPE_SEQUENCES[0x2029] = '\\P'; + +var DEPRECATED_BOOLEANS_SYNTAX = [ + 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', + 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' +]; + +function compileStyleMap(schema, map) { + var result, keys, index, length, tag, style, type; + + if (map === null) return {}; + + result = {}; + keys = Object.keys(map); + + for (index = 0, length = keys.length; index < length; index += 1) { + tag = keys[index]; + style = String(map[tag]); + + if (tag.slice(0, 2) === '!!') { + tag = 'tag:yaml.org,2002:' + tag.slice(2); + } + type = schema.compiledTypeMap['fallback'][tag]; + + if (type && _hasOwnProperty.call(type.styleAliases, style)) { + style = type.styleAliases[style]; + } + + result[tag] = style; + } + + return result; +} + +function encodeHex(character) { + var string, handle, length; + + string = character.toString(16).toUpperCase(); + + if (character <= 0xFF) { + handle = 'x'; + length = 2; + } else if (character <= 0xFFFF) { + handle = 'u'; + length = 4; + } else if (character <= 0xFFFFFFFF) { + handle = 'U'; + length = 8; + } else { + throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF'); + } + + return '\\' + handle + common.repeat('0', length - string.length) + string; +} + +function State(options) { + this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; + this.indent = Math.max(1, (options['indent'] || 2)); + this.noArrayIndent = options['noArrayIndent'] || false; + this.skipInvalid = options['skipInvalid'] || false; + this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); + this.styleMap = compileStyleMap(this.schema, options['styles'] || null); + this.sortKeys = options['sortKeys'] || false; + this.lineWidth = options['lineWidth'] || 80; + this.noRefs = options['noRefs'] || false; + this.noCompatMode = options['noCompatMode'] || false; + this.condenseFlow = options['condenseFlow'] || false; + + this.implicitTypes = this.schema.compiledImplicit; + this.explicitTypes = this.schema.compiledExplicit; + + this.tag = null; + this.result = ''; + + this.duplicates = []; + this.usedDuplicates = null; +} + +// Indents every line in a string. Empty lines (\n only) are not indented. +function indentString(string, spaces) { + var ind = common.repeat(' ', spaces), + position = 0, + next = -1, + result = '', + line, + length = string.length; + + while (position < length) { + next = string.indexOf('\n', position); + if (next === -1) { + line = string.slice(position); + position = length; + } else { + line = string.slice(position, next + 1); + position = next + 1; + } + + if (line.length && line !== '\n') result += ind; + + result += line; + } + + return result; +} + +function generateNextLine(state, level) { + return '\n' + common.repeat(' ', state.indent * level); +} + +function testImplicitResolving(state, str) { + var index, length, type; + + for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { + type = state.implicitTypes[index]; + + if (type.resolve(str)) { + return true; + } + } + + return false; +} + +// [33] s-white ::= s-space | s-tab +function isWhitespace(c) { + return c === CHAR_SPACE || c === CHAR_TAB; +} + +// Returns true if the character can be printed without escaping. +// From YAML 1.2: "any allowed characters known to be non-printable +// should also be escaped. [However,] This isn’t mandatory" +// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. +function isPrintable(c) { + return (0x00020 <= c && c <= 0x00007E) + || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) + || ((0x0E000 <= c && c <= 0x00FFFD) && c !== 0xFEFF /* BOM */) + || (0x10000 <= c && c <= 0x10FFFF); +} + +// [34] ns-char ::= nb-char - s-white +// [27] nb-char ::= c-printable - b-char - c-byte-order-mark +// [26] b-char ::= b-line-feed | b-carriage-return +// [24] b-line-feed ::= #xA /* LF */ +// [25] b-carriage-return ::= #xD /* CR */ +// [3] c-byte-order-mark ::= #xFEFF +function isNsChar(c) { + return isPrintable(c) && !isWhitespace(c) + // byte-order-mark + && c !== 0xFEFF + // b-char + && c !== CHAR_CARRIAGE_RETURN + && c !== CHAR_LINE_FEED; +} + +// Simplified test for values allowed after the first character in plain style. +function isPlainSafe(c, prev) { + // Uses a subset of nb-char - c-flow-indicator - ":" - "#" + // where nb-char ::= c-printable - b-char - c-byte-order-mark. + return isPrintable(c) && c !== 0xFEFF + // - c-flow-indicator + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + // - ":" - "#" + // /* An ns-char preceding */ "#" + && c !== CHAR_COLON + && ((c !== CHAR_SHARP) || (prev && isNsChar(prev))); +} + +// Simplified test for values allowed as the first character in plain style. +function isPlainSafeFirst(c) { + // Uses a subset of ns-char - c-indicator + // where ns-char = nb-char - s-white. + return isPrintable(c) && c !== 0xFEFF + && !isWhitespace(c) // - s-white + // - (c-indicator ::= + // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” + && c !== CHAR_MINUS + && c !== CHAR_QUESTION + && c !== CHAR_COLON + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” + && c !== CHAR_SHARP + && c !== CHAR_AMPERSAND + && c !== CHAR_ASTERISK + && c !== CHAR_EXCLAMATION + && c !== CHAR_VERTICAL_LINE + && c !== CHAR_EQUALS + && c !== CHAR_GREATER_THAN + && c !== CHAR_SINGLE_QUOTE + && c !== CHAR_DOUBLE_QUOTE + // | “%” | “@” | “`”) + && c !== CHAR_PERCENT + && c !== CHAR_COMMERCIAL_AT + && c !== CHAR_GRAVE_ACCENT; +} + +// Determines whether block indentation indicator is required. +function needIndentIndicator(string) { + var leadingSpaceRe = /^\n* /; + return leadingSpaceRe.test(string); +} + +var STYLE_PLAIN = 1, + STYLE_SINGLE = 2, + STYLE_LITERAL = 3, + STYLE_FOLDED = 4, + STYLE_DOUBLE = 5; + +// Determines which scalar styles are possible and returns the preferred style. +// lineWidth = -1 => no limit. +// Pre-conditions: str.length > 0. +// Post-conditions: +// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. +// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). +// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). +function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) { + var i; + var char, prev_char; + var hasLineBreak = false; + var hasFoldableLine = false; // only checked if shouldTrackWidth + var shouldTrackWidth = lineWidth !== -1; + var previousLineBreak = -1; // count the first line correctly + var plain = isPlainSafeFirst(string.charCodeAt(0)) + && !isWhitespace(string.charCodeAt(string.length - 1)); + + if (singleLineOnly) { + // Case: no block styles. + // Check for disallowed characters to rule out plain and single. + for (i = 0; i < string.length; i++) { + char = string.charCodeAt(i); + if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + prev_char = i > 0 ? string.charCodeAt(i - 1) : null; + plain = plain && isPlainSafe(char, prev_char); + } + } else { + // Case: block styles permitted. + for (i = 0; i < string.length; i++) { + char = string.charCodeAt(i); + if (char === CHAR_LINE_FEED) { + hasLineBreak = true; + // Check if any line can be folded. + if (shouldTrackWidth) { + hasFoldableLine = hasFoldableLine || + // Foldable line = too long, and not more-indented. + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' '); + previousLineBreak = i; + } + } else if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + prev_char = i > 0 ? string.charCodeAt(i - 1) : null; + plain = plain && isPlainSafe(char, prev_char); + } + // in case the end is missing a \n + hasFoldableLine = hasFoldableLine || (shouldTrackWidth && + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' ')); + } + // Although every style can represent \n without escaping, prefer block styles + // for multiline, since they're more readable and they don't add empty lines. + // Also prefer folding a super-long line. + if (!hasLineBreak && !hasFoldableLine) { + // Strings interpretable as another type have to be quoted; + // e.g. the string 'true' vs. the boolean true. + return plain && !testAmbiguousType(string) + ? STYLE_PLAIN : STYLE_SINGLE; + } + // Edge case: block indentation indicator can only have one digit. + if (indentPerLevel > 9 && needIndentIndicator(string)) { + return STYLE_DOUBLE; + } + // At this point we know block styles are valid. + // Prefer literal style unless we want to fold. + return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; +} + +// Note: line breaking/folding is implemented for only the folded style. +// NB. We drop the last trailing newline (if any) of a returned block scalar +// since the dumper adds its own newline. This always works: +// • No ending newline => unaffected; already using strip "-" chomping. +// • Ending newline => removed then restored. +// Importantly, this keeps the "+" chomp indicator from gaining an extra line. +function writeScalar(state, string, level, iskey) { + state.dump = (function () { + if (string.length === 0) { + return "''"; + } + if (!state.noCompatMode && + DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) { + return "'" + string + "'"; + } + + var indent = state.indent * Math.max(1, level); // no 0-indent scalars + // As indentation gets deeper, let the width decrease monotonically + // to the lower bound min(state.lineWidth, 40). + // Note that this implies + // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. + // state.lineWidth > 40 + state.indent: width decreases until the lower bound. + // This behaves better than a constant minimum width which disallows narrower options, + // or an indent threshold which causes the width to suddenly increase. + var lineWidth = state.lineWidth === -1 + ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); + + // Without knowing if keys are implicit/explicit, assume implicit for safety. + var singleLineOnly = iskey + // No block styles in flow mode. + || (state.flowLevel > -1 && level >= state.flowLevel); + function testAmbiguity(string) { + return testImplicitResolving(state, string); + } + + switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) { + case STYLE_PLAIN: + return string; + case STYLE_SINGLE: + return "'" + string.replace(/'/g, "''") + "'"; + case STYLE_LITERAL: + return '|' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(string, indent)); + case STYLE_FOLDED: + return '>' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); + case STYLE_DOUBLE: + return '"' + escapeString(string, lineWidth) + '"'; + default: + throw new YAMLException('impossible error: invalid scalar style'); + } + }()); +} + +// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. +function blockHeader(string, indentPerLevel) { + var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; + + // note the special case: the string '\n' counts as a "trailing" empty line. + var clip = string[string.length - 1] === '\n'; + var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); + var chomp = keep ? '+' : (clip ? '' : '-'); + + return indentIndicator + chomp + '\n'; +} + +// (See the note for writeScalar.) +function dropEndingNewline(string) { + return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; +} + +// Note: a long line without a suitable break point will exceed the width limit. +// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. +function foldString(string, width) { + // In folded style, $k$ consecutive newlines output as $k+1$ newlines— + // unless they're before or after a more-indented line, or at the very + // beginning or end, in which case $k$ maps to $k$. + // Therefore, parse each chunk as newline(s) followed by a content line. + var lineRe = /(\n+)([^\n]*)/g; + + // first line (possibly an empty line) + var result = (function () { + var nextLF = string.indexOf('\n'); + nextLF = nextLF !== -1 ? nextLF : string.length; + lineRe.lastIndex = nextLF; + return foldLine(string.slice(0, nextLF), width); + }()); + // If we haven't reached the first content line yet, don't add an extra \n. + var prevMoreIndented = string[0] === '\n' || string[0] === ' '; + var moreIndented; + + // rest of the lines + var match; + while ((match = lineRe.exec(string))) { + var prefix = match[1], line = match[2]; + moreIndented = (line[0] === ' '); + result += prefix + + (!prevMoreIndented && !moreIndented && line !== '' + ? '\n' : '') + + foldLine(line, width); + prevMoreIndented = moreIndented; + } + + return result; +} + +// Greedy line breaking. +// Picks the longest line under the limit each time, +// otherwise settles for the shortest line over the limit. +// NB. More-indented lines *cannot* be folded, as that would add an extra \n. +function foldLine(line, width) { + if (line === '' || line[0] === ' ') return line; + + // Since a more-indented line adds a \n, breaks can't be followed by a space. + var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. + var match; + // start is an inclusive index. end, curr, and next are exclusive. + var start = 0, end, curr = 0, next = 0; + var result = ''; + + // Invariants: 0 <= start <= length-1. + // 0 <= curr <= next <= max(0, length-2). curr - start <= width. + // Inside the loop: + // A match implies length >= 2, so curr and next are <= length-2. + while ((match = breakRe.exec(line))) { + next = match.index; + // maintain invariant: curr - start <= width + if (next - start > width) { + end = (curr > start) ? curr : next; // derive end <= length-2 + result += '\n' + line.slice(start, end); + // skip the space that was output as \n + start = end + 1; // derive start <= length-1 + } + curr = next; + } + + // By the invariants, start <= length-1, so there is something left over. + // It is either the whole string or a part starting from non-whitespace. + result += '\n'; + // Insert a break if the remainder is too long and there is a break available. + if (line.length - start > width && curr > start) { + result += line.slice(start, curr) + '\n' + line.slice(curr + 1); + } else { + result += line.slice(start); + } + + return result.slice(1); // drop extra \n joiner +} + +// Escapes a double-quoted string. +function escapeString(string) { + var result = ''; + var char, nextChar; + var escapeSeq; + + for (var i = 0; i < string.length; i++) { + char = string.charCodeAt(i); + // Check for surrogate pairs (reference Unicode 3.0 section "3.7 Surrogates"). + if (char >= 0xD800 && char <= 0xDBFF/* high surrogate */) { + nextChar = string.charCodeAt(i + 1); + if (nextChar >= 0xDC00 && nextChar <= 0xDFFF/* low surrogate */) { + // Combine the surrogate pair and store it escaped. + result += encodeHex((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000); + // Advance index one extra since we already used that char here. + i++; continue; + } + } + escapeSeq = ESCAPE_SEQUENCES[char]; + result += !escapeSeq && isPrintable(char) + ? string[i] + : escapeSeq || encodeHex(char); + } + + return result; +} + +function writeFlowSequence(state, level, object) { + var _result = '', + _tag = state.tag, + index, + length; + + for (index = 0, length = object.length; index < length; index += 1) { + // Write only valid elements. + if (writeNode(state, level, object[index], false, false)) { + if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : ''); + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = '[' + _result + ']'; +} + +function writeBlockSequence(state, level, object, compact) { + var _result = '', + _tag = state.tag, + index, + length; + + for (index = 0, length = object.length; index < length; index += 1) { + // Write only valid elements. + if (writeNode(state, level + 1, object[index], true, true)) { + if (!compact || index !== 0) { + _result += generateNextLine(state, level); + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + _result += '-'; + } else { + _result += '- '; + } + + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = _result || '[]'; // Empty sequence if no valid values. +} + +function writeFlowMapping(state, level, object) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + pairBuffer; + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + + pairBuffer = ''; + if (index !== 0) pairBuffer += ', '; + + if (state.condenseFlow) pairBuffer += '"'; + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (!writeNode(state, level, objectKey, false, false)) { + continue; // Skip this pair because of invalid key; + } + + if (state.dump.length > 1024) pairBuffer += '? '; + + pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); + + if (!writeNode(state, level, objectValue, false, false)) { + continue; // Skip this pair because of invalid value. + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = '{' + _result + '}'; +} + +function writeBlockMapping(state, level, object, compact) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + explicitPair, + pairBuffer; + + // Allow sorting keys so that the output file is deterministic + if (state.sortKeys === true) { + // Default sorting + objectKeyList.sort(); + } else if (typeof state.sortKeys === 'function') { + // Custom sort function + objectKeyList.sort(state.sortKeys); + } else if (state.sortKeys) { + // Something is wrong + throw new YAMLException('sortKeys must be a boolean or a function'); + } + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + pairBuffer = ''; + + if (!compact || index !== 0) { + pairBuffer += generateNextLine(state, level); + } + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (!writeNode(state, level + 1, objectKey, true, true, true)) { + continue; // Skip this pair because of invalid key. + } + + explicitPair = (state.tag !== null && state.tag !== '?') || + (state.dump && state.dump.length > 1024); + + if (explicitPair) { + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += '?'; + } else { + pairBuffer += '? '; + } + } + + pairBuffer += state.dump; + + if (explicitPair) { + pairBuffer += generateNextLine(state, level); + } + + if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { + continue; // Skip this pair because of invalid value. + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += ':'; + } else { + pairBuffer += ': '; + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = _result || '{}'; // Empty mapping if no valid pairs. +} + +function detectType(state, object, explicit) { + var _result, typeList, index, length, type, style; + + typeList = explicit ? state.explicitTypes : state.implicitTypes; + + for (index = 0, length = typeList.length; index < length; index += 1) { + type = typeList[index]; + + if ((type.instanceOf || type.predicate) && + (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && + (!type.predicate || type.predicate(object))) { + + state.tag = explicit ? type.tag : '?'; + + if (type.represent) { + style = state.styleMap[type.tag] || type.defaultStyle; + + if (_toString.call(type.represent) === '[object Function]') { + _result = type.represent(object, style); + } else if (_hasOwnProperty.call(type.represent, style)) { + _result = type.represent[style](object, style); + } else { + throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); + } + + state.dump = _result; + } + + return true; + } + } + + return false; +} + +// Serializes `object` and writes it to global `result`. +// Returns true on success, or false on invalid object. +// +function writeNode(state, level, object, block, compact, iskey) { + state.tag = null; + state.dump = object; + + if (!detectType(state, object, false)) { + detectType(state, object, true); + } + + var type = _toString.call(state.dump); + + if (block) { + block = (state.flowLevel < 0 || state.flowLevel > level); + } + + var objectOrArray = type === '[object Object]' || type === '[object Array]', + duplicateIndex, + duplicate; + + if (objectOrArray) { + duplicateIndex = state.duplicates.indexOf(object); + duplicate = duplicateIndex !== -1; + } + + if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { + compact = false; + } + + if (duplicate && state.usedDuplicates[duplicateIndex]) { + state.dump = '*ref_' + duplicateIndex; + } else { + if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { + state.usedDuplicates[duplicateIndex] = true; + } + if (type === '[object Object]') { + if (block && (Object.keys(state.dump).length !== 0)) { + writeBlockMapping(state, level, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowMapping(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object Array]') { + var arrayLevel = (state.noArrayIndent && (level > 0)) ? level - 1 : level; + if (block && (state.dump.length !== 0)) { + writeBlockSequence(state, arrayLevel, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowSequence(state, arrayLevel, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object String]') { + if (state.tag !== '?') { + writeScalar(state, state.dump, level, iskey); + } + } else { + if (state.skipInvalid) return false; + throw new YAMLException('unacceptable kind of an object to dump ' + type); + } + + if (state.tag !== null && state.tag !== '?') { + state.dump = '!<' + state.tag + '> ' + state.dump; + } + } + + return true; +} + +function getDuplicateReferences(object, state) { + var objects = [], + duplicatesIndexes = [], + index, + length; + + inspectNode(object, objects, duplicatesIndexes); + + for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { + state.duplicates.push(objects[duplicatesIndexes[index]]); + } + state.usedDuplicates = new Array(length); +} + +function inspectNode(object, objects, duplicatesIndexes) { + var objectKeyList, + index, + length; + + if (object !== null && typeof object === 'object') { + index = objects.indexOf(object); + if (index !== -1) { + if (duplicatesIndexes.indexOf(index) === -1) { + duplicatesIndexes.push(index); + } + } else { + objects.push(object); + + if (Array.isArray(object)) { + for (index = 0, length = object.length; index < length; index += 1) { + inspectNode(object[index], objects, duplicatesIndexes); + } + } else { + objectKeyList = Object.keys(object); + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); + } + } + } + } +} + +function dump(input, options) { + options = options || {}; + + var state = new State(options); + + if (!state.noRefs) getDuplicateReferences(input, state); + + if (writeNode(state, 0, input, true, true)) return state.dump + '\n'; + + return ''; +} + +function safeDump(input, options) { + return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +} + +module.exports.dump = dump; +module.exports.safeDump = safeDump; diff --git a/scripts/node_modules/js-yaml/lib/js-yaml/exception.js b/scripts/node_modules/js-yaml/lib/js-yaml/exception.js new file mode 100644 index 000000000..b744a1ee4 --- /dev/null +++ b/scripts/node_modules/js-yaml/lib/js-yaml/exception.js @@ -0,0 +1,43 @@ +// YAML error class. http://stackoverflow.com/questions/8458984 +// +'use strict'; + +function YAMLException(reason, mark) { + // Super constructor + Error.call(this); + + this.name = 'YAMLException'; + this.reason = reason; + this.mark = mark; + this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : ''); + + // Include stack trace in error object + if (Error.captureStackTrace) { + // Chrome and NodeJS + Error.captureStackTrace(this, this.constructor); + } else { + // FF, IE 10+ and Safari 6+. Fallback for others + this.stack = (new Error()).stack || ''; + } +} + + +// Inherit from Error +YAMLException.prototype = Object.create(Error.prototype); +YAMLException.prototype.constructor = YAMLException; + + +YAMLException.prototype.toString = function toString(compact) { + var result = this.name + ': '; + + result += this.reason || '(unknown reason)'; + + if (!compact && this.mark) { + result += ' ' + this.mark.toString(); + } + + return result; +}; + + +module.exports = YAMLException; diff --git a/scripts/node_modules/js-yaml/lib/js-yaml/loader.js b/scripts/node_modules/js-yaml/lib/js-yaml/loader.js new file mode 100644 index 000000000..d7484a591 --- /dev/null +++ b/scripts/node_modules/js-yaml/lib/js-yaml/loader.js @@ -0,0 +1,1644 @@ +'use strict'; + +/*eslint-disable max-len,no-use-before-define*/ + +var common = require('./common'); +var YAMLException = require('./exception'); +var Mark = require('./mark'); +var DEFAULT_SAFE_SCHEMA = require('./schema/default_safe'); +var DEFAULT_FULL_SCHEMA = require('./schema/default_full'); + + +var _hasOwnProperty = Object.prototype.hasOwnProperty; + + +var CONTEXT_FLOW_IN = 1; +var CONTEXT_FLOW_OUT = 2; +var CONTEXT_BLOCK_IN = 3; +var CONTEXT_BLOCK_OUT = 4; + + +var CHOMPING_CLIP = 1; +var CHOMPING_STRIP = 2; +var CHOMPING_KEEP = 3; + + +var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; +var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; +var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; +var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; +var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; + + +function _class(obj) { return Object.prototype.toString.call(obj); } + +function is_EOL(c) { + return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); +} + +function is_WHITE_SPACE(c) { + return (c === 0x09/* Tab */) || (c === 0x20/* Space */); +} + +function is_WS_OR_EOL(c) { + return (c === 0x09/* Tab */) || + (c === 0x20/* Space */) || + (c === 0x0A/* LF */) || + (c === 0x0D/* CR */); +} + +function is_FLOW_INDICATOR(c) { + return c === 0x2C/* , */ || + c === 0x5B/* [ */ || + c === 0x5D/* ] */ || + c === 0x7B/* { */ || + c === 0x7D/* } */; +} + +function fromHexCode(c) { + var lc; + + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + /*eslint-disable no-bitwise*/ + lc = c | 0x20; + + if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { + return lc - 0x61 + 10; + } + + return -1; +} + +function escapedHexLen(c) { + if (c === 0x78/* x */) { return 2; } + if (c === 0x75/* u */) { return 4; } + if (c === 0x55/* U */) { return 8; } + return 0; +} + +function fromDecimalCode(c) { + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + return -1; +} + +function simpleEscapeSequence(c) { + /* eslint-disable indent */ + return (c === 0x30/* 0 */) ? '\x00' : + (c === 0x61/* a */) ? '\x07' : + (c === 0x62/* b */) ? '\x08' : + (c === 0x74/* t */) ? '\x09' : + (c === 0x09/* Tab */) ? '\x09' : + (c === 0x6E/* n */) ? '\x0A' : + (c === 0x76/* v */) ? '\x0B' : + (c === 0x66/* f */) ? '\x0C' : + (c === 0x72/* r */) ? '\x0D' : + (c === 0x65/* e */) ? '\x1B' : + (c === 0x20/* Space */) ? ' ' : + (c === 0x22/* " */) ? '\x22' : + (c === 0x2F/* / */) ? '/' : + (c === 0x5C/* \ */) ? '\x5C' : + (c === 0x4E/* N */) ? '\x85' : + (c === 0x5F/* _ */) ? '\xA0' : + (c === 0x4C/* L */) ? '\u2028' : + (c === 0x50/* P */) ? '\u2029' : ''; +} + +function charFromCodepoint(c) { + if (c <= 0xFFFF) { + return String.fromCharCode(c); + } + // Encode UTF-16 surrogate pair + // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF + return String.fromCharCode( + ((c - 0x010000) >> 10) + 0xD800, + ((c - 0x010000) & 0x03FF) + 0xDC00 + ); +} + +var simpleEscapeCheck = new Array(256); // integer, for fast access +var simpleEscapeMap = new Array(256); +for (var i = 0; i < 256; i++) { + simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; + simpleEscapeMap[i] = simpleEscapeSequence(i); +} + + +function State(input, options) { + this.input = input; + + this.filename = options['filename'] || null; + this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; + this.onWarning = options['onWarning'] || null; + this.legacy = options['legacy'] || false; + this.json = options['json'] || false; + this.listener = options['listener'] || null; + + this.implicitTypes = this.schema.compiledImplicit; + this.typeMap = this.schema.compiledTypeMap; + + this.length = input.length; + this.position = 0; + this.line = 0; + this.lineStart = 0; + this.lineIndent = 0; + + this.documents = []; + + /* + this.version; + this.checkLineBreaks; + this.tagMap; + this.anchorMap; + this.tag; + this.anchor; + this.kind; + this.result;*/ + +} + + +function generateError(state, message) { + return new YAMLException( + message, + new Mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart))); +} + +function throwError(state, message) { + throw generateError(state, message); +} + +function throwWarning(state, message) { + if (state.onWarning) { + state.onWarning.call(null, generateError(state, message)); + } +} + + +var directiveHandlers = { + + YAML: function handleYamlDirective(state, name, args) { + + var match, major, minor; + + if (state.version !== null) { + throwError(state, 'duplication of %YAML directive'); + } + + if (args.length !== 1) { + throwError(state, 'YAML directive accepts exactly one argument'); + } + + match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); + + if (match === null) { + throwError(state, 'ill-formed argument of the YAML directive'); + } + + major = parseInt(match[1], 10); + minor = parseInt(match[2], 10); + + if (major !== 1) { + throwError(state, 'unacceptable YAML version of the document'); + } + + state.version = args[0]; + state.checkLineBreaks = (minor < 2); + + if (minor !== 1 && minor !== 2) { + throwWarning(state, 'unsupported YAML version of the document'); + } + }, + + TAG: function handleTagDirective(state, name, args) { + + var handle, prefix; + + if (args.length !== 2) { + throwError(state, 'TAG directive accepts exactly two arguments'); + } + + handle = args[0]; + prefix = args[1]; + + if (!PATTERN_TAG_HANDLE.test(handle)) { + throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); + } + + if (_hasOwnProperty.call(state.tagMap, handle)) { + throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); + } + + if (!PATTERN_TAG_URI.test(prefix)) { + throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); + } + + state.tagMap[handle] = prefix; + } +}; + + +function captureSegment(state, start, end, checkJson) { + var _position, _length, _character, _result; + + if (start < end) { + _result = state.input.slice(start, end); + + if (checkJson) { + for (_position = 0, _length = _result.length; _position < _length; _position += 1) { + _character = _result.charCodeAt(_position); + if (!(_character === 0x09 || + (0x20 <= _character && _character <= 0x10FFFF))) { + throwError(state, 'expected valid JSON character'); + } + } + } else if (PATTERN_NON_PRINTABLE.test(_result)) { + throwError(state, 'the stream contains non-printable characters'); + } + + state.result += _result; + } +} + +function mergeMappings(state, destination, source, overridableKeys) { + var sourceKeys, key, index, quantity; + + if (!common.isObject(source)) { + throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); + } + + sourceKeys = Object.keys(source); + + for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { + key = sourceKeys[index]; + + if (!_hasOwnProperty.call(destination, key)) { + destination[key] = source[key]; + overridableKeys[key] = true; + } + } +} + +function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) { + var index, quantity; + + // The output is a plain object here, so keys can only be strings. + // We need to convert keyNode to a string, but doing so can hang the process + // (deeply nested arrays that explode exponentially using aliases). + if (Array.isArray(keyNode)) { + keyNode = Array.prototype.slice.call(keyNode); + + for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { + if (Array.isArray(keyNode[index])) { + throwError(state, 'nested arrays are not supported inside keys'); + } + + if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { + keyNode[index] = '[object Object]'; + } + } + } + + // Avoid code execution in load() via toString property + // (still use its own toString for arrays, timestamps, + // and whatever user schema extensions happen to have @@toStringTag) + if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { + keyNode = '[object Object]'; + } + + + keyNode = String(keyNode); + + if (_result === null) { + _result = {}; + } + + if (keyTag === 'tag:yaml.org,2002:merge') { + if (Array.isArray(valueNode)) { + for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { + mergeMappings(state, _result, valueNode[index], overridableKeys); + } + } else { + mergeMappings(state, _result, valueNode, overridableKeys); + } + } else { + if (!state.json && + !_hasOwnProperty.call(overridableKeys, keyNode) && + _hasOwnProperty.call(_result, keyNode)) { + state.line = startLine || state.line; + state.position = startPos || state.position; + throwError(state, 'duplicated mapping key'); + } + _result[keyNode] = valueNode; + delete overridableKeys[keyNode]; + } + + return _result; +} + +function readLineBreak(state) { + var ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x0A/* LF */) { + state.position++; + } else if (ch === 0x0D/* CR */) { + state.position++; + if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { + state.position++; + } + } else { + throwError(state, 'a line break is expected'); + } + + state.line += 1; + state.lineStart = state.position; +} + +function skipSeparationSpace(state, allowComments, checkIndent) { + var lineBreaks = 0, + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (allowComments && ch === 0x23/* # */) { + do { + ch = state.input.charCodeAt(++state.position); + } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); + } + + if (is_EOL(ch)) { + readLineBreak(state); + + ch = state.input.charCodeAt(state.position); + lineBreaks++; + state.lineIndent = 0; + + while (ch === 0x20/* Space */) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + } else { + break; + } + } + + if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { + throwWarning(state, 'deficient indentation'); + } + + return lineBreaks; +} + +function testDocumentSeparator(state) { + var _position = state.position, + ch; + + ch = state.input.charCodeAt(_position); + + // Condition state.position === state.lineStart is tested + // in parent on each call, for efficiency. No needs to test here again. + if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && + ch === state.input.charCodeAt(_position + 1) && + ch === state.input.charCodeAt(_position + 2)) { + + _position += 3; + + ch = state.input.charCodeAt(_position); + + if (ch === 0 || is_WS_OR_EOL(ch)) { + return true; + } + } + + return false; +} + +function writeFoldedLines(state, count) { + if (count === 1) { + state.result += ' '; + } else if (count > 1) { + state.result += common.repeat('\n', count - 1); + } +} + + +function readPlainScalar(state, nodeIndent, withinFlowCollection) { + var preceding, + following, + captureStart, + captureEnd, + hasPendingContent, + _line, + _lineStart, + _lineIndent, + _kind = state.kind, + _result = state.result, + ch; + + ch = state.input.charCodeAt(state.position); + + if (is_WS_OR_EOL(ch) || + is_FLOW_INDICATOR(ch) || + ch === 0x23/* # */ || + ch === 0x26/* & */ || + ch === 0x2A/* * */ || + ch === 0x21/* ! */ || + ch === 0x7C/* | */ || + ch === 0x3E/* > */ || + ch === 0x27/* ' */ || + ch === 0x22/* " */ || + ch === 0x25/* % */ || + ch === 0x40/* @ */ || + ch === 0x60/* ` */) { + return false; + } + + if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + return false; + } + } + + state.kind = 'scalar'; + state.result = ''; + captureStart = captureEnd = state.position; + hasPendingContent = false; + + while (ch !== 0) { + if (ch === 0x3A/* : */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + break; + } + + } else if (ch === 0x23/* # */) { + preceding = state.input.charCodeAt(state.position - 1); + + if (is_WS_OR_EOL(preceding)) { + break; + } + + } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || + withinFlowCollection && is_FLOW_INDICATOR(ch)) { + break; + + } else if (is_EOL(ch)) { + _line = state.line; + _lineStart = state.lineStart; + _lineIndent = state.lineIndent; + skipSeparationSpace(state, false, -1); + + if (state.lineIndent >= nodeIndent) { + hasPendingContent = true; + ch = state.input.charCodeAt(state.position); + continue; + } else { + state.position = captureEnd; + state.line = _line; + state.lineStart = _lineStart; + state.lineIndent = _lineIndent; + break; + } + } + + if (hasPendingContent) { + captureSegment(state, captureStart, captureEnd, false); + writeFoldedLines(state, state.line - _line); + captureStart = captureEnd = state.position; + hasPendingContent = false; + } + + if (!is_WHITE_SPACE(ch)) { + captureEnd = state.position + 1; + } + + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, captureEnd, false); + + if (state.result) { + return true; + } + + state.kind = _kind; + state.result = _result; + return false; +} + +function readSingleQuotedScalar(state, nodeIndent) { + var ch, + captureStart, captureEnd; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x27/* ' */) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x27/* ' */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x27/* ' */) { + captureStart = state.position; + state.position++; + captureEnd = state.position; + } else { + return true; + } + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a single quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a single quoted scalar'); +} + +function readDoubleQuotedScalar(state, nodeIndent) { + var captureStart, + captureEnd, + hexLength, + hexResult, + tmp, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x22/* " */) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x22/* " */) { + captureSegment(state, captureStart, state.position, true); + state.position++; + return true; + + } else if (ch === 0x5C/* \ */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (is_EOL(ch)) { + skipSeparationSpace(state, false, nodeIndent); + + // TODO: rework to inline fn with no type cast? + } else if (ch < 256 && simpleEscapeCheck[ch]) { + state.result += simpleEscapeMap[ch]; + state.position++; + + } else if ((tmp = escapedHexLen(ch)) > 0) { + hexLength = tmp; + hexResult = 0; + + for (; hexLength > 0; hexLength--) { + ch = state.input.charCodeAt(++state.position); + + if ((tmp = fromHexCode(ch)) >= 0) { + hexResult = (hexResult << 4) + tmp; + + } else { + throwError(state, 'expected hexadecimal character'); + } + } + + state.result += charFromCodepoint(hexResult); + + state.position++; + + } else { + throwError(state, 'unknown escape sequence'); + } + + captureStart = captureEnd = state.position; + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a double quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a double quoted scalar'); +} + +function readFlowCollection(state, nodeIndent) { + var readNext = true, + _line, + _tag = state.tag, + _result, + _anchor = state.anchor, + following, + terminator, + isPair, + isExplicitPair, + isMapping, + overridableKeys = {}, + keyNode, + keyTag, + valueNode, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x5B/* [ */) { + terminator = 0x5D;/* ] */ + isMapping = false; + _result = []; + } else if (ch === 0x7B/* { */) { + terminator = 0x7D;/* } */ + isMapping = true; + _result = {}; + } else { + return false; + } + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(++state.position); + + while (ch !== 0) { + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === terminator) { + state.position++; + state.tag = _tag; + state.anchor = _anchor; + state.kind = isMapping ? 'mapping' : 'sequence'; + state.result = _result; + return true; + } else if (!readNext) { + throwError(state, 'missed comma between flow collection entries'); + } + + keyTag = keyNode = valueNode = null; + isPair = isExplicitPair = false; + + if (ch === 0x3F/* ? */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following)) { + isPair = isExplicitPair = true; + state.position++; + skipSeparationSpace(state, true, nodeIndent); + } + } + + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + keyTag = state.tag; + keyNode = state.result; + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { + isPair = true; + ch = state.input.charCodeAt(++state.position); + skipSeparationSpace(state, true, nodeIndent); + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + valueNode = state.result; + } + + if (isMapping) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode); + } else if (isPair) { + _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode)); + } else { + _result.push(keyNode); + } + + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x2C/* , */) { + readNext = true; + ch = state.input.charCodeAt(++state.position); + } else { + readNext = false; + } + } + + throwError(state, 'unexpected end of the stream within a flow collection'); +} + +function readBlockScalar(state, nodeIndent) { + var captureStart, + folding, + chomping = CHOMPING_CLIP, + didReadContent = false, + detectedIndent = false, + textIndent = nodeIndent, + emptyLines = 0, + atMoreIndented = false, + tmp, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x7C/* | */) { + folding = false; + } else if (ch === 0x3E/* > */) { + folding = true; + } else { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + + while (ch !== 0) { + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { + if (CHOMPING_CLIP === chomping) { + chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; + } else { + throwError(state, 'repeat of a chomping mode identifier'); + } + + } else if ((tmp = fromDecimalCode(ch)) >= 0) { + if (tmp === 0) { + throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); + } else if (!detectedIndent) { + textIndent = nodeIndent + tmp - 1; + detectedIndent = true; + } else { + throwError(state, 'repeat of an indentation width identifier'); + } + + } else { + break; + } + } + + if (is_WHITE_SPACE(ch)) { + do { ch = state.input.charCodeAt(++state.position); } + while (is_WHITE_SPACE(ch)); + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (!is_EOL(ch) && (ch !== 0)); + } + } + + while (ch !== 0) { + readLineBreak(state); + state.lineIndent = 0; + + ch = state.input.charCodeAt(state.position); + + while ((!detectedIndent || state.lineIndent < textIndent) && + (ch === 0x20/* Space */)) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + + if (!detectedIndent && state.lineIndent > textIndent) { + textIndent = state.lineIndent; + } + + if (is_EOL(ch)) { + emptyLines++; + continue; + } + + // End of the scalar. + if (state.lineIndent < textIndent) { + + // Perform the chomping. + if (chomping === CHOMPING_KEEP) { + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } else if (chomping === CHOMPING_CLIP) { + if (didReadContent) { // i.e. only if the scalar is not empty. + state.result += '\n'; + } + } + + // Break this `while` cycle and go to the funciton's epilogue. + break; + } + + // Folded style: use fancy rules to handle line breaks. + if (folding) { + + // Lines starting with white space characters (more-indented lines) are not folded. + if (is_WHITE_SPACE(ch)) { + atMoreIndented = true; + // except for the first content line (cf. Example 8.1) + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + + // End of more-indented block. + } else if (atMoreIndented) { + atMoreIndented = false; + state.result += common.repeat('\n', emptyLines + 1); + + // Just one line break - perceive as the same line. + } else if (emptyLines === 0) { + if (didReadContent) { // i.e. only if we have already read some scalar content. + state.result += ' '; + } + + // Several line breaks - perceive as different lines. + } else { + state.result += common.repeat('\n', emptyLines); + } + + // Literal style: just add exact number of line breaks between content lines. + } else { + // Keep all line breaks except the header line break. + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } + + didReadContent = true; + detectedIndent = true; + emptyLines = 0; + captureStart = state.position; + + while (!is_EOL(ch) && (ch !== 0)) { + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, state.position, false); + } + + return true; +} + +function readBlockSequence(state, nodeIndent) { + var _line, + _tag = state.tag, + _anchor = state.anchor, + _result = [], + following, + detected = false, + ch; + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + + if (ch !== 0x2D/* - */) { + break; + } + + following = state.input.charCodeAt(state.position + 1); + + if (!is_WS_OR_EOL(following)) { + break; + } + + detected = true; + state.position++; + + if (skipSeparationSpace(state, true, -1)) { + if (state.lineIndent <= nodeIndent) { + _result.push(null); + ch = state.input.charCodeAt(state.position); + continue; + } + } + + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); + _result.push(state.result); + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a sequence entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } + + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'sequence'; + state.result = _result; + return true; + } + return false; +} + +function readBlockMapping(state, nodeIndent, flowIndent) { + var following, + allowCompact, + _line, + _pos, + _tag = state.tag, + _anchor = state.anchor, + _result = {}, + overridableKeys = {}, + keyTag = null, + keyNode = null, + valueNode = null, + atExplicitKey = false, + detected = false, + ch; + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + following = state.input.charCodeAt(state.position + 1); + _line = state.line; // Save the current line. + _pos = state.position; + + // + // Explicit notation case. There are two separate blocks: + // first for the key (denoted by "?") and second for the value (denoted by ":") + // + if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { + + if (ch === 0x3F/* ? */) { + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = true; + allowCompact = true; + + } else if (atExplicitKey) { + // i.e. 0x3A/* : */ === character after the explicit key. + atExplicitKey = false; + allowCompact = true; + + } else { + throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); + } + + state.position += 1; + ch = following; + + // + // Implicit notation case. Flow-style node as the key first, then ":", and the value. + // + } else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { + + if (state.line === _line) { + ch = state.input.charCodeAt(state.position); + + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (ch === 0x3A/* : */) { + ch = state.input.charCodeAt(++state.position); + + if (!is_WS_OR_EOL(ch)) { + throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); + } + + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = false; + allowCompact = false; + keyTag = state.tag; + keyNode = state.result; + + } else if (detected) { + throwError(state, 'can not read an implicit mapping pair; a colon is missed'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + + } else if (detected) { + throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + + } else { + break; // Reading is done. Go to the epilogue. + } + + // + // Common reading code for both explicit and implicit notations. + // + if (state.line === _line || state.lineIndent > nodeIndent) { + if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { + if (atExplicitKey) { + keyNode = state.result; + } else { + valueNode = state.result; + } + } + + if (!atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _pos); + keyTag = keyNode = valueNode = null; + } + + skipSeparationSpace(state, true, -1); + ch = state.input.charCodeAt(state.position); + } + + if (state.lineIndent > nodeIndent && (ch !== 0)) { + throwError(state, 'bad indentation of a mapping entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } + + // + // Epilogue. + // + + // Special case: last mapping's node contains only the key in explicit notation. + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); + } + + // Expose the resulting mapping. + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'mapping'; + state.result = _result; + } + + return detected; +} + +function readTagProperty(state) { + var _position, + isVerbatim = false, + isNamed = false, + tagHandle, + tagName, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x21/* ! */) return false; + + if (state.tag !== null) { + throwError(state, 'duplication of a tag property'); + } + + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x3C/* < */) { + isVerbatim = true; + ch = state.input.charCodeAt(++state.position); + + } else if (ch === 0x21/* ! */) { + isNamed = true; + tagHandle = '!!'; + ch = state.input.charCodeAt(++state.position); + + } else { + tagHandle = '!'; + } + + _position = state.position; + + if (isVerbatim) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && ch !== 0x3E/* > */); + + if (state.position < state.length) { + tagName = state.input.slice(_position, state.position); + ch = state.input.charCodeAt(++state.position); + } else { + throwError(state, 'unexpected end of the stream within a verbatim tag'); + } + } else { + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + + if (ch === 0x21/* ! */) { + if (!isNamed) { + tagHandle = state.input.slice(_position - 1, state.position + 1); + + if (!PATTERN_TAG_HANDLE.test(tagHandle)) { + throwError(state, 'named tag handle cannot contain such characters'); + } + + isNamed = true; + _position = state.position + 1; + } else { + throwError(state, 'tag suffix cannot contain exclamation marks'); + } + } + + ch = state.input.charCodeAt(++state.position); + } + + tagName = state.input.slice(_position, state.position); + + if (PATTERN_FLOW_INDICATORS.test(tagName)) { + throwError(state, 'tag suffix cannot contain flow indicator characters'); + } + } + + if (tagName && !PATTERN_TAG_URI.test(tagName)) { + throwError(state, 'tag name cannot contain such characters: ' + tagName); + } + + if (isVerbatim) { + state.tag = tagName; + + } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) { + state.tag = state.tagMap[tagHandle] + tagName; + + } else if (tagHandle === '!') { + state.tag = '!' + tagName; + + } else if (tagHandle === '!!') { + state.tag = 'tag:yaml.org,2002:' + tagName; + + } else { + throwError(state, 'undeclared tag handle "' + tagHandle + '"'); + } + + return true; +} + +function readAnchorProperty(state) { + var _position, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x26/* & */) return false; + + if (state.anchor !== null) { + throwError(state, 'duplication of an anchor property'); + } + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an anchor node must contain at least one character'); + } + + state.anchor = state.input.slice(_position, state.position); + return true; +} + +function readAlias(state) { + var _position, alias, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x2A/* * */) return false; + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an alias node must contain at least one character'); + } + + alias = state.input.slice(_position, state.position); + + if (!_hasOwnProperty.call(state.anchorMap, alias)) { + throwError(state, 'unidentified alias "' + alias + '"'); + } + + state.result = state.anchorMap[alias]; + skipSeparationSpace(state, true, -1); + return true; +} + +function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { + var allowBlockStyles, + allowBlockScalars, + allowBlockCollections, + indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } + } + + if (indentStatus === 1) { + while (readTagProperty(state) || readAnchorProperty(state)) { + if (skipSeparationSpace(state, true, -1)) { + atNewLine = true; + allowBlockCollections = allowBlockStyles; + + if (state.lineIndent > parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } else { + allowBlockCollections = false; + } + } + } + + if (allowBlockCollections) { + allowBlockCollections = atNewLine || allowCompact; + } + + if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { + if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { + flowIndent = parentIndent; + } else { + flowIndent = parentIndent + 1; + } + + blockIndent = state.position - state.lineStart; + + if (indentStatus === 1) { + if (allowBlockCollections && + (readBlockSequence(state, blockIndent) || + readBlockMapping(state, blockIndent, flowIndent)) || + readFlowCollection(state, flowIndent)) { + hasContent = true; + } else { + if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || + readSingleQuotedScalar(state, flowIndent) || + readDoubleQuotedScalar(state, flowIndent)) { + hasContent = true; + + } else if (readAlias(state)) { + hasContent = true; + + if (state.tag !== null || state.anchor !== null) { + throwError(state, 'alias node should not have any properties'); + } + + } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { + hasContent = true; + + if (state.tag === null) { + state.tag = '?'; + } + } + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } else if (indentStatus === 0) { + // Special case: block sequences are allowed to have same indentation level as the parent. + // http://www.yaml.org/spec/1.2/spec.html#id2799784 + hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); + } + } + + if (state.tag !== null && state.tag !== '!') { + if (state.tag === '?') { + // Implicit resolving is not allowed for non-scalar types, and '?' + // non-specific tag is only automatically assigned to plain scalars. + // + // We only need to check kind conformity in case user explicitly assigns '?' + // tag, for example like this: "! [0]" + // + if (state.result !== null && state.kind !== 'scalar') { + throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); + } + + for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { + type = state.implicitTypes[typeIndex]; + + if (type.resolve(state.result)) { // `state.result` updated in resolver if matched + state.result = type.construct(state.result); + state.tag = type.tag; + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + break; + } + } + } else if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) { + type = state.typeMap[state.kind || 'fallback'][state.tag]; + + if (state.result !== null && type.kind !== state.kind) { + throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); + } + + if (!type.resolve(state.result)) { // `state.result` updated in resolver if matched + throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); + } else { + state.result = type.construct(state.result); + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } else { + throwError(state, 'unknown tag !<' + state.tag + '>'); + } + } + + if (state.listener !== null) { + state.listener('close', state); + } + return state.tag !== null || state.anchor !== null || hasContent; +} + +function readDocument(state) { + var documentStart = state.position, + _position, + directiveName, + directiveArgs, + hasDirectives = false, + ch; + + state.version = null; + state.checkLineBreaks = state.legacy; + state.tagMap = {}; + state.anchorMap = {}; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if (state.lineIndent > 0 || ch !== 0x25/* % */) { + break; + } + + hasDirectives = true; + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveName = state.input.slice(_position, state.position); + directiveArgs = []; + + if (directiveName.length < 1) { + throwError(state, 'directive name must not be less than one character in length'); + } + + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && !is_EOL(ch)); + break; + } + + if (is_EOL(ch)) break; + + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveArgs.push(state.input.slice(_position, state.position)); + } + + if (ch !== 0) readLineBreak(state); + + if (_hasOwnProperty.call(directiveHandlers, directiveName)) { + directiveHandlers[directiveName](state, directiveName, directiveArgs); + } else { + throwWarning(state, 'unknown document directive "' + directiveName + '"'); + } + } + + skipSeparationSpace(state, true, -1); + + if (state.lineIndent === 0 && + state.input.charCodeAt(state.position) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + + } else if (hasDirectives) { + throwError(state, 'directives end mark is expected'); + } + + composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); + skipSeparationSpace(state, true, -1); + + if (state.checkLineBreaks && + PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { + throwWarning(state, 'non-ASCII line breaks are interpreted as content'); + } + + state.documents.push(state.result); + + if (state.position === state.lineStart && testDocumentSeparator(state)) { + + if (state.input.charCodeAt(state.position) === 0x2E/* . */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + } + return; + } + + if (state.position < (state.length - 1)) { + throwError(state, 'end of the stream or a document separator is expected'); + } else { + return; + } +} + + +function loadDocuments(input, options) { + input = String(input); + options = options || {}; + + if (input.length !== 0) { + + // Add tailing `\n` if not exists + if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && + input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { + input += '\n'; + } + + // Strip BOM + if (input.charCodeAt(0) === 0xFEFF) { + input = input.slice(1); + } + } + + var state = new State(input, options); + + var nullpos = input.indexOf('\0'); + + if (nullpos !== -1) { + state.position = nullpos; + throwError(state, 'null byte is not allowed in input'); + } + + // Use 0 as string terminator. That significantly simplifies bounds check. + state.input += '\0'; + + while (state.input.charCodeAt(state.position) === 0x20/* Space */) { + state.lineIndent += 1; + state.position += 1; + } + + while (state.position < (state.length - 1)) { + readDocument(state); + } + + return state.documents; +} + + +function loadAll(input, iterator, options) { + if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { + options = iterator; + iterator = null; + } + + var documents = loadDocuments(input, options); + + if (typeof iterator !== 'function') { + return documents; + } + + for (var index = 0, length = documents.length; index < length; index += 1) { + iterator(documents[index]); + } +} + + +function load(input, options) { + var documents = loadDocuments(input, options); + + if (documents.length === 0) { + /*eslint-disable no-undefined*/ + return undefined; + } else if (documents.length === 1) { + return documents[0]; + } + throw new YAMLException('expected a single document in the stream, but found more'); +} + + +function safeLoadAll(input, iterator, options) { + if (typeof iterator === 'object' && iterator !== null && typeof options === 'undefined') { + options = iterator; + iterator = null; + } + + return loadAll(input, iterator, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +} + + +function safeLoad(input, options) { + return load(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +} + + +module.exports.loadAll = loadAll; +module.exports.load = load; +module.exports.safeLoadAll = safeLoadAll; +module.exports.safeLoad = safeLoad; diff --git a/scripts/node_modules/js-yaml/lib/js-yaml/mark.js b/scripts/node_modules/js-yaml/lib/js-yaml/mark.js new file mode 100644 index 000000000..47b265c20 --- /dev/null +++ b/scripts/node_modules/js-yaml/lib/js-yaml/mark.js @@ -0,0 +1,76 @@ +'use strict'; + + +var common = require('./common'); + + +function Mark(name, buffer, position, line, column) { + this.name = name; + this.buffer = buffer; + this.position = position; + this.line = line; + this.column = column; +} + + +Mark.prototype.getSnippet = function getSnippet(indent, maxLength) { + var head, start, tail, end, snippet; + + if (!this.buffer) return null; + + indent = indent || 4; + maxLength = maxLength || 75; + + head = ''; + start = this.position; + + while (start > 0 && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) { + start -= 1; + if (this.position - start > (maxLength / 2 - 1)) { + head = ' ... '; + start += 5; + break; + } + } + + tail = ''; + end = this.position; + + while (end < this.buffer.length && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end)) === -1) { + end += 1; + if (end - this.position > (maxLength / 2 - 1)) { + tail = ' ... '; + end -= 5; + break; + } + } + + snippet = this.buffer.slice(start, end); + + return common.repeat(' ', indent) + head + snippet + tail + '\n' + + common.repeat(' ', indent + this.position - start + head.length) + '^'; +}; + + +Mark.prototype.toString = function toString(compact) { + var snippet, where = ''; + + if (this.name) { + where += 'in "' + this.name + '" '; + } + + where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1); + + if (!compact) { + snippet = this.getSnippet(); + + if (snippet) { + where += ':\n' + snippet; + } + } + + return where; +}; + + +module.exports = Mark; diff --git a/scripts/node_modules/js-yaml/lib/js-yaml/schema.js b/scripts/node_modules/js-yaml/lib/js-yaml/schema.js new file mode 100644 index 000000000..ca7cf47e7 --- /dev/null +++ b/scripts/node_modules/js-yaml/lib/js-yaml/schema.js @@ -0,0 +1,108 @@ +'use strict'; + +/*eslint-disable max-len*/ + +var common = require('./common'); +var YAMLException = require('./exception'); +var Type = require('./type'); + + +function compileList(schema, name, result) { + var exclude = []; + + schema.include.forEach(function (includedSchema) { + result = compileList(includedSchema, name, result); + }); + + schema[name].forEach(function (currentType) { + result.forEach(function (previousType, previousIndex) { + if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) { + exclude.push(previousIndex); + } + }); + + result.push(currentType); + }); + + return result.filter(function (type, index) { + return exclude.indexOf(index) === -1; + }); +} + + +function compileMap(/* lists... */) { + var result = { + scalar: {}, + sequence: {}, + mapping: {}, + fallback: {} + }, index, length; + + function collectType(type) { + result[type.kind][type.tag] = result['fallback'][type.tag] = type; + } + + for (index = 0, length = arguments.length; index < length; index += 1) { + arguments[index].forEach(collectType); + } + return result; +} + + +function Schema(definition) { + this.include = definition.include || []; + this.implicit = definition.implicit || []; + this.explicit = definition.explicit || []; + + this.implicit.forEach(function (type) { + if (type.loadKind && type.loadKind !== 'scalar') { + throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); + } + }); + + this.compiledImplicit = compileList(this, 'implicit', []); + this.compiledExplicit = compileList(this, 'explicit', []); + this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit); +} + + +Schema.DEFAULT = null; + + +Schema.create = function createSchema() { + var schemas, types; + + switch (arguments.length) { + case 1: + schemas = Schema.DEFAULT; + types = arguments[0]; + break; + + case 2: + schemas = arguments[0]; + types = arguments[1]; + break; + + default: + throw new YAMLException('Wrong number of arguments for Schema.create function'); + } + + schemas = common.toArray(schemas); + types = common.toArray(types); + + if (!schemas.every(function (schema) { return schema instanceof Schema; })) { + throw new YAMLException('Specified list of super schemas (or a single Schema object) contains a non-Schema object.'); + } + + if (!types.every(function (type) { return type instanceof Type; })) { + throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + } + + return new Schema({ + include: schemas, + explicit: types + }); +}; + + +module.exports = Schema; diff --git a/scripts/node_modules/js-yaml/lib/js-yaml/schema/core.js b/scripts/node_modules/js-yaml/lib/js-yaml/schema/core.js new file mode 100644 index 000000000..206daab56 --- /dev/null +++ b/scripts/node_modules/js-yaml/lib/js-yaml/schema/core.js @@ -0,0 +1,18 @@ +// Standard YAML's Core schema. +// http://www.yaml.org/spec/1.2/spec.html#id2804923 +// +// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. +// So, Core schema has no distinctions from JSON schema is JS-YAML. + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = new Schema({ + include: [ + require('./json') + ] +}); diff --git a/scripts/node_modules/js-yaml/lib/js-yaml/schema/default_full.js b/scripts/node_modules/js-yaml/lib/js-yaml/schema/default_full.js new file mode 100644 index 000000000..a55ef42ac --- /dev/null +++ b/scripts/node_modules/js-yaml/lib/js-yaml/schema/default_full.js @@ -0,0 +1,25 @@ +// JS-YAML's default schema for `load` function. +// It is not described in the YAML specification. +// +// This schema is based on JS-YAML's default safe schema and includes +// JavaScript-specific types: !!js/undefined, !!js/regexp and !!js/function. +// +// Also this schema is used as default base schema at `Schema.create` function. + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = Schema.DEFAULT = new Schema({ + include: [ + require('./default_safe') + ], + explicit: [ + require('../type/js/undefined'), + require('../type/js/regexp'), + require('../type/js/function') + ] +}); diff --git a/scripts/node_modules/js-yaml/lib/js-yaml/schema/default_safe.js b/scripts/node_modules/js-yaml/lib/js-yaml/schema/default_safe.js new file mode 100644 index 000000000..11d89bbfb --- /dev/null +++ b/scripts/node_modules/js-yaml/lib/js-yaml/schema/default_safe.js @@ -0,0 +1,28 @@ +// JS-YAML's default schema for `safeLoad` function. +// It is not described in the YAML specification. +// +// This schema is based on standard YAML's Core schema and includes most of +// extra types described at YAML tag repository. (http://yaml.org/type/) + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = new Schema({ + include: [ + require('./core') + ], + implicit: [ + require('../type/timestamp'), + require('../type/merge') + ], + explicit: [ + require('../type/binary'), + require('../type/omap'), + require('../type/pairs'), + require('../type/set') + ] +}); diff --git a/scripts/node_modules/js-yaml/lib/js-yaml/schema/failsafe.js b/scripts/node_modules/js-yaml/lib/js-yaml/schema/failsafe.js new file mode 100644 index 000000000..b7a33eb7a --- /dev/null +++ b/scripts/node_modules/js-yaml/lib/js-yaml/schema/failsafe.js @@ -0,0 +1,17 @@ +// Standard YAML's Failsafe schema. +// http://www.yaml.org/spec/1.2/spec.html#id2802346 + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = new Schema({ + explicit: [ + require('../type/str'), + require('../type/seq'), + require('../type/map') + ] +}); diff --git a/scripts/node_modules/js-yaml/lib/js-yaml/schema/json.js b/scripts/node_modules/js-yaml/lib/js-yaml/schema/json.js new file mode 100644 index 000000000..5be3dbf80 --- /dev/null +++ b/scripts/node_modules/js-yaml/lib/js-yaml/schema/json.js @@ -0,0 +1,25 @@ +// Standard YAML's JSON schema. +// http://www.yaml.org/spec/1.2/spec.html#id2803231 +// +// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. +// So, this schema is not such strict as defined in the YAML specification. +// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc. + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = new Schema({ + include: [ + require('./failsafe') + ], + implicit: [ + require('../type/null'), + require('../type/bool'), + require('../type/int'), + require('../type/float') + ] +}); diff --git a/scripts/node_modules/js-yaml/lib/js-yaml/type.js b/scripts/node_modules/js-yaml/lib/js-yaml/type.js new file mode 100644 index 000000000..90b702ac0 --- /dev/null +++ b/scripts/node_modules/js-yaml/lib/js-yaml/type.js @@ -0,0 +1,61 @@ +'use strict'; + +var YAMLException = require('./exception'); + +var TYPE_CONSTRUCTOR_OPTIONS = [ + 'kind', + 'resolve', + 'construct', + 'instanceOf', + 'predicate', + 'represent', + 'defaultStyle', + 'styleAliases' +]; + +var YAML_NODE_KINDS = [ + 'scalar', + 'sequence', + 'mapping' +]; + +function compileStyleAliases(map) { + var result = {}; + + if (map !== null) { + Object.keys(map).forEach(function (style) { + map[style].forEach(function (alias) { + result[String(alias)] = style; + }); + }); + } + + return result; +} + +function Type(tag, options) { + options = options || {}; + + Object.keys(options).forEach(function (name) { + if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { + throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); + } + }); + + // TODO: Add tag format check. + this.tag = tag; + this.kind = options['kind'] || null; + this.resolve = options['resolve'] || function () { return true; }; + this.construct = options['construct'] || function (data) { return data; }; + this.instanceOf = options['instanceOf'] || null; + this.predicate = options['predicate'] || null; + this.represent = options['represent'] || null; + this.defaultStyle = options['defaultStyle'] || null; + this.styleAliases = compileStyleAliases(options['styleAliases'] || null); + + if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { + throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); + } +} + +module.exports = Type; diff --git a/scripts/node_modules/js-yaml/lib/js-yaml/type/binary.js b/scripts/node_modules/js-yaml/lib/js-yaml/type/binary.js new file mode 100644 index 000000000..10b187559 --- /dev/null +++ b/scripts/node_modules/js-yaml/lib/js-yaml/type/binary.js @@ -0,0 +1,138 @@ +'use strict'; + +/*eslint-disable no-bitwise*/ + +var NodeBuffer; + +try { + // A trick for browserified version, to not include `Buffer` shim + var _require = require; + NodeBuffer = _require('buffer').Buffer; +} catch (__) {} + +var Type = require('../type'); + + +// [ 64, 65, 66 ] -> [ padding, CR, LF ] +var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; + + +function resolveYamlBinary(data) { + if (data === null) return false; + + var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; + + // Convert one by one. + for (idx = 0; idx < max; idx++) { + code = map.indexOf(data.charAt(idx)); + + // Skip CR/LF + if (code > 64) continue; + + // Fail on illegal characters + if (code < 0) return false; + + bitlen += 6; + } + + // If there are any bits left, source was corrupted + return (bitlen % 8) === 0; +} + +function constructYamlBinary(data) { + var idx, tailbits, + input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan + max = input.length, + map = BASE64_MAP, + bits = 0, + result = []; + + // Collect by 6*4 bits (3 bytes) + + for (idx = 0; idx < max; idx++) { + if ((idx % 4 === 0) && idx) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } + + bits = (bits << 6) | map.indexOf(input.charAt(idx)); + } + + // Dump tail + + tailbits = (max % 4) * 6; + + if (tailbits === 0) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } else if (tailbits === 18) { + result.push((bits >> 10) & 0xFF); + result.push((bits >> 2) & 0xFF); + } else if (tailbits === 12) { + result.push((bits >> 4) & 0xFF); + } + + // Wrap into Buffer for NodeJS and leave Array for browser + if (NodeBuffer) { + // Support node 6.+ Buffer API when available + return NodeBuffer.from ? NodeBuffer.from(result) : new NodeBuffer(result); + } + + return result; +} + +function representYamlBinary(object /*, style*/) { + var result = '', bits = 0, idx, tail, + max = object.length, + map = BASE64_MAP; + + // Convert every three bytes to 4 ASCII characters. + + for (idx = 0; idx < max; idx++) { + if ((idx % 3 === 0) && idx) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } + + bits = (bits << 8) + object[idx]; + } + + // Dump tail + + tail = max % 3; + + if (tail === 0) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } else if (tail === 2) { + result += map[(bits >> 10) & 0x3F]; + result += map[(bits >> 4) & 0x3F]; + result += map[(bits << 2) & 0x3F]; + result += map[64]; + } else if (tail === 1) { + result += map[(bits >> 2) & 0x3F]; + result += map[(bits << 4) & 0x3F]; + result += map[64]; + result += map[64]; + } + + return result; +} + +function isBinary(object) { + return NodeBuffer && NodeBuffer.isBuffer(object); +} + +module.exports = new Type('tag:yaml.org,2002:binary', { + kind: 'scalar', + resolve: resolveYamlBinary, + construct: constructYamlBinary, + predicate: isBinary, + represent: representYamlBinary +}); diff --git a/scripts/node_modules/js-yaml/lib/js-yaml/type/bool.js b/scripts/node_modules/js-yaml/lib/js-yaml/type/bool.js new file mode 100644 index 000000000..cb7745930 --- /dev/null +++ b/scripts/node_modules/js-yaml/lib/js-yaml/type/bool.js @@ -0,0 +1,35 @@ +'use strict'; + +var Type = require('../type'); + +function resolveYamlBoolean(data) { + if (data === null) return false; + + var max = data.length; + + return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || + (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); +} + +function constructYamlBoolean(data) { + return data === 'true' || + data === 'True' || + data === 'TRUE'; +} + +function isBoolean(object) { + return Object.prototype.toString.call(object) === '[object Boolean]'; +} + +module.exports = new Type('tag:yaml.org,2002:bool', { + kind: 'scalar', + resolve: resolveYamlBoolean, + construct: constructYamlBoolean, + predicate: isBoolean, + represent: { + lowercase: function (object) { return object ? 'true' : 'false'; }, + uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, + camelcase: function (object) { return object ? 'True' : 'False'; } + }, + defaultStyle: 'lowercase' +}); diff --git a/scripts/node_modules/js-yaml/lib/js-yaml/type/float.js b/scripts/node_modules/js-yaml/lib/js-yaml/type/float.js new file mode 100644 index 000000000..127671b21 --- /dev/null +++ b/scripts/node_modules/js-yaml/lib/js-yaml/type/float.js @@ -0,0 +1,116 @@ +'use strict'; + +var common = require('../common'); +var Type = require('../type'); + +var YAML_FLOAT_PATTERN = new RegExp( + // 2.5e4, 2.5 and integers + '^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + + // .2e4, .2 + // special case, seems not from spec + '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + + // 20:59 + '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' + + // .inf + '|[-+]?\\.(?:inf|Inf|INF)' + + // .nan + '|\\.(?:nan|NaN|NAN))$'); + +function resolveYamlFloat(data) { + if (data === null) return false; + + if (!YAML_FLOAT_PATTERN.test(data) || + // Quick hack to not allow integers end with `_` + // Probably should update regexp & check speed + data[data.length - 1] === '_') { + return false; + } + + return true; +} + +function constructYamlFloat(data) { + var value, sign, base, digits; + + value = data.replace(/_/g, '').toLowerCase(); + sign = value[0] === '-' ? -1 : 1; + digits = []; + + if ('+-'.indexOf(value[0]) >= 0) { + value = value.slice(1); + } + + if (value === '.inf') { + return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; + + } else if (value === '.nan') { + return NaN; + + } else if (value.indexOf(':') >= 0) { + value.split(':').forEach(function (v) { + digits.unshift(parseFloat(v, 10)); + }); + + value = 0.0; + base = 1; + + digits.forEach(function (d) { + value += d * base; + base *= 60; + }); + + return sign * value; + + } + return sign * parseFloat(value, 10); +} + + +var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; + +function representYamlFloat(object, style) { + var res; + + if (isNaN(object)) { + switch (style) { + case 'lowercase': return '.nan'; + case 'uppercase': return '.NAN'; + case 'camelcase': return '.NaN'; + } + } else if (Number.POSITIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '.inf'; + case 'uppercase': return '.INF'; + case 'camelcase': return '.Inf'; + } + } else if (Number.NEGATIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '-.inf'; + case 'uppercase': return '-.INF'; + case 'camelcase': return '-.Inf'; + } + } else if (common.isNegativeZero(object)) { + return '-0.0'; + } + + res = object.toString(10); + + // JS stringifier can build scientific format without dots: 5e-100, + // while YAML requres dot: 5.e-100. Fix it with simple hack + + return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; +} + +function isFloat(object) { + return (Object.prototype.toString.call(object) === '[object Number]') && + (object % 1 !== 0 || common.isNegativeZero(object)); +} + +module.exports = new Type('tag:yaml.org,2002:float', { + kind: 'scalar', + resolve: resolveYamlFloat, + construct: constructYamlFloat, + predicate: isFloat, + represent: representYamlFloat, + defaultStyle: 'lowercase' +}); diff --git a/scripts/node_modules/js-yaml/lib/js-yaml/type/int.js b/scripts/node_modules/js-yaml/lib/js-yaml/type/int.js new file mode 100644 index 000000000..ba61c5f95 --- /dev/null +++ b/scripts/node_modules/js-yaml/lib/js-yaml/type/int.js @@ -0,0 +1,173 @@ +'use strict'; + +var common = require('../common'); +var Type = require('../type'); + +function isHexCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || + ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || + ((0x61/* a */ <= c) && (c <= 0x66/* f */)); +} + +function isOctCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); +} + +function isDecCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); +} + +function resolveYamlInteger(data) { + if (data === null) return false; + + var max = data.length, + index = 0, + hasDigits = false, + ch; + + if (!max) return false; + + ch = data[index]; + + // sign + if (ch === '-' || ch === '+') { + ch = data[++index]; + } + + if (ch === '0') { + // 0 + if (index + 1 === max) return true; + ch = data[++index]; + + // base 2, base 8, base 16 + + if (ch === 'b') { + // base 2 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (ch !== '0' && ch !== '1') return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + + if (ch === 'x') { + // base 16 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isHexCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + // base 8 + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isOctCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + // base 10 (except 0) or base 60 + + // value should not start with `_`; + if (ch === '_') return false; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (ch === ':') break; + if (!isDecCode(data.charCodeAt(index))) { + return false; + } + hasDigits = true; + } + + // Should have digits and should not end with `_` + if (!hasDigits || ch === '_') return false; + + // if !base60 - done; + if (ch !== ':') return true; + + // base60 almost not used, no needs to optimize + return /^(:[0-5]?[0-9])+$/.test(data.slice(index)); +} + +function constructYamlInteger(data) { + var value = data, sign = 1, ch, base, digits = []; + + if (value.indexOf('_') !== -1) { + value = value.replace(/_/g, ''); + } + + ch = value[0]; + + if (ch === '-' || ch === '+') { + if (ch === '-') sign = -1; + value = value.slice(1); + ch = value[0]; + } + + if (value === '0') return 0; + + if (ch === '0') { + if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); + if (value[1] === 'x') return sign * parseInt(value, 16); + return sign * parseInt(value, 8); + } + + if (value.indexOf(':') !== -1) { + value.split(':').forEach(function (v) { + digits.unshift(parseInt(v, 10)); + }); + + value = 0; + base = 1; + + digits.forEach(function (d) { + value += (d * base); + base *= 60; + }); + + return sign * value; + + } + + return sign * parseInt(value, 10); +} + +function isInteger(object) { + return (Object.prototype.toString.call(object)) === '[object Number]' && + (object % 1 === 0 && !common.isNegativeZero(object)); +} + +module.exports = new Type('tag:yaml.org,2002:int', { + kind: 'scalar', + resolve: resolveYamlInteger, + construct: constructYamlInteger, + predicate: isInteger, + represent: { + binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, + octal: function (obj) { return obj >= 0 ? '0' + obj.toString(8) : '-0' + obj.toString(8).slice(1); }, + decimal: function (obj) { return obj.toString(10); }, + /* eslint-disable max-len */ + hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } + }, + defaultStyle: 'decimal', + styleAliases: { + binary: [ 2, 'bin' ], + octal: [ 8, 'oct' ], + decimal: [ 10, 'dec' ], + hexadecimal: [ 16, 'hex' ] + } +}); diff --git a/scripts/node_modules/js-yaml/lib/js-yaml/type/js/function.js b/scripts/node_modules/js-yaml/lib/js-yaml/type/js/function.js new file mode 100644 index 000000000..8fab8c430 --- /dev/null +++ b/scripts/node_modules/js-yaml/lib/js-yaml/type/js/function.js @@ -0,0 +1,93 @@ +'use strict'; + +var esprima; + +// Browserified version does not have esprima +// +// 1. For node.js just require module as deps +// 2. For browser try to require mudule via external AMD system. +// If not found - try to fallback to window.esprima. If not +// found too - then fail to parse. +// +try { + // workaround to exclude package from browserify list. + var _require = require; + esprima = _require('esprima'); +} catch (_) { + /* eslint-disable no-redeclare */ + /* global window */ + if (typeof window !== 'undefined') esprima = window.esprima; +} + +var Type = require('../../type'); + +function resolveJavascriptFunction(data) { + if (data === null) return false; + + try { + var source = '(' + data + ')', + ast = esprima.parse(source, { range: true }); + + if (ast.type !== 'Program' || + ast.body.length !== 1 || + ast.body[0].type !== 'ExpressionStatement' || + (ast.body[0].expression.type !== 'ArrowFunctionExpression' && + ast.body[0].expression.type !== 'FunctionExpression')) { + return false; + } + + return true; + } catch (err) { + return false; + } +} + +function constructJavascriptFunction(data) { + /*jslint evil:true*/ + + var source = '(' + data + ')', + ast = esprima.parse(source, { range: true }), + params = [], + body; + + if (ast.type !== 'Program' || + ast.body.length !== 1 || + ast.body[0].type !== 'ExpressionStatement' || + (ast.body[0].expression.type !== 'ArrowFunctionExpression' && + ast.body[0].expression.type !== 'FunctionExpression')) { + throw new Error('Failed to resolve function'); + } + + ast.body[0].expression.params.forEach(function (param) { + params.push(param.name); + }); + + body = ast.body[0].expression.body.range; + + // Esprima's ranges include the first '{' and the last '}' characters on + // function expressions. So cut them out. + if (ast.body[0].expression.body.type === 'BlockStatement') { + /*eslint-disable no-new-func*/ + return new Function(params, source.slice(body[0] + 1, body[1] - 1)); + } + // ES6 arrow functions can omit the BlockStatement. In that case, just return + // the body. + /*eslint-disable no-new-func*/ + return new Function(params, 'return ' + source.slice(body[0], body[1])); +} + +function representJavascriptFunction(object /*, style*/) { + return object.toString(); +} + +function isFunction(object) { + return Object.prototype.toString.call(object) === '[object Function]'; +} + +module.exports = new Type('tag:yaml.org,2002:js/function', { + kind: 'scalar', + resolve: resolveJavascriptFunction, + construct: constructJavascriptFunction, + predicate: isFunction, + represent: representJavascriptFunction +}); diff --git a/scripts/node_modules/js-yaml/lib/js-yaml/type/js/regexp.js b/scripts/node_modules/js-yaml/lib/js-yaml/type/js/regexp.js new file mode 100644 index 000000000..43fa47017 --- /dev/null +++ b/scripts/node_modules/js-yaml/lib/js-yaml/type/js/regexp.js @@ -0,0 +1,60 @@ +'use strict'; + +var Type = require('../../type'); + +function resolveJavascriptRegExp(data) { + if (data === null) return false; + if (data.length === 0) return false; + + var regexp = data, + tail = /\/([gim]*)$/.exec(data), + modifiers = ''; + + // if regexp starts with '/' it can have modifiers and must be properly closed + // `/foo/gim` - modifiers tail can be maximum 3 chars + if (regexp[0] === '/') { + if (tail) modifiers = tail[1]; + + if (modifiers.length > 3) return false; + // if expression starts with /, is should be properly terminated + if (regexp[regexp.length - modifiers.length - 1] !== '/') return false; + } + + return true; +} + +function constructJavascriptRegExp(data) { + var regexp = data, + tail = /\/([gim]*)$/.exec(data), + modifiers = ''; + + // `/foo/gim` - tail can be maximum 4 chars + if (regexp[0] === '/') { + if (tail) modifiers = tail[1]; + regexp = regexp.slice(1, regexp.length - modifiers.length - 1); + } + + return new RegExp(regexp, modifiers); +} + +function representJavascriptRegExp(object /*, style*/) { + var result = '/' + object.source + '/'; + + if (object.global) result += 'g'; + if (object.multiline) result += 'm'; + if (object.ignoreCase) result += 'i'; + + return result; +} + +function isRegExp(object) { + return Object.prototype.toString.call(object) === '[object RegExp]'; +} + +module.exports = new Type('tag:yaml.org,2002:js/regexp', { + kind: 'scalar', + resolve: resolveJavascriptRegExp, + construct: constructJavascriptRegExp, + predicate: isRegExp, + represent: representJavascriptRegExp +}); diff --git a/scripts/node_modules/js-yaml/lib/js-yaml/type/js/undefined.js b/scripts/node_modules/js-yaml/lib/js-yaml/type/js/undefined.js new file mode 100644 index 000000000..95b5569fd --- /dev/null +++ b/scripts/node_modules/js-yaml/lib/js-yaml/type/js/undefined.js @@ -0,0 +1,28 @@ +'use strict'; + +var Type = require('../../type'); + +function resolveJavascriptUndefined() { + return true; +} + +function constructJavascriptUndefined() { + /*eslint-disable no-undefined*/ + return undefined; +} + +function representJavascriptUndefined() { + return ''; +} + +function isUndefined(object) { + return typeof object === 'undefined'; +} + +module.exports = new Type('tag:yaml.org,2002:js/undefined', { + kind: 'scalar', + resolve: resolveJavascriptUndefined, + construct: constructJavascriptUndefined, + predicate: isUndefined, + represent: representJavascriptUndefined +}); diff --git a/scripts/node_modules/js-yaml/lib/js-yaml/type/map.js b/scripts/node_modules/js-yaml/lib/js-yaml/type/map.js new file mode 100644 index 000000000..f327beebd --- /dev/null +++ b/scripts/node_modules/js-yaml/lib/js-yaml/type/map.js @@ -0,0 +1,8 @@ +'use strict'; + +var Type = require('../type'); + +module.exports = new Type('tag:yaml.org,2002:map', { + kind: 'mapping', + construct: function (data) { return data !== null ? data : {}; } +}); diff --git a/scripts/node_modules/js-yaml/lib/js-yaml/type/merge.js b/scripts/node_modules/js-yaml/lib/js-yaml/type/merge.js new file mode 100644 index 000000000..ae08a8644 --- /dev/null +++ b/scripts/node_modules/js-yaml/lib/js-yaml/type/merge.js @@ -0,0 +1,12 @@ +'use strict'; + +var Type = require('../type'); + +function resolveYamlMerge(data) { + return data === '<<' || data === null; +} + +module.exports = new Type('tag:yaml.org,2002:merge', { + kind: 'scalar', + resolve: resolveYamlMerge +}); diff --git a/scripts/node_modules/js-yaml/lib/js-yaml/type/null.js b/scripts/node_modules/js-yaml/lib/js-yaml/type/null.js new file mode 100644 index 000000000..6874daa64 --- /dev/null +++ b/scripts/node_modules/js-yaml/lib/js-yaml/type/null.js @@ -0,0 +1,34 @@ +'use strict'; + +var Type = require('../type'); + +function resolveYamlNull(data) { + if (data === null) return true; + + var max = data.length; + + return (max === 1 && data === '~') || + (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); +} + +function constructYamlNull() { + return null; +} + +function isNull(object) { + return object === null; +} + +module.exports = new Type('tag:yaml.org,2002:null', { + kind: 'scalar', + resolve: resolveYamlNull, + construct: constructYamlNull, + predicate: isNull, + represent: { + canonical: function () { return '~'; }, + lowercase: function () { return 'null'; }, + uppercase: function () { return 'NULL'; }, + camelcase: function () { return 'Null'; } + }, + defaultStyle: 'lowercase' +}); diff --git a/scripts/node_modules/js-yaml/lib/js-yaml/type/omap.js b/scripts/node_modules/js-yaml/lib/js-yaml/type/omap.js new file mode 100644 index 000000000..b2b5323bd --- /dev/null +++ b/scripts/node_modules/js-yaml/lib/js-yaml/type/omap.js @@ -0,0 +1,44 @@ +'use strict'; + +var Type = require('../type'); + +var _hasOwnProperty = Object.prototype.hasOwnProperty; +var _toString = Object.prototype.toString; + +function resolveYamlOmap(data) { + if (data === null) return true; + + var objectKeys = [], index, length, pair, pairKey, pairHasKey, + object = data; + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + pairHasKey = false; + + if (_toString.call(pair) !== '[object Object]') return false; + + for (pairKey in pair) { + if (_hasOwnProperty.call(pair, pairKey)) { + if (!pairHasKey) pairHasKey = true; + else return false; + } + } + + if (!pairHasKey) return false; + + if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); + else return false; + } + + return true; +} + +function constructYamlOmap(data) { + return data !== null ? data : []; +} + +module.exports = new Type('tag:yaml.org,2002:omap', { + kind: 'sequence', + resolve: resolveYamlOmap, + construct: constructYamlOmap +}); diff --git a/scripts/node_modules/js-yaml/lib/js-yaml/type/pairs.js b/scripts/node_modules/js-yaml/lib/js-yaml/type/pairs.js new file mode 100644 index 000000000..74b52403f --- /dev/null +++ b/scripts/node_modules/js-yaml/lib/js-yaml/type/pairs.js @@ -0,0 +1,53 @@ +'use strict'; + +var Type = require('../type'); + +var _toString = Object.prototype.toString; + +function resolveYamlPairs(data) { + if (data === null) return true; + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + if (_toString.call(pair) !== '[object Object]') return false; + + keys = Object.keys(pair); + + if (keys.length !== 1) return false; + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return true; +} + +function constructYamlPairs(data) { + if (data === null) return []; + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + keys = Object.keys(pair); + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return result; +} + +module.exports = new Type('tag:yaml.org,2002:pairs', { + kind: 'sequence', + resolve: resolveYamlPairs, + construct: constructYamlPairs +}); diff --git a/scripts/node_modules/js-yaml/lib/js-yaml/type/seq.js b/scripts/node_modules/js-yaml/lib/js-yaml/type/seq.js new file mode 100644 index 000000000..be8f77f28 --- /dev/null +++ b/scripts/node_modules/js-yaml/lib/js-yaml/type/seq.js @@ -0,0 +1,8 @@ +'use strict'; + +var Type = require('../type'); + +module.exports = new Type('tag:yaml.org,2002:seq', { + kind: 'sequence', + construct: function (data) { return data !== null ? data : []; } +}); diff --git a/scripts/node_modules/js-yaml/lib/js-yaml/type/set.js b/scripts/node_modules/js-yaml/lib/js-yaml/type/set.js new file mode 100644 index 000000000..f885a329c --- /dev/null +++ b/scripts/node_modules/js-yaml/lib/js-yaml/type/set.js @@ -0,0 +1,29 @@ +'use strict'; + +var Type = require('../type'); + +var _hasOwnProperty = Object.prototype.hasOwnProperty; + +function resolveYamlSet(data) { + if (data === null) return true; + + var key, object = data; + + for (key in object) { + if (_hasOwnProperty.call(object, key)) { + if (object[key] !== null) return false; + } + } + + return true; +} + +function constructYamlSet(data) { + return data !== null ? data : {}; +} + +module.exports = new Type('tag:yaml.org,2002:set', { + kind: 'mapping', + resolve: resolveYamlSet, + construct: constructYamlSet +}); diff --git a/scripts/node_modules/js-yaml/lib/js-yaml/type/str.js b/scripts/node_modules/js-yaml/lib/js-yaml/type/str.js new file mode 100644 index 000000000..27acc106c --- /dev/null +++ b/scripts/node_modules/js-yaml/lib/js-yaml/type/str.js @@ -0,0 +1,8 @@ +'use strict'; + +var Type = require('../type'); + +module.exports = new Type('tag:yaml.org,2002:str', { + kind: 'scalar', + construct: function (data) { return data !== null ? data : ''; } +}); diff --git a/scripts/node_modules/js-yaml/lib/js-yaml/type/timestamp.js b/scripts/node_modules/js-yaml/lib/js-yaml/type/timestamp.js new file mode 100644 index 000000000..8fa9c5865 --- /dev/null +++ b/scripts/node_modules/js-yaml/lib/js-yaml/type/timestamp.js @@ -0,0 +1,88 @@ +'use strict'; + +var Type = require('../type'); + +var YAML_DATE_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9])' + // [2] month + '-([0-9][0-9])$'); // [3] day + +var YAML_TIMESTAMP_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9]?)' + // [2] month + '-([0-9][0-9]?)' + // [3] day + '(?:[Tt]|[ \\t]+)' + // ... + '([0-9][0-9]?)' + // [4] hour + ':([0-9][0-9])' + // [5] minute + ':([0-9][0-9])' + // [6] second + '(?:\\.([0-9]*))?' + // [7] fraction + '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour + '(?::([0-9][0-9]))?))?$'); // [11] tz_minute + +function resolveYamlTimestamp(data) { + if (data === null) return false; + if (YAML_DATE_REGEXP.exec(data) !== null) return true; + if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; + return false; +} + +function constructYamlTimestamp(data) { + var match, year, month, day, hour, minute, second, fraction = 0, + delta = null, tz_hour, tz_minute, date; + + match = YAML_DATE_REGEXP.exec(data); + if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); + + if (match === null) throw new Error('Date resolve error'); + + // match: [1] year [2] month [3] day + + year = +(match[1]); + month = +(match[2]) - 1; // JS month starts with 0 + day = +(match[3]); + + if (!match[4]) { // no hour + return new Date(Date.UTC(year, month, day)); + } + + // match: [4] hour [5] minute [6] second [7] fraction + + hour = +(match[4]); + minute = +(match[5]); + second = +(match[6]); + + if (match[7]) { + fraction = match[7].slice(0, 3); + while (fraction.length < 3) { // milli-seconds + fraction += '0'; + } + fraction = +fraction; + } + + // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute + + if (match[9]) { + tz_hour = +(match[10]); + tz_minute = +(match[11] || 0); + delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds + if (match[9] === '-') delta = -delta; + } + + date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); + + if (delta) date.setTime(date.getTime() - delta); + + return date; +} + +function representYamlTimestamp(object /*, style*/) { + return object.toISOString(); +} + +module.exports = new Type('tag:yaml.org,2002:timestamp', { + kind: 'scalar', + resolve: resolveYamlTimestamp, + construct: constructYamlTimestamp, + instanceOf: Date, + represent: representYamlTimestamp +}); diff --git a/scripts/node_modules/js-yaml/package.json b/scripts/node_modules/js-yaml/package.json new file mode 100644 index 000000000..0d2366762 --- /dev/null +++ b/scripts/node_modules/js-yaml/package.json @@ -0,0 +1,49 @@ +{ + "name": "js-yaml", + "version": "3.14.1", + "description": "YAML 1.2 parser and serializer", + "keywords": [ + "yaml", + "parser", + "serializer", + "pyyaml" + ], + "homepage": "https://github.com/nodeca/js-yaml", + "author": "Vladimir Zapparov ", + "contributors": [ + "Aleksey V Zapparov (http://www.ixti.net/)", + "Vitaly Puzrin (https://github.com/puzrin)", + "Martin Grenfell (http://got-ravings.blogspot.com)" + ], + "license": "MIT", + "repository": "nodeca/js-yaml", + "files": [ + "index.js", + "lib/", + "bin/", + "dist/" + ], + "bin": { + "js-yaml": "bin/js-yaml.js" + }, + "unpkg": "dist/js-yaml.min.js", + "jsdelivr": "dist/js-yaml.min.js", + "dependencies": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + }, + "devDependencies": { + "ansi": "^0.3.1", + "benchmark": "^2.1.4", + "browserify": "^16.2.2", + "codemirror": "^5.13.4", + "eslint": "^7.0.0", + "fast-check": "^1.24.2", + "istanbul": "^0.4.5", + "mocha": "^7.1.2", + "uglify-js": "^3.0.1" + }, + "scripts": { + "test": "make test" + } +} diff --git a/scripts/node_modules/kind-of/CHANGELOG.md b/scripts/node_modules/kind-of/CHANGELOG.md new file mode 100644 index 000000000..01687d5cb --- /dev/null +++ b/scripts/node_modules/kind-of/CHANGELOG.md @@ -0,0 +1,160 @@ +# Release history + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). + +
+ Guiding Principles + +- Changelogs are for humans, not machines. +- There should be an entry for every single version. +- The same types of changes should be grouped. +- Versions and sections should be linkable. +- The latest version comes first. +- The release date of each versions is displayed. +- Mention whether you follow Semantic Versioning. + +
+ +
+ Types of changes + +Changelog entries are classified using the following labels _(from [keep-a-changelog](http://keepachangelog.com/)_): + +- `Added` for new features. +- `Changed` for changes in existing functionality. +- `Deprecated` for soon-to-be removed features. +- `Removed` for now removed features. +- `Fixed` for any bug fixes. +- `Security` in case of vulnerabilities. + +
+ +## [6.0.3] - 2020-01-16 + +- Merge pull request #31 for issue #30 + +## [6.0.0] - 2017-10-13 + +- refactor code to be more performant +- refactor benchmarks + +## [5.1.0] - 2017-10-13 + +**Added** + +- Merge pull request #15 from aretecode/patch-1 +- adds support and tests for string & array iterators + +**Changed** + +- updates benchmarks + +## [5.0.2] - 2017-08-02 + +- Merge pull request #14 from struct78/master +- Added `undefined` check + +## [5.0.0] - 2017-06-21 + +- Merge pull request #12 from aretecode/iterator +- Set Iterator + Map Iterator +- streamline `isbuffer`, minor edits + +## [4.0.0] - 2017-05-19 + +- Merge pull request #8 from tunnckoCore/master +- update deps + +## [3.2.2] - 2017-05-16 + +- fix version + +## [3.2.1] - 2017-05-16 + +- add browserify + +## [3.2.0] - 2017-04-25 + +- Merge pull request #10 from ksheedlo/unrequire-buffer +- add `promise` support and tests +- Remove unnecessary `Buffer` check + +## [3.1.0] - 2016-12-07 + +- Merge pull request #7 from laggingreflex/err +- add support for `error` and tests +- run update + +## [3.0.4] - 2016-07-29 + +- move tests +- run update + +## [3.0.3] - 2016-05-03 + +- fix prepublish script +- remove unused dep + +## [3.0.0] - 2015-11-17 + +- add typed array support +- Merge pull request #5 from miguelmota/typed-arrays +- adds new tests + +## [2.0.1] - 2015-08-21 + +- use `is-buffer` module + +## [2.0.0] - 2015-05-31 + +- Create fallback for `Array.isArray` if used as a browser package +- Merge pull request #2 from dtothefp/patch-1 +- Merge pull request #3 from pdehaan/patch-1 +- Merge branch 'master' of https://github.com/chorks/kind-of into chorks-master +- optimizations, mostly date and regex + +## [1.1.0] - 2015-02-09 + +- adds `buffer` support +- adds tests for `buffer` + +## [1.0.0] - 2015-01-19 + +- update benchmarks +- optimizations based on benchmarks + +## [0.1.2] - 2014-10-26 + +- return `typeof` value if it's not an object. very slight speed improvement +- use `.slice` +- adds benchmarks + +## [0.1.0] - 2014-9-26 + +- first commit + +[6.0.0]: https://github.com/jonschlinkert/kind-of/compare/5.1.0...6.0.0 +[5.1.0]: https://github.com/jonschlinkert/kind-of/compare/5.0.2...5.1.0 +[5.0.2]: https://github.com/jonschlinkert/kind-of/compare/5.0.1...5.0.2 +[5.0.1]: https://github.com/jonschlinkert/kind-of/compare/5.0.0...5.0.1 +[5.0.0]: https://github.com/jonschlinkert/kind-of/compare/4.0.0...5.0.0 +[4.0.0]: https://github.com/jonschlinkert/kind-of/compare/3.2.2...4.0.0 +[3.2.2]: https://github.com/jonschlinkert/kind-of/compare/3.2.1...3.2.2 +[3.2.1]: https://github.com/jonschlinkert/kind-of/compare/3.2.0...3.2.1 +[3.2.0]: https://github.com/jonschlinkert/kind-of/compare/3.1.0...3.2.0 +[3.1.0]: https://github.com/jonschlinkert/kind-of/compare/3.0.4...3.1.0 +[3.0.4]: https://github.com/jonschlinkert/kind-of/compare/3.0.3...3.0.4 +[3.0.3]: https://github.com/jonschlinkert/kind-of/compare/3.0.0...3.0.3 +[3.0.0]: https://github.com/jonschlinkert/kind-of/compare/2.0.1...3.0.0 +[2.0.1]: https://github.com/jonschlinkert/kind-of/compare/2.0.0...2.0.1 +[2.0.0]: https://github.com/jonschlinkert/kind-of/compare/1.1.0...2.0.0 +[1.1.0]: https://github.com/jonschlinkert/kind-of/compare/1.0.0...1.1.0 +[1.0.0]: https://github.com/jonschlinkert/kind-of/compare/0.1.2...1.0.0 +[0.1.2]: https://github.com/jonschlinkert/kind-of/compare/0.1.0...0.1.2 +[0.1.0]: https://github.com/jonschlinkert/kind-of/commit/2fae09b0b19b1aadb558e9be39f0c3ef6034eb87 + +[Unreleased]: https://github.com/jonschlinkert/kind-of/compare/0.1.2...HEAD +[keep-a-changelog]: https://github.com/olivierlacan/keep-a-changelog \ No newline at end of file diff --git a/scripts/node_modules/kind-of/LICENSE b/scripts/node_modules/kind-of/LICENSE new file mode 100644 index 000000000..3f2eca18f --- /dev/null +++ b/scripts/node_modules/kind-of/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2017, Jon Schlinkert. + +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/scripts/node_modules/kind-of/README.md b/scripts/node_modules/kind-of/README.md new file mode 100644 index 000000000..0411dc58a --- /dev/null +++ b/scripts/node_modules/kind-of/README.md @@ -0,0 +1,367 @@ +# kind-of [![NPM version](https://img.shields.io/npm/v/kind-of.svg?style=flat)](https://www.npmjs.com/package/kind-of) [![NPM monthly downloads](https://img.shields.io/npm/dm/kind-of.svg?style=flat)](https://npmjs.org/package/kind-of) [![NPM total downloads](https://img.shields.io/npm/dt/kind-of.svg?style=flat)](https://npmjs.org/package/kind-of) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/kind-of.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/kind-of) + +> Get the native type of a value. + +Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. + +## Install + +Install with [npm](https://www.npmjs.com/): + +```sh +$ npm install --save kind-of +``` + +Install with [bower](https://bower.io/) + +```sh +$ bower install kind-of --save +``` + +## Why use this? + +1. [it's fast](#benchmarks) | [optimizations](#optimizations) +2. [better type checking](#better-type-checking) + +## Usage + +> es5, es6, and browser ready + +```js +var kindOf = require('kind-of'); + +kindOf(undefined); +//=> 'undefined' + +kindOf(null); +//=> 'null' + +kindOf(true); +//=> 'boolean' + +kindOf(false); +//=> 'boolean' + +kindOf(new Buffer('')); +//=> 'buffer' + +kindOf(42); +//=> 'number' + +kindOf('str'); +//=> 'string' + +kindOf(arguments); +//=> 'arguments' + +kindOf({}); +//=> 'object' + +kindOf(Object.create(null)); +//=> 'object' + +kindOf(new Test()); +//=> 'object' + +kindOf(new Date()); +//=> 'date' + +kindOf([1, 2, 3]); +//=> 'array' + +kindOf(/foo/); +//=> 'regexp' + +kindOf(new RegExp('foo')); +//=> 'regexp' + +kindOf(new Error('error')); +//=> 'error' + +kindOf(function () {}); +//=> 'function' + +kindOf(function * () {}); +//=> 'generatorfunction' + +kindOf(Symbol('str')); +//=> 'symbol' + +kindOf(new Map()); +//=> 'map' + +kindOf(new WeakMap()); +//=> 'weakmap' + +kindOf(new Set()); +//=> 'set' + +kindOf(new WeakSet()); +//=> 'weakset' + +kindOf(new Int8Array()); +//=> 'int8array' + +kindOf(new Uint8Array()); +//=> 'uint8array' + +kindOf(new Uint8ClampedArray()); +//=> 'uint8clampedarray' + +kindOf(new Int16Array()); +//=> 'int16array' + +kindOf(new Uint16Array()); +//=> 'uint16array' + +kindOf(new Int32Array()); +//=> 'int32array' + +kindOf(new Uint32Array()); +//=> 'uint32array' + +kindOf(new Float32Array()); +//=> 'float32array' + +kindOf(new Float64Array()); +//=> 'float64array' +``` + +## Benchmarks + +Benchmarked against [typeof](http://github.com/CodingFu/typeof) and [type-of](https://github.com/ForbesLindesay/type-of). + +```bash +# arguments (32 bytes) + kind-of x 17,024,098 ops/sec ±1.90% (86 runs sampled) + lib-type-of x 11,926,235 ops/sec ±1.34% (83 runs sampled) + lib-typeof x 9,245,257 ops/sec ±1.22% (87 runs sampled) + + fastest is kind-of (by 161% avg) + +# array (22 bytes) + kind-of x 17,196,492 ops/sec ±1.07% (88 runs sampled) + lib-type-of x 8,838,283 ops/sec ±1.02% (87 runs sampled) + lib-typeof x 8,677,848 ops/sec ±0.87% (87 runs sampled) + + fastest is kind-of (by 196% avg) + +# boolean (24 bytes) + kind-of x 16,841,600 ops/sec ±1.10% (86 runs sampled) + lib-type-of x 8,096,787 ops/sec ±0.95% (87 runs sampled) + lib-typeof x 8,423,345 ops/sec ±1.15% (86 runs sampled) + + fastest is kind-of (by 204% avg) + +# buffer (38 bytes) + kind-of x 14,848,060 ops/sec ±1.05% (86 runs sampled) + lib-type-of x 3,671,577 ops/sec ±1.49% (87 runs sampled) + lib-typeof x 8,360,236 ops/sec ±1.24% (86 runs sampled) + + fastest is kind-of (by 247% avg) + +# date (30 bytes) + kind-of x 16,067,761 ops/sec ±1.58% (86 runs sampled) + lib-type-of x 8,954,436 ops/sec ±1.40% (87 runs sampled) + lib-typeof x 8,488,307 ops/sec ±1.51% (84 runs sampled) + + fastest is kind-of (by 184% avg) + +# error (36 bytes) + kind-of x 9,634,090 ops/sec ±1.12% (89 runs sampled) + lib-type-of x 7,735,624 ops/sec ±1.32% (86 runs sampled) + lib-typeof x 7,442,160 ops/sec ±1.11% (90 runs sampled) + + fastest is kind-of (by 127% avg) + +# function (34 bytes) + kind-of x 10,031,494 ops/sec ±1.27% (86 runs sampled) + lib-type-of x 9,502,757 ops/sec ±1.17% (89 runs sampled) + lib-typeof x 8,278,985 ops/sec ±1.08% (88 runs sampled) + + fastest is kind-of (by 113% avg) + +# null (24 bytes) + kind-of x 18,159,808 ops/sec ±1.92% (86 runs sampled) + lib-type-of x 12,927,635 ops/sec ±1.01% (88 runs sampled) + lib-typeof x 7,958,234 ops/sec ±1.21% (89 runs sampled) + + fastest is kind-of (by 174% avg) + +# number (22 bytes) + kind-of x 17,846,779 ops/sec ±0.91% (85 runs sampled) + lib-type-of x 3,316,636 ops/sec ±1.19% (86 runs sampled) + lib-typeof x 2,329,477 ops/sec ±2.21% (85 runs sampled) + + fastest is kind-of (by 632% avg) + +# object-plain (47 bytes) + kind-of x 7,085,155 ops/sec ±1.05% (88 runs sampled) + lib-type-of x 8,870,930 ops/sec ±1.06% (83 runs sampled) + lib-typeof x 8,716,024 ops/sec ±1.05% (87 runs sampled) + + fastest is lib-type-of (by 112% avg) + +# regex (25 bytes) + kind-of x 14,196,052 ops/sec ±1.65% (84 runs sampled) + lib-type-of x 9,554,164 ops/sec ±1.25% (88 runs sampled) + lib-typeof x 8,359,691 ops/sec ±1.07% (87 runs sampled) + + fastest is kind-of (by 158% avg) + +# string (33 bytes) + kind-of x 16,131,428 ops/sec ±1.41% (85 runs sampled) + lib-type-of x 7,273,172 ops/sec ±1.05% (87 runs sampled) + lib-typeof x 7,382,635 ops/sec ±1.17% (85 runs sampled) + + fastest is kind-of (by 220% avg) + +# symbol (34 bytes) + kind-of x 17,011,537 ops/sec ±1.24% (86 runs sampled) + lib-type-of x 3,492,454 ops/sec ±1.23% (89 runs sampled) + lib-typeof x 7,471,235 ops/sec ±2.48% (87 runs sampled) + + fastest is kind-of (by 310% avg) + +# template-strings (36 bytes) + kind-of x 15,434,250 ops/sec ±1.46% (83 runs sampled) + lib-type-of x 7,157,907 ops/sec ±0.97% (87 runs sampled) + lib-typeof x 7,517,986 ops/sec ±0.92% (86 runs sampled) + + fastest is kind-of (by 210% avg) + +# undefined (29 bytes) + kind-of x 19,167,115 ops/sec ±1.71% (87 runs sampled) + lib-type-of x 15,477,740 ops/sec ±1.63% (85 runs sampled) + lib-typeof x 19,075,495 ops/sec ±1.17% (83 runs sampled) + + fastest is lib-typeof,kind-of + +``` + +## Optimizations + +In 7 out of 8 cases, this library is 2x-10x faster than other top libraries included in the benchmarks. There are a few things that lead to this performance advantage, none of them hard and fast rules, but all of them simple and repeatable in almost any code library: + +1. Optimize around the fastest and most common use cases first. Of course, this will change from project-to-project, but I took some time to understand how and why `typeof` checks were being used in my own libraries and other libraries I use a lot. +2. Optimize around bottlenecks - In other words, the order in which conditionals are implemented is significant, because each check is only as fast as the failing checks that came before it. Here, the biggest bottleneck by far is checking for plain objects (an object that was created by the `Object` constructor). I opted to make this check happen by process of elimination rather than brute force up front (e.g. by using something like `val.constructor.name`), so that every other type check would not be penalized it. +3. Don't do uneccessary processing - why do `.slice(8, -1).toLowerCase();` just to get the word `regex`? It's much faster to do `if (type === '[object RegExp]') return 'regex'` +4. There is no reason to make the code in a microlib as terse as possible, just to win points for making it shorter. It's always better to favor performant code over terse code. You will always only be using a single `require()` statement to use the library anyway, regardless of how the code is written. + +## Better type checking + +kind-of seems to be more consistently "correct" than other type checking libs I've looked at. For example, here are some differing results from other popular libs: + +### [typeof](https://github.com/CodingFu/typeof) lib + +Incorrectly identifies instances of custom constructors (pretty common): + +```js +var typeOf = require('typeof'); +function Test() {} +console.log(typeOf(new Test())); +//=> 'test' +``` + +Returns `object` instead of `arguments`: + +```js +function foo() { + console.log(typeOf(arguments)) //=> 'object' +} +foo(); +``` + +### [type-of](https://github.com/ForbesLindesay/type-of) lib + +Incorrectly returns `object` for generator functions, buffers, `Map`, `Set`, `WeakMap` and `WeakSet`: + +```js +function * foo() {} +console.log(typeOf(foo)); +//=> 'object' +console.log(typeOf(new Buffer(''))); +//=> 'object' +console.log(typeOf(new Map())); +//=> 'object' +console.log(typeOf(new Set())); +//=> 'object' +console.log(typeOf(new WeakMap())); +//=> 'object' +console.log(typeOf(new WeakSet())); +//=> 'object' +``` + +## About + +
+Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +
+ +
+Running Tests + +Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: + +```sh +$ npm install && npm test +``` + +
+ +
+Building docs + +_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ + +To generate the readme, run the following command: + +```sh +$ npm install -g verbose/verb#dev verb-generate-readme && verb +``` + +
+ +### Related projects + +You might also be interested in these projects: + +* [is-glob](https://www.npmjs.com/package/is-glob): Returns `true` if the given string looks like a glob pattern or an extglob pattern… [more](https://github.com/micromatch/is-glob) | [homepage](https://github.com/micromatch/is-glob "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a bet") +* [is-number](https://www.npmjs.com/package/is-number): Returns true if a number or string value is a finite number. Useful for regex… [more](https://github.com/jonschlinkert/is-number) | [homepage](https://github.com/jonschlinkert/is-number "Returns true if a number or string value is a finite number. Useful for regex matches, parsing, user input, etc.") +* [is-primitive](https://www.npmjs.com/package/is-primitive): Returns `true` if the value is a primitive. | [homepage](https://github.com/jonschlinkert/is-primitive "Returns `true` if the value is a primitive. ") + +### Contributors + +| **Commits** | **Contributor** | +| --- | --- | +| 102 | [jonschlinkert](https://github.com/jonschlinkert) | +| 3 | [aretecode](https://github.com/aretecode) | +| 2 | [miguelmota](https://github.com/miguelmota) | +| 1 | [doowb](https://github.com/doowb) | +| 1 | [dtothefp](https://github.com/dtothefp) | +| 1 | [ianstormtaylor](https://github.com/ianstormtaylor) | +| 1 | [ksheedlo](https://github.com/ksheedlo) | +| 1 | [pdehaan](https://github.com/pdehaan) | +| 1 | [laggingreflex](https://github.com/laggingreflex) | +| 1 | [tunnckoCore](https://github.com/tunnckoCore) | +| 1 | [xiaofen9](https://github.com/xiaofen9) | + +### Author + +**Jon Schlinkert** + +* [GitHub Profile](https://github.com/jonschlinkert) +* [Twitter Profile](https://twitter.com/jonschlinkert) +* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) + +### License + +Copyright © 2020, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT License](LICENSE). + +*** + +_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on January 16, 2020._ \ No newline at end of file diff --git a/scripts/node_modules/kind-of/index.js b/scripts/node_modules/kind-of/index.js new file mode 100644 index 000000000..dfa799b78 --- /dev/null +++ b/scripts/node_modules/kind-of/index.js @@ -0,0 +1,129 @@ +var toString = Object.prototype.toString; + +module.exports = function kindOf(val) { + if (val === void 0) return 'undefined'; + if (val === null) return 'null'; + + var type = typeof val; + if (type === 'boolean') return 'boolean'; + if (type === 'string') return 'string'; + if (type === 'number') return 'number'; + if (type === 'symbol') return 'symbol'; + if (type === 'function') { + return isGeneratorFn(val) ? 'generatorfunction' : 'function'; + } + + if (isArray(val)) return 'array'; + if (isBuffer(val)) return 'buffer'; + if (isArguments(val)) return 'arguments'; + if (isDate(val)) return 'date'; + if (isError(val)) return 'error'; + if (isRegexp(val)) return 'regexp'; + + switch (ctorName(val)) { + case 'Symbol': return 'symbol'; + case 'Promise': return 'promise'; + + // Set, Map, WeakSet, WeakMap + case 'WeakMap': return 'weakmap'; + case 'WeakSet': return 'weakset'; + case 'Map': return 'map'; + case 'Set': return 'set'; + + // 8-bit typed arrays + case 'Int8Array': return 'int8array'; + case 'Uint8Array': return 'uint8array'; + case 'Uint8ClampedArray': return 'uint8clampedarray'; + + // 16-bit typed arrays + case 'Int16Array': return 'int16array'; + case 'Uint16Array': return 'uint16array'; + + // 32-bit typed arrays + case 'Int32Array': return 'int32array'; + case 'Uint32Array': return 'uint32array'; + case 'Float32Array': return 'float32array'; + case 'Float64Array': return 'float64array'; + } + + if (isGeneratorObj(val)) { + return 'generator'; + } + + // Non-plain objects + type = toString.call(val); + switch (type) { + case '[object Object]': return 'object'; + // iterators + case '[object Map Iterator]': return 'mapiterator'; + case '[object Set Iterator]': return 'setiterator'; + case '[object String Iterator]': return 'stringiterator'; + case '[object Array Iterator]': return 'arrayiterator'; + } + + // other + return type.slice(8, -1).toLowerCase().replace(/\s/g, ''); +}; + +function ctorName(val) { + return typeof val.constructor === 'function' ? val.constructor.name : null; +} + +function isArray(val) { + if (Array.isArray) return Array.isArray(val); + return val instanceof Array; +} + +function isError(val) { + return val instanceof Error || (typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number'); +} + +function isDate(val) { + if (val instanceof Date) return true; + return typeof val.toDateString === 'function' + && typeof val.getDate === 'function' + && typeof val.setDate === 'function'; +} + +function isRegexp(val) { + if (val instanceof RegExp) return true; + return typeof val.flags === 'string' + && typeof val.ignoreCase === 'boolean' + && typeof val.multiline === 'boolean' + && typeof val.global === 'boolean'; +} + +function isGeneratorFn(name, val) { + return ctorName(name) === 'GeneratorFunction'; +} + +function isGeneratorObj(val) { + return typeof val.throw === 'function' + && typeof val.return === 'function' + && typeof val.next === 'function'; +} + +function isArguments(val) { + try { + if (typeof val.length === 'number' && typeof val.callee === 'function') { + return true; + } + } catch (err) { + if (err.message.indexOf('callee') !== -1) { + return true; + } + } + return false; +} + +/** + * If you need to support Safari 5-7 (8-10 yr-old browser), + * take a look at https://github.com/feross/is-buffer + */ + +function isBuffer(val) { + if (val.constructor && typeof val.constructor.isBuffer === 'function') { + return val.constructor.isBuffer(val); + } + return false; +} diff --git a/scripts/node_modules/kind-of/package.json b/scripts/node_modules/kind-of/package.json new file mode 100644 index 000000000..5820cad23 --- /dev/null +++ b/scripts/node_modules/kind-of/package.json @@ -0,0 +1,88 @@ +{ + "name": "kind-of", + "description": "Get the native type of a value.", + "version": "6.0.3", + "homepage": "https://github.com/jonschlinkert/kind-of", + "author": "Jon Schlinkert (https://github.com/jonschlinkert)", + "contributors": [ + "David Fox-Powell (https://dtothefp.github.io/me)", + "James (https://twitter.com/aretecode)", + "Jon Schlinkert (http://twitter.com/jonschlinkert)", + "Ken Sheedlo (kensheedlo.com)", + "laggingreflex (https://github.com/laggingreflex)", + "Miguel Mota (https://miguelmota.com)", + "Peter deHaan (http://about.me/peterdehaan)", + "tunnckoCore (https://i.am.charlike.online)" + ], + "repository": "jonschlinkert/kind-of", + "bugs": { + "url": "https://github.com/jonschlinkert/kind-of/issues" + }, + "license": "MIT", + "files": [ + "index.js" + ], + "main": "index.js", + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "mocha", + "prepublish": "browserify -o browser.js -e index.js -s index --bare" + }, + "devDependencies": { + "benchmarked": "^2.0.0", + "browserify": "^14.4.0", + "gulp-format-md": "^1.0.0", + "mocha": "^4.0.1", + "write": "^1.0.3" + }, + "keywords": [ + "arguments", + "array", + "boolean", + "check", + "date", + "function", + "is", + "is-type", + "is-type-of", + "kind", + "kind-of", + "number", + "object", + "of", + "regexp", + "string", + "test", + "type", + "type-of", + "typeof", + "types" + ], + "verb": { + "toc": false, + "layout": "default", + "tasks": [ + "readme" + ], + "plugins": [ + "gulp-format-md" + ], + "lint": { + "reflinks": true + }, + "related": { + "list": [ + "is-glob", + "is-number", + "is-primitive" + ] + }, + "reflinks": [ + "type-of", + "typeof", + "verb" + ] + } +} diff --git a/scripts/node_modules/marked/LICENSE.md b/scripts/node_modules/marked/LICENSE.md new file mode 100644 index 000000000..4bd2d4a08 --- /dev/null +++ b/scripts/node_modules/marked/LICENSE.md @@ -0,0 +1,44 @@ +# License information + +## Contribution License Agreement + +If you contribute code to this project, you are implicitly allowing your code +to be distributed under the MIT license. You are also implicitly verifying that +all code is your original work. `` + +## Marked + +Copyright (c) 2018+, MarkedJS (https://github.com/markedjs/) +Copyright (c) 2011-2018, Christopher Jeffrey (https://github.com/chjj/) + +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. + +## Markdown + +Copyright © 2004, John Gruber +http://daringfireball.net/ +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. +* Neither the name “Markdown” nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +This software is provided by the copyright holders and contributors “as is” and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall the copyright owner or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage. diff --git a/scripts/node_modules/marked/README.md b/scripts/node_modules/marked/README.md new file mode 100644 index 000000000..d4ab25129 --- /dev/null +++ b/scripts/node_modules/marked/README.md @@ -0,0 +1,107 @@ + + + + +# Marked + +[![npm](https://badgen.net/npm/v/marked)](https://www.npmjs.com/package/marked) +[![gzip size](https://badgen.net/badgesize/gzip/https://cdn.jsdelivr.net/npm/marked/marked.min.js)](https://cdn.jsdelivr.net/npm/marked/marked.min.js) +[![install size](https://badgen.net/packagephobia/install/marked)](https://packagephobia.now.sh/result?p=marked) +[![downloads](https://badgen.net/npm/dt/marked)](https://www.npmjs.com/package/marked) +[![github actions](https://github.com/markedjs/marked/workflows/Tests/badge.svg)](https://github.com/markedjs/marked/actions) +[![snyk](https://snyk.io/test/npm/marked/badge.svg)](https://snyk.io/test/npm/marked) + +- ⚡ built for speed +- ⬇️ low-level compiler for parsing markdown without caching or blocking for long periods of time +- ⚖️ light-weight while implementing all markdown features from the supported flavors & specifications +- 🌐 works in a browser, on a server, or from a command line interface (CLI) + +## Demo + +Checkout the [demo page](https://marked.js.org/demo/) to see marked in action ⛹️ + +## Docs + +Our [documentation pages](https://marked.js.org) are also rendered using marked 💯 + +Also read about: + +* [Options](https://marked.js.org/using_advanced) +* [Extensibility](https://marked.js.org/using_pro) + +## Compatibility + +**Node.js:** Only [current and LTS](https://nodejs.org/en/about/releases/) Node.js versions are supported. End of life Node.js versions may become incompatible with Marked at any point in time. + +**Browser:** Not IE11 :) + +## Installation + +**CLI:** + +```sh +npm install -g marked +``` + +**In-browser:** + +```sh +npm install marked +``` + +## Usage + +### Warning: 🚨 Marked does not [sanitize](https://marked.js.org/using_advanced#options) the output HTML. Please use a sanitize library, like [DOMPurify](https://github.com/cure53/DOMPurify) (recommended), [sanitize-html](https://github.com/apostrophecms/sanitize-html) or [insane](https://github.com/bevacqua/insane) on the *output* HTML! 🚨 + +``` +DOMPurify.sanitize(marked.parse(``)); +``` + +**CLI** + +``` bash +# Example with stdin input +$ marked -o hello.html +hello world +^D +$ cat hello.html +

hello world

+``` + +```bash +# Print all options +$ marked --help +``` + +**Browser** + +```html + + + + + Marked in the browser + + +
+ + + + +``` +or import esm module + +```html + +``` + +## License + +Copyright (c) 2011-2022, Christopher Jeffrey. (MIT License) diff --git a/scripts/node_modules/marked/bin/main.js b/scripts/node_modules/marked/bin/main.js new file mode 100644 index 000000000..758ef56ad --- /dev/null +++ b/scripts/node_modules/marked/bin/main.js @@ -0,0 +1,279 @@ +#!/usr/bin/env node + +/** + * Marked CLI + * Copyright (c) 2011-2013, Christopher Jeffrey (MIT License) + */ + +import { promises } from 'node:fs'; +import { dirname, resolve } from 'node:path'; +import { homedir } from 'node:os'; +import { createRequire } from 'node:module'; +import { marked } from '../lib/marked.esm.js'; + +const { access, readFile, writeFile } = promises; +const require = createRequire(import.meta.url); + +/** + * @param {Process} nodeProcess inject process so it can be mocked in tests. + */ +export async function main(nodeProcess) { + /** + * Man Page + */ + async function help() { + const { spawn } = await import('child_process'); + const { fileURLToPath } = await import('url'); + + const options = { + cwd: nodeProcess.cwd(), + env: nodeProcess.env, + stdio: 'inherit' + }; + + const __dirname = dirname(fileURLToPath(import.meta.url)); + const helpText = await readFile(resolve(__dirname, '../man/marked.1.md'), 'utf8'); + + // eslint-disable-next-line promise/param-names + await new Promise(res => { + spawn('man', [resolve(__dirname, '../man/marked.1')], options) + .on('error', () => { + console.log(helpText); + }) + .on('close', res); + }); + } + + async function version() { + const pkg = require('../package.json'); + console.log(pkg.version); + } + + /** + * Main + */ + async function start(argv) { + const files = []; + const options = {}; + let input; + let output; + let string; + let arg; + let tokens; + let config; + let opt; + let noclobber; + + function getArg() { + let arg = argv.shift(); + + if (arg.indexOf('--') === 0) { + // e.g. --opt + arg = arg.split('='); + if (arg.length > 1) { + // e.g. --opt=val + argv.unshift(arg.slice(1).join('=')); + } + arg = arg[0]; + } else if (arg[0] === '-') { + if (arg.length > 2) { + // e.g. -abc + argv = arg.substring(1).split('').map(function(ch) { + return '-' + ch; + }).concat(argv); + arg = argv.shift(); + } else { + // e.g. -a + } + } else { + // e.g. foo + } + + return arg; + } + + while (argv.length) { + arg = getArg(); + switch (arg) { + case '-o': + case '--output': + output = argv.shift(); + break; + case '-i': + case '--input': + input = argv.shift(); + break; + case '-s': + case '--string': + string = argv.shift(); + break; + case '-t': + case '--tokens': + tokens = true; + break; + case '-c': + case '--config': + config = argv.shift(); + break; + case '-n': + case '--no-clobber': + noclobber = true; + break; + case '-h': + case '--help': + return await help(); + case '-v': + case '--version': + return await version(); + default: + if (arg.indexOf('--') === 0) { + opt = camelize(arg.replace(/^--(no-)?/, '')); + if (!marked.defaults.hasOwnProperty(opt)) { + continue; + } + if (arg.indexOf('--no-') === 0) { + options[opt] = typeof marked.defaults[opt] !== 'boolean' + ? null + : false; + } else { + options[opt] = typeof marked.defaults[opt] !== 'boolean' + ? argv.shift() + : true; + } + } else { + files.push(arg); + } + break; + } + } + + async function getData() { + if (!input) { + if (files.length <= 2) { + if (string) { + return string; + } + return await getStdin(); + } + input = files.pop(); + } + return await readFile(input, 'utf8'); + } + + function resolveFile(file) { + return resolve(file.replace(/^~/, homedir)); + } + + function fileExists(file) { + return access(resolveFile(file)).then(() => true, () => false); + } + + async function runConfig(file) { + const configFile = resolveFile(file); + let markedConfig; + try { + // try require for json + markedConfig = require(configFile); + } catch (err) { + if (err.code !== 'ERR_REQUIRE_ESM') { + throw err; + } + // must import esm + markedConfig = await import('file:///' + configFile); + } + + if (markedConfig.default) { + markedConfig = markedConfig.default; + } + + if (typeof markedConfig === 'function') { + markedConfig(marked); + } else { + marked.use(markedConfig); + } + } + + const data = await getData(); + + if (config) { + if (!await fileExists(config)) { + throw Error(`Cannot load config file '${config}'`); + } + + await runConfig(config); + } else { + const defaultConfig = [ + '~/.marked.json', + '~/.marked.js', + '~/.marked/index.js' + ]; + + for (const configFile of defaultConfig) { + if (await fileExists(configFile)) { + await runConfig(configFile); + break; + } + } + } + + const html = tokens + ? JSON.stringify(marked.lexer(data, options), null, 2) + : await marked.parse(data, options); + + if (output) { + if (noclobber && await fileExists(output)) { + throw Error('marked: output file \'' + output + '\' already exists, disable the \'-n\' / \'--no-clobber\' flag to overwrite\n'); + } + return await writeFile(output, html); + } + + nodeProcess.stdout.write(html + '\n'); + } + + /** + * Helpers + */ + function getStdin() { + return new Promise((resolve, reject) => { + const stdin = nodeProcess.stdin; + let buff = ''; + + stdin.setEncoding('utf8'); + + stdin.on('data', function(data) { + buff += data; + }); + + stdin.on('error', function(err) { + reject(err); + }); + + stdin.on('end', function() { + resolve(buff); + }); + + stdin.resume(); + }); + } + + /** + * @param {string} text + */ + function camelize(text) { + return text.replace(/(\w)-(\w)/g, function(_, a, b) { + return a + b.toUpperCase(); + }); + } + + try { + await start(nodeProcess.argv.slice()); + nodeProcess.exit(0); + } catch (err) { + if (err.code === 'ENOENT') { + nodeProcess.stderr.write('marked: ' + err.path + ': No such file or directory'); + } else { + nodeProcess.stderr.write(err.message); + } + return nodeProcess.exit(1); + } +} diff --git a/scripts/node_modules/marked/bin/marked.js b/scripts/node_modules/marked/bin/marked.js new file mode 100755 index 000000000..e2dd816f6 --- /dev/null +++ b/scripts/node_modules/marked/bin/marked.js @@ -0,0 +1,15 @@ +#!/usr/bin/env node + +/** + * Marked CLI + * Copyright (c) 2011-2013, Christopher Jeffrey (MIT License) + */ + +import { main } from './main.js'; + +/** + * Expose / Entry Point + */ + +process.title = 'marked'; +main(process); diff --git a/scripts/node_modules/marked/lib/marked.cjs b/scripts/node_modules/marked/lib/marked.cjs new file mode 100644 index 000000000..687e225ba --- /dev/null +++ b/scripts/node_modules/marked/lib/marked.cjs @@ -0,0 +1,2726 @@ +/** + * marked v13.0.1 - a markdown parser + * Copyright (c) 2011-2024, Christopher Jeffrey. (MIT Licensed) + * https://github.com/markedjs/marked + */ + +/** + * DO NOT EDIT THIS FILE + * The code in this file is generated from files in ./src/ + */ + +'use strict'; + +/** + * Gets the original marked default options. + */ +function _getDefaults() { + return { + async: false, + breaks: false, + extensions: null, + gfm: true, + hooks: null, + pedantic: false, + renderer: null, + silent: false, + tokenizer: null, + walkTokens: null + }; +} +exports.defaults = _getDefaults(); +function changeDefaults(newDefaults) { + exports.defaults = newDefaults; +} + +/** + * Helpers + */ +const escapeTest = /[&<>"']/; +const escapeReplace = new RegExp(escapeTest.source, 'g'); +const escapeTestNoEncode = /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/; +const escapeReplaceNoEncode = new RegExp(escapeTestNoEncode.source, 'g'); +const escapeReplacements = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' +}; +const getEscapeReplacement = (ch) => escapeReplacements[ch]; +function escape$1(html, encode) { + if (encode) { + if (escapeTest.test(html)) { + return html.replace(escapeReplace, getEscapeReplacement); + } + } + else { + if (escapeTestNoEncode.test(html)) { + return html.replace(escapeReplaceNoEncode, getEscapeReplacement); + } + } + return html; +} +const unescapeTest = /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig; +function unescape(html) { + // explicitly match decimal, hex, and named HTML entities + return html.replace(unescapeTest, (_, n) => { + n = n.toLowerCase(); + if (n === 'colon') + return ':'; + if (n.charAt(0) === '#') { + return n.charAt(1) === 'x' + ? String.fromCharCode(parseInt(n.substring(2), 16)) + : String.fromCharCode(+n.substring(1)); + } + return ''; + }); +} +const caret = /(^|[^\[])\^/g; +function edit(regex, opt) { + let source = typeof regex === 'string' ? regex : regex.source; + opt = opt || ''; + const obj = { + replace: (name, val) => { + let valSource = typeof val === 'string' ? val : val.source; + valSource = valSource.replace(caret, '$1'); + source = source.replace(name, valSource); + return obj; + }, + getRegex: () => { + return new RegExp(source, opt); + } + }; + return obj; +} +function cleanUrl(href) { + try { + href = encodeURI(href).replace(/%25/g, '%'); + } + catch (e) { + return null; + } + return href; +} +const noopTest = { exec: () => null }; +function splitCells(tableRow, count) { + // ensure that every cell-delimiting pipe has a space + // before it to distinguish it from an escaped pipe + const row = tableRow.replace(/\|/g, (match, offset, str) => { + let escaped = false; + let curr = offset; + while (--curr >= 0 && str[curr] === '\\') + escaped = !escaped; + if (escaped) { + // odd number of slashes means | is escaped + // so we leave it alone + return '|'; + } + else { + // add space before unescaped | + return ' |'; + } + }), cells = row.split(/ \|/); + let i = 0; + // First/last cell in a row cannot be empty if it has no leading/trailing pipe + if (!cells[0].trim()) { + cells.shift(); + } + if (cells.length > 0 && !cells[cells.length - 1].trim()) { + cells.pop(); + } + if (count) { + if (cells.length > count) { + cells.splice(count); + } + else { + while (cells.length < count) + cells.push(''); + } + } + for (; i < cells.length; i++) { + // leading or trailing whitespace is ignored per the gfm spec + cells[i] = cells[i].trim().replace(/\\\|/g, '|'); + } + return cells; +} +/** + * Remove trailing 'c's. Equivalent to str.replace(/c*$/, ''). + * /c*$/ is vulnerable to REDOS. + * + * @param str + * @param c + * @param invert Remove suffix of non-c chars instead. Default falsey. + */ +function rtrim(str, c, invert) { + const l = str.length; + if (l === 0) { + return ''; + } + // Length of suffix matching the invert condition. + let suffLen = 0; + // Step left until we fail to match the invert condition. + while (suffLen < l) { + const currChar = str.charAt(l - suffLen - 1); + if (currChar === c && !invert) { + suffLen++; + } + else if (currChar !== c && invert) { + suffLen++; + } + else { + break; + } + } + return str.slice(0, l - suffLen); +} +function findClosingBracket(str, b) { + if (str.indexOf(b[1]) === -1) { + return -1; + } + let level = 0; + for (let i = 0; i < str.length; i++) { + if (str[i] === '\\') { + i++; + } + else if (str[i] === b[0]) { + level++; + } + else if (str[i] === b[1]) { + level--; + if (level < 0) { + return i; + } + } + } + return -1; +} + +function outputLink(cap, link, raw, lexer) { + const href = link.href; + const title = link.title ? escape$1(link.title) : null; + const text = cap[1].replace(/\\([\[\]])/g, '$1'); + if (cap[0].charAt(0) !== '!') { + lexer.state.inLink = true; + const token = { + type: 'link', + raw, + href, + title, + text, + tokens: lexer.inlineTokens(text) + }; + lexer.state.inLink = false; + return token; + } + return { + type: 'image', + raw, + href, + title, + text: escape$1(text) + }; +} +function indentCodeCompensation(raw, text) { + const matchIndentToCode = raw.match(/^(\s+)(?:```)/); + if (matchIndentToCode === null) { + return text; + } + const indentToCode = matchIndentToCode[1]; + return text + .split('\n') + .map(node => { + const matchIndentInNode = node.match(/^\s+/); + if (matchIndentInNode === null) { + return node; + } + const [indentInNode] = matchIndentInNode; + if (indentInNode.length >= indentToCode.length) { + return node.slice(indentToCode.length); + } + return node; + }) + .join('\n'); +} +/** + * Tokenizer + */ +class _Tokenizer { + options; + rules; // set by the lexer + lexer; // set by the lexer + constructor(options) { + this.options = options || exports.defaults; + } + space(src) { + const cap = this.rules.block.newline.exec(src); + if (cap && cap[0].length > 0) { + return { + type: 'space', + raw: cap[0] + }; + } + } + code(src) { + const cap = this.rules.block.code.exec(src); + if (cap) { + const text = cap[0].replace(/^ {1,4}/gm, ''); + return { + type: 'code', + raw: cap[0], + codeBlockStyle: 'indented', + text: !this.options.pedantic + ? rtrim(text, '\n') + : text + }; + } + } + fences(src) { + const cap = this.rules.block.fences.exec(src); + if (cap) { + const raw = cap[0]; + const text = indentCodeCompensation(raw, cap[3] || ''); + return { + type: 'code', + raw, + lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, '$1') : cap[2], + text + }; + } + } + heading(src) { + const cap = this.rules.block.heading.exec(src); + if (cap) { + let text = cap[2].trim(); + // remove trailing #s + if (/#$/.test(text)) { + const trimmed = rtrim(text, '#'); + if (this.options.pedantic) { + text = trimmed.trim(); + } + else if (!trimmed || / $/.test(trimmed)) { + // CommonMark requires space before trailing #s + text = trimmed.trim(); + } + } + return { + type: 'heading', + raw: cap[0], + depth: cap[1].length, + text, + tokens: this.lexer.inline(text) + }; + } + } + hr(src) { + const cap = this.rules.block.hr.exec(src); + if (cap) { + return { + type: 'hr', + raw: rtrim(cap[0], '\n') + }; + } + } + blockquote(src) { + const cap = this.rules.block.blockquote.exec(src); + if (cap) { + let lines = rtrim(cap[0], '\n').split('\n'); + let raw = ''; + let text = ''; + const tokens = []; + while (lines.length > 0) { + let inBlockquote = false; + const currentLines = []; + let i; + for (i = 0; i < lines.length; i++) { + // get lines up to a continuation + if (/^ {0,3}>/.test(lines[i])) { + currentLines.push(lines[i]); + inBlockquote = true; + } + else if (!inBlockquote) { + currentLines.push(lines[i]); + } + else { + break; + } + } + lines = lines.slice(i); + const currentRaw = currentLines.join('\n'); + const currentText = currentRaw + // precede setext continuation with 4 spaces so it isn't a setext + .replace(/\n {0,3}((?:=+|-+) *)(?=\n|$)/g, '\n $1') + .replace(/^ {0,3}>[ \t]?/gm, ''); + raw = raw ? `${raw}\n${currentRaw}` : currentRaw; + text = text ? `${text}\n${currentText}` : currentText; + // parse blockquote lines as top level tokens + // merge paragraphs if this is a continuation + const top = this.lexer.state.top; + this.lexer.state.top = true; + this.lexer.blockTokens(currentText, tokens, true); + this.lexer.state.top = top; + // if there is no continuation then we are done + if (lines.length === 0) { + break; + } + const lastToken = tokens[tokens.length - 1]; + if (lastToken?.type === 'code') { + // blockquote continuation cannot be preceded by a code block + break; + } + else if (lastToken?.type === 'blockquote') { + // include continuation in nested blockquote + const oldToken = lastToken; + const newText = oldToken.raw + '\n' + lines.join('\n'); + const newToken = this.blockquote(newText); + tokens[tokens.length - 1] = newToken; + raw = raw.substring(0, raw.length - oldToken.raw.length) + newToken.raw; + text = text.substring(0, text.length - oldToken.text.length) + newToken.text; + break; + } + else if (lastToken?.type === 'list') { + // include continuation in nested list + const oldToken = lastToken; + const newText = oldToken.raw + '\n' + lines.join('\n'); + const newToken = this.list(newText); + tokens[tokens.length - 1] = newToken; + raw = raw.substring(0, raw.length - lastToken.raw.length) + newToken.raw; + text = text.substring(0, text.length - oldToken.raw.length) + newToken.raw; + lines = newText.substring(tokens[tokens.length - 1].raw.length).split('\n'); + continue; + } + } + return { + type: 'blockquote', + raw, + tokens, + text + }; + } + } + list(src) { + let cap = this.rules.block.list.exec(src); + if (cap) { + let bull = cap[1].trim(); + const isordered = bull.length > 1; + const list = { + type: 'list', + raw: '', + ordered: isordered, + start: isordered ? +bull.slice(0, -1) : '', + loose: false, + items: [] + }; + bull = isordered ? `\\d{1,9}\\${bull.slice(-1)}` : `\\${bull}`; + if (this.options.pedantic) { + bull = isordered ? bull : '[*+-]'; + } + // Get next list item + const itemRegex = new RegExp(`^( {0,3}${bull})((?:[\t ][^\\n]*)?(?:\\n|$))`); + let raw = ''; + let itemContents = ''; + let endsWithBlankLine = false; + // Check if current bullet point can start a new List Item + while (src) { + let endEarly = false; + if (!(cap = itemRegex.exec(src))) { + break; + } + if (this.rules.block.hr.test(src)) { // End list if bullet was actually HR (possibly move into itemRegex?) + break; + } + raw = cap[0]; + src = src.substring(raw.length); + let line = cap[2].split('\n', 1)[0].replace(/^\t+/, (t) => ' '.repeat(3 * t.length)); + let nextLine = src.split('\n', 1)[0]; + let indent = 0; + if (this.options.pedantic) { + indent = 2; + itemContents = line.trimStart(); + } + else { + indent = cap[2].search(/[^ ]/); // Find first non-space char + indent = indent > 4 ? 1 : indent; // Treat indented code blocks (> 4 spaces) as having only 1 indent + itemContents = line.slice(indent); + indent += cap[1].length; + } + let blankLine = false; + if (!line && /^ *$/.test(nextLine)) { // Items begin with at most one blank line + raw += nextLine + '\n'; + src = src.substring(nextLine.length + 1); + endEarly = true; + } + if (!endEarly) { + const nextBulletRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ \t][^\\n]*)?(?:\\n|$))`); + const hrRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`); + const fencesBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\`\`\`|~~~)`); + const headingBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`); + // Check if following lines should be included in List Item + while (src) { + const rawLine = src.split('\n', 1)[0]; + nextLine = rawLine; + // Re-align to follow commonmark nesting rules + if (this.options.pedantic) { + nextLine = nextLine.replace(/^ {1,4}(?=( {4})*[^ ])/g, ' '); + } + // End list item if found code fences + if (fencesBeginRegex.test(nextLine)) { + break; + } + // End list item if found start of new heading + if (headingBeginRegex.test(nextLine)) { + break; + } + // End list item if found start of new bullet + if (nextBulletRegex.test(nextLine)) { + break; + } + // Horizontal rule found + if (hrRegex.test(src)) { + break; + } + if (nextLine.search(/[^ ]/) >= indent || !nextLine.trim()) { // Dedent if possible + itemContents += '\n' + nextLine.slice(indent); + } + else { + // not enough indentation + if (blankLine) { + break; + } + // paragraph continuation unless last line was a different block level element + if (line.search(/[^ ]/) >= 4) { // indented code block + break; + } + if (fencesBeginRegex.test(line)) { + break; + } + if (headingBeginRegex.test(line)) { + break; + } + if (hrRegex.test(line)) { + break; + } + itemContents += '\n' + nextLine; + } + if (!blankLine && !nextLine.trim()) { // Check if current line is blank + blankLine = true; + } + raw += rawLine + '\n'; + src = src.substring(rawLine.length + 1); + line = nextLine.slice(indent); + } + } + if (!list.loose) { + // If the previous item ended with a blank line, the list is loose + if (endsWithBlankLine) { + list.loose = true; + } + else if (/\n *\n *$/.test(raw)) { + endsWithBlankLine = true; + } + } + let istask = null; + let ischecked; + // Check for task list items + if (this.options.gfm) { + istask = /^\[[ xX]\] /.exec(itemContents); + if (istask) { + ischecked = istask[0] !== '[ ] '; + itemContents = itemContents.replace(/^\[[ xX]\] +/, ''); + } + } + list.items.push({ + type: 'list_item', + raw, + task: !!istask, + checked: ischecked, + loose: false, + text: itemContents, + tokens: [] + }); + list.raw += raw; + } + // Do not consume newlines at end of final item. Alternatively, make itemRegex *start* with any newlines to simplify/speed up endsWithBlankLine logic + list.items[list.items.length - 1].raw = raw.trimEnd(); + (list.items[list.items.length - 1]).text = itemContents.trimEnd(); + list.raw = list.raw.trimEnd(); + // Item child tokens handled here at end because we needed to have the final item to trim it first + for (let i = 0; i < list.items.length; i++) { + this.lexer.state.top = false; + list.items[i].tokens = this.lexer.blockTokens(list.items[i].text, []); + if (!list.loose) { + // Check if list should be loose + const spacers = list.items[i].tokens.filter(t => t.type === 'space'); + const hasMultipleLineBreaks = spacers.length > 0 && spacers.some(t => /\n.*\n/.test(t.raw)); + list.loose = hasMultipleLineBreaks; + } + } + // Set all items to loose if list is loose + if (list.loose) { + for (let i = 0; i < list.items.length; i++) { + list.items[i].loose = true; + } + } + return list; + } + } + html(src) { + const cap = this.rules.block.html.exec(src); + if (cap) { + const token = { + type: 'html', + block: true, + raw: cap[0], + pre: cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style', + text: cap[0] + }; + return token; + } + } + def(src) { + const cap = this.rules.block.def.exec(src); + if (cap) { + const tag = cap[1].toLowerCase().replace(/\s+/g, ' '); + const href = cap[2] ? cap[2].replace(/^<(.*)>$/, '$1').replace(this.rules.inline.anyPunctuation, '$1') : ''; + const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, '$1') : cap[3]; + return { + type: 'def', + tag, + raw: cap[0], + href, + title + }; + } + } + table(src) { + const cap = this.rules.block.table.exec(src); + if (!cap) { + return; + } + if (!/[:|]/.test(cap[2])) { + // delimiter row must have a pipe (|) or colon (:) otherwise it is a setext heading + return; + } + const headers = splitCells(cap[1]); + const aligns = cap[2].replace(/^\||\| *$/g, '').split('|'); + const rows = cap[3] && cap[3].trim() ? cap[3].replace(/\n[ \t]*$/, '').split('\n') : []; + const item = { + type: 'table', + raw: cap[0], + header: [], + align: [], + rows: [] + }; + if (headers.length !== aligns.length) { + // header and align columns must be equal, rows can be different. + return; + } + for (const align of aligns) { + if (/^ *-+: *$/.test(align)) { + item.align.push('right'); + } + else if (/^ *:-+: *$/.test(align)) { + item.align.push('center'); + } + else if (/^ *:-+ *$/.test(align)) { + item.align.push('left'); + } + else { + item.align.push(null); + } + } + for (let i = 0; i < headers.length; i++) { + item.header.push({ + text: headers[i], + tokens: this.lexer.inline(headers[i]), + header: true, + align: item.align[i] + }); + } + for (const row of rows) { + item.rows.push(splitCells(row, item.header.length).map((cell, i) => { + return { + text: cell, + tokens: this.lexer.inline(cell), + header: false, + align: item.align[i] + }; + })); + } + return item; + } + lheading(src) { + const cap = this.rules.block.lheading.exec(src); + if (cap) { + return { + type: 'heading', + raw: cap[0], + depth: cap[2].charAt(0) === '=' ? 1 : 2, + text: cap[1], + tokens: this.lexer.inline(cap[1]) + }; + } + } + paragraph(src) { + const cap = this.rules.block.paragraph.exec(src); + if (cap) { + const text = cap[1].charAt(cap[1].length - 1) === '\n' + ? cap[1].slice(0, -1) + : cap[1]; + return { + type: 'paragraph', + raw: cap[0], + text, + tokens: this.lexer.inline(text) + }; + } + } + text(src) { + const cap = this.rules.block.text.exec(src); + if (cap) { + return { + type: 'text', + raw: cap[0], + text: cap[0], + tokens: this.lexer.inline(cap[0]) + }; + } + } + escape(src) { + const cap = this.rules.inline.escape.exec(src); + if (cap) { + return { + type: 'escape', + raw: cap[0], + text: escape$1(cap[1]) + }; + } + } + tag(src) { + const cap = this.rules.inline.tag.exec(src); + if (cap) { + if (!this.lexer.state.inLink && /^/i.test(cap[0])) { + this.lexer.state.inLink = false; + } + if (!this.lexer.state.inRawBlock && /^<(pre|code|kbd|script)(\s|>)/i.test(cap[0])) { + this.lexer.state.inRawBlock = true; + } + else if (this.lexer.state.inRawBlock && /^<\/(pre|code|kbd|script)(\s|>)/i.test(cap[0])) { + this.lexer.state.inRawBlock = false; + } + return { + type: 'html', + raw: cap[0], + inLink: this.lexer.state.inLink, + inRawBlock: this.lexer.state.inRawBlock, + block: false, + text: cap[0] + }; + } + } + link(src) { + const cap = this.rules.inline.link.exec(src); + if (cap) { + const trimmedUrl = cap[2].trim(); + if (!this.options.pedantic && /^$/.test(trimmedUrl))) { + return; + } + // ending angle bracket cannot be escaped + const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), '\\'); + if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) { + return; + } + } + else { + // find closing parenthesis + const lastParenIndex = findClosingBracket(cap[2], '()'); + if (lastParenIndex > -1) { + const start = cap[0].indexOf('!') === 0 ? 5 : 4; + const linkLen = start + cap[1].length + lastParenIndex; + cap[2] = cap[2].substring(0, lastParenIndex); + cap[0] = cap[0].substring(0, linkLen).trim(); + cap[3] = ''; + } + } + let href = cap[2]; + let title = ''; + if (this.options.pedantic) { + // split pedantic href and title + const link = /^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(href); + if (link) { + href = link[1]; + title = link[3]; + } + } + else { + title = cap[3] ? cap[3].slice(1, -1) : ''; + } + href = href.trim(); + if (/^$/.test(trimmedUrl))) { + // pedantic allows starting angle bracket without ending angle bracket + href = href.slice(1); + } + else { + href = href.slice(1, -1); + } + } + return outputLink(cap, { + href: href ? href.replace(this.rules.inline.anyPunctuation, '$1') : href, + title: title ? title.replace(this.rules.inline.anyPunctuation, '$1') : title + }, cap[0], this.lexer); + } + } + reflink(src, links) { + let cap; + if ((cap = this.rules.inline.reflink.exec(src)) + || (cap = this.rules.inline.nolink.exec(src))) { + const linkString = (cap[2] || cap[1]).replace(/\s+/g, ' '); + const link = links[linkString.toLowerCase()]; + if (!link) { + const text = cap[0].charAt(0); + return { + type: 'text', + raw: text, + text + }; + } + return outputLink(cap, link, cap[0], this.lexer); + } + } + emStrong(src, maskedSrc, prevChar = '') { + let match = this.rules.inline.emStrongLDelim.exec(src); + if (!match) + return; + // _ can't be between two alphanumerics. \p{L}\p{N} includes non-english alphabet/numbers as well + if (match[3] && prevChar.match(/[\p{L}\p{N}]/u)) + return; + const nextChar = match[1] || match[2] || ''; + if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) { + // unicode Regex counts emoji as 1 char; spread into array for proper count (used multiple times below) + const lLength = [...match[0]].length - 1; + let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0; + const endReg = match[0][0] === '*' ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd; + endReg.lastIndex = 0; + // Clip maskedSrc to same section of string as src (move to lexer?) + maskedSrc = maskedSrc.slice(-1 * src.length + lLength); + while ((match = endReg.exec(maskedSrc)) != null) { + rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6]; + if (!rDelim) + continue; // skip single * in __abc*abc__ + rLength = [...rDelim].length; + if (match[3] || match[4]) { // found another Left Delim + delimTotal += rLength; + continue; + } + else if (match[5] || match[6]) { // either Left or Right Delim + if (lLength % 3 && !((lLength + rLength) % 3)) { + midDelimTotal += rLength; + continue; // CommonMark Emphasis Rules 9-10 + } + } + delimTotal -= rLength; + if (delimTotal > 0) + continue; // Haven't found enough closing delimiters + // Remove extra characters. *a*** -> *a* + rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal); + // char length can be >1 for unicode characters; + const lastCharLength = [...match[0]][0].length; + const raw = src.slice(0, lLength + match.index + lastCharLength + rLength); + // Create `em` if smallest delimiter has odd char count. *a*** + if (Math.min(lLength, rLength) % 2) { + const text = raw.slice(1, -1); + return { + type: 'em', + raw, + text, + tokens: this.lexer.inlineTokens(text) + }; + } + // Create 'strong' if smallest delimiter has even char count. **a*** + const text = raw.slice(2, -2); + return { + type: 'strong', + raw, + text, + tokens: this.lexer.inlineTokens(text) + }; + } + } + } + codespan(src) { + const cap = this.rules.inline.code.exec(src); + if (cap) { + let text = cap[2].replace(/\n/g, ' '); + const hasNonSpaceChars = /[^ ]/.test(text); + const hasSpaceCharsOnBothEnds = /^ /.test(text) && / $/.test(text); + if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) { + text = text.substring(1, text.length - 1); + } + text = escape$1(text, true); + return { + type: 'codespan', + raw: cap[0], + text + }; + } + } + br(src) { + const cap = this.rules.inline.br.exec(src); + if (cap) { + return { + type: 'br', + raw: cap[0] + }; + } + } + del(src) { + const cap = this.rules.inline.del.exec(src); + if (cap) { + return { + type: 'del', + raw: cap[0], + text: cap[2], + tokens: this.lexer.inlineTokens(cap[2]) + }; + } + } + autolink(src) { + const cap = this.rules.inline.autolink.exec(src); + if (cap) { + let text, href; + if (cap[2] === '@') { + text = escape$1(cap[1]); + href = 'mailto:' + text; + } + else { + text = escape$1(cap[1]); + href = text; + } + return { + type: 'link', + raw: cap[0], + text, + href, + tokens: [ + { + type: 'text', + raw: text, + text + } + ] + }; + } + } + url(src) { + let cap; + if (cap = this.rules.inline.url.exec(src)) { + let text, href; + if (cap[2] === '@') { + text = escape$1(cap[0]); + href = 'mailto:' + text; + } + else { + // do extended autolink path validation + let prevCapZero; + do { + prevCapZero = cap[0]; + cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? ''; + } while (prevCapZero !== cap[0]); + text = escape$1(cap[0]); + if (cap[1] === 'www.') { + href = 'http://' + cap[0]; + } + else { + href = cap[0]; + } + } + return { + type: 'link', + raw: cap[0], + text, + href, + tokens: [ + { + type: 'text', + raw: text, + text + } + ] + }; + } + } + inlineText(src) { + const cap = this.rules.inline.text.exec(src); + if (cap) { + let text; + if (this.lexer.state.inRawBlock) { + text = cap[0]; + } + else { + text = escape$1(cap[0]); + } + return { + type: 'text', + raw: cap[0], + text + }; + } + } +} + +/** + * Block-Level Grammar + */ +const newline = /^(?: *(?:\n|$))+/; +const blockCode = /^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/; +const fences = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/; +const hr = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/; +const heading = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/; +const bullet = /(?:[*+-]|\d{1,9}[.)])/; +const lheading = edit(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/) + .replace(/bull/g, bullet) // lists can interrupt + .replace(/blockCode/g, / {4}/) // indented code blocks can interrupt + .replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/) // fenced code blocks can interrupt + .replace(/blockquote/g, / {0,3}>/) // blockquote can interrupt + .replace(/heading/g, / {0,3}#{1,6}/) // ATX heading can interrupt + .replace(/html/g, / {0,3}<[^\n>]+>\n/) // block html can interrupt + .getRegex(); +const _paragraph = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/; +const blockText = /^[^\n]+/; +const _blockLabel = /(?!\s*\])(?:\\.|[^\[\]\\])+/; +const def = edit(/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/) + .replace('label', _blockLabel) + .replace('title', /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/) + .getRegex(); +const list = edit(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/) + .replace(/bull/g, bullet) + .getRegex(); +const _tag = 'address|article|aside|base|basefont|blockquote|body|caption' + + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption' + + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe' + + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option' + + '|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title' + + '|tr|track|ul'; +const _comment = /|$))/; +const html = edit('^ {0,3}(?:' // optional indentation + + '<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)' // (1) + + '|comment[^\\n]*(\\n+|$)' // (2) + + '|<\\?[\\s\\S]*?(?:\\?>\\n*|$)' // (3) + + '|\\n*|$)' // (4) + + '|\\n*|$)' // (5) + + '|)[\\s\\S]*?(?:(?:\\n *)+\\n|$)' // (6) + + '|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)' // (7) open tag + + '|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)' // (7) closing tag + + ')', 'i') + .replace('comment', _comment) + .replace('tag', _tag) + .replace('attribute', / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/) + .getRegex(); +const paragraph = edit(_paragraph) + .replace('hr', hr) + .replace('heading', ' {0,3}#{1,6}(?:\\s|$)') + .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs + .replace('|table', '') + .replace('blockquote', ' {0,3}>') + .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n') + .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt + .replace('html', ')|<(?:script|pre|style|textarea|!--)') + .replace('tag', _tag) // pars can be interrupted by type (6) html blocks + .getRegex(); +const blockquote = edit(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/) + .replace('paragraph', paragraph) + .getRegex(); +/** + * Normal Block Grammar + */ +const blockNormal = { + blockquote, + code: blockCode, + def, + fences, + heading, + hr, + html, + lheading, + list, + newline, + paragraph, + table: noopTest, + text: blockText +}; +/** + * GFM Block Grammar + */ +const gfmTable = edit('^ *([^\\n ].*)\\n' // Header + + ' {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)' // Align + + '(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)') // Cells + .replace('hr', hr) + .replace('heading', ' {0,3}#{1,6}(?:\\s|$)') + .replace('blockquote', ' {0,3}>') + .replace('code', ' {4}[^\\n]') + .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n') + .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt + .replace('html', ')|<(?:script|pre|style|textarea|!--)') + .replace('tag', _tag) // tables can be interrupted by type (6) html blocks + .getRegex(); +const blockGfm = { + ...blockNormal, + table: gfmTable, + paragraph: edit(_paragraph) + .replace('hr', hr) + .replace('heading', ' {0,3}#{1,6}(?:\\s|$)') + .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs + .replace('table', gfmTable) // interrupt paragraphs with table + .replace('blockquote', ' {0,3}>') + .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n') + .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt + .replace('html', ')|<(?:script|pre|style|textarea|!--)') + .replace('tag', _tag) // pars can be interrupted by type (6) html blocks + .getRegex() +}; +/** + * Pedantic grammar (original John Gruber's loose markdown specification) + */ +const blockPedantic = { + ...blockNormal, + html: edit('^ *(?:comment *(?:\\n|\\s*$)' + + '|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)' // closed tag + + '|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))') + .replace('comment', _comment) + .replace(/tag/g, '(?!(?:' + + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub' + + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)' + + '\\b)\\w+(?!:|[^\\w\\s@]*@)\\b') + .getRegex(), + def: /^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/, + heading: /^(#{1,6})(.*)(?:\n+|$)/, + fences: noopTest, // fences not supported + lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/, + paragraph: edit(_paragraph) + .replace('hr', hr) + .replace('heading', ' *#{1,6} *[^\n]') + .replace('lheading', lheading) + .replace('|table', '') + .replace('blockquote', ' {0,3}>') + .replace('|fences', '') + .replace('|list', '') + .replace('|html', '') + .replace('|tag', '') + .getRegex() +}; +/** + * Inline-Level Grammar + */ +const escape = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/; +const inlineCode = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/; +const br = /^( {2,}|\\)\n(?!\s*$)/; +const inlineText = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\ +const blockSkip = /\[[^[\]]*?\]\([^\(\)]*?\)|`[^`]*?`|<[^<>]*?>/g; +const emStrongLDelim = edit(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/, 'u') + .replace(/punct/g, _punctuation) + .getRegex(); +const emStrongRDelimAst = edit('^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)' // Skip orphan inside strong + + '|[^*]+(?=[^*])' // Consume to delim + + '|(?!\\*)[punct](\\*+)(?=[\\s]|$)' // (1) #*** can only be a Right Delimiter + + '|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)' // (2) a***#, a*** can only be a Right Delimiter + + '|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])' // (3) #***a, ***a can only be Left Delimiter + + '|[\\s](\\*+)(?!\\*)(?=[punct])' // (4) ***# can only be Left Delimiter + + '|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])' // (5) #***# can be either Left or Right Delimiter + + '|[^punct\\s](\\*+)(?=[^punct\\s])', 'gu') // (6) a***a can be either Left or Right Delimiter + .replace(/punct/g, _punctuation) + .getRegex(); +// (6) Not allowed for _ +const emStrongRDelimUnd = edit('^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)' // Skip orphan inside strong + + '|[^_]+(?=[^_])' // Consume to delim + + '|(?!_)[punct](_+)(?=[\\s]|$)' // (1) #___ can only be a Right Delimiter + + '|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)' // (2) a___#, a___ can only be a Right Delimiter + + '|(?!_)[punct\\s](_+)(?=[^punct\\s])' // (3) #___a, ___a can only be Left Delimiter + + '|[\\s](_+)(?!_)(?=[punct])' // (4) ___# can only be Left Delimiter + + '|(?!_)[punct](_+)(?!_)(?=[punct])', 'gu') // (5) #___# can be either Left or Right Delimiter + .replace(/punct/g, _punctuation) + .getRegex(); +const anyPunctuation = edit(/\\([punct])/, 'gu') + .replace(/punct/g, _punctuation) + .getRegex(); +const autolink = edit(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/) + .replace('scheme', /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/) + .replace('email', /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/) + .getRegex(); +const _inlineComment = edit(_comment).replace('(?:-->|$)', '-->').getRegex(); +const tag = edit('^comment' + + '|^' // self-closing tag + + '|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>' // open tag + + '|^<\\?[\\s\\S]*?\\?>' // processing instruction, e.g. + + '|^' // declaration, e.g. + + '|^') // CDATA section + .replace('comment', _inlineComment) + .replace('attribute', /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/) + .getRegex(); +const _inlineLabel = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/; +const link = edit(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/) + .replace('label', _inlineLabel) + .replace('href', /<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/) + .replace('title', /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/) + .getRegex(); +const reflink = edit(/^!?\[(label)\]\[(ref)\]/) + .replace('label', _inlineLabel) + .replace('ref', _blockLabel) + .getRegex(); +const nolink = edit(/^!?\[(ref)\](?:\[\])?/) + .replace('ref', _blockLabel) + .getRegex(); +const reflinkSearch = edit('reflink|nolink(?!\\()', 'g') + .replace('reflink', reflink) + .replace('nolink', nolink) + .getRegex(); +/** + * Normal Inline Grammar + */ +const inlineNormal = { + _backpedal: noopTest, // only used for GFM url + anyPunctuation, + autolink, + blockSkip, + br, + code: inlineCode, + del: noopTest, + emStrongLDelim, + emStrongRDelimAst, + emStrongRDelimUnd, + escape, + link, + nolink, + punctuation, + reflink, + reflinkSearch, + tag, + text: inlineText, + url: noopTest +}; +/** + * Pedantic Inline Grammar + */ +const inlinePedantic = { + ...inlineNormal, + link: edit(/^!?\[(label)\]\((.*?)\)/) + .replace('label', _inlineLabel) + .getRegex(), + reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/) + .replace('label', _inlineLabel) + .getRegex() +}; +/** + * GFM Inline Grammar + */ +const inlineGfm = { + ...inlineNormal, + escape: edit(escape).replace('])', '~|])').getRegex(), + url: edit(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/, 'i') + .replace('email', /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/) + .getRegex(), + _backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/, + del: /^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/, + text: /^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\ { + return leading + ' '.repeat(tabs.length); + }); + } + let token; + let lastToken; + let cutSrc; + while (src) { + if (this.options.extensions + && this.options.extensions.block + && this.options.extensions.block.some((extTokenizer) => { + if (token = extTokenizer.call({ lexer: this }, src, tokens)) { + src = src.substring(token.raw.length); + tokens.push(token); + return true; + } + return false; + })) { + continue; + } + // newline + if (token = this.tokenizer.space(src)) { + src = src.substring(token.raw.length); + if (token.raw.length === 1 && tokens.length > 0) { + // if there's a single \n as a spacer, it's terminating the last line, + // so move it there so that we don't get unnecessary paragraph tags + tokens[tokens.length - 1].raw += '\n'; + } + else { + tokens.push(token); + } + continue; + } + // code + if (token = this.tokenizer.code(src)) { + src = src.substring(token.raw.length); + lastToken = tokens[tokens.length - 1]; + // An indented code block cannot interrupt a paragraph. + if (lastToken && (lastToken.type === 'paragraph' || lastToken.type === 'text')) { + lastToken.raw += '\n' + token.raw; + lastToken.text += '\n' + token.text; + this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text; + } + else { + tokens.push(token); + } + continue; + } + // fences + if (token = this.tokenizer.fences(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // heading + if (token = this.tokenizer.heading(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // hr + if (token = this.tokenizer.hr(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // blockquote + if (token = this.tokenizer.blockquote(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // list + if (token = this.tokenizer.list(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // html + if (token = this.tokenizer.html(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // def + if (token = this.tokenizer.def(src)) { + src = src.substring(token.raw.length); + lastToken = tokens[tokens.length - 1]; + if (lastToken && (lastToken.type === 'paragraph' || lastToken.type === 'text')) { + lastToken.raw += '\n' + token.raw; + lastToken.text += '\n' + token.raw; + this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text; + } + else if (!this.tokens.links[token.tag]) { + this.tokens.links[token.tag] = { + href: token.href, + title: token.title + }; + } + continue; + } + // table (gfm) + if (token = this.tokenizer.table(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // lheading + if (token = this.tokenizer.lheading(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // top-level paragraph + // prevent paragraph consuming extensions by clipping 'src' to extension start + cutSrc = src; + if (this.options.extensions && this.options.extensions.startBlock) { + let startIndex = Infinity; + const tempSrc = src.slice(1); + let tempStart; + this.options.extensions.startBlock.forEach((getStartIndex) => { + tempStart = getStartIndex.call({ lexer: this }, tempSrc); + if (typeof tempStart === 'number' && tempStart >= 0) { + startIndex = Math.min(startIndex, tempStart); + } + }); + if (startIndex < Infinity && startIndex >= 0) { + cutSrc = src.substring(0, startIndex + 1); + } + } + if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) { + lastToken = tokens[tokens.length - 1]; + if (lastParagraphClipped && lastToken?.type === 'paragraph') { + lastToken.raw += '\n' + token.raw; + lastToken.text += '\n' + token.text; + this.inlineQueue.pop(); + this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text; + } + else { + tokens.push(token); + } + lastParagraphClipped = (cutSrc.length !== src.length); + src = src.substring(token.raw.length); + continue; + } + // text + if (token = this.tokenizer.text(src)) { + src = src.substring(token.raw.length); + lastToken = tokens[tokens.length - 1]; + if (lastToken && lastToken.type === 'text') { + lastToken.raw += '\n' + token.raw; + lastToken.text += '\n' + token.text; + this.inlineQueue.pop(); + this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text; + } + else { + tokens.push(token); + } + continue; + } + if (src) { + const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0); + if (this.options.silent) { + console.error(errMsg); + break; + } + else { + throw new Error(errMsg); + } + } + } + this.state.top = true; + return tokens; + } + inline(src, tokens = []) { + this.inlineQueue.push({ src, tokens }); + return tokens; + } + /** + * Lexing/Compiling + */ + inlineTokens(src, tokens = []) { + let token, lastToken, cutSrc; + // String with links masked to avoid interference with em and strong + let maskedSrc = src; + let match; + let keepPrevChar, prevChar; + // Mask out reflinks + if (this.tokens.links) { + const links = Object.keys(this.tokens.links); + if (links.length > 0) { + while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) { + if (links.includes(match[0].slice(match[0].lastIndexOf('[') + 1, -1))) { + maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex); + } + } + } + } + // Mask out other blocks + while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) { + maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex); + } + // Mask out escaped characters + while ((match = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) != null) { + maskedSrc = maskedSrc.slice(0, match.index) + '++' + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex); + } + while (src) { + if (!keepPrevChar) { + prevChar = ''; + } + keepPrevChar = false; + // extensions + if (this.options.extensions + && this.options.extensions.inline + && this.options.extensions.inline.some((extTokenizer) => { + if (token = extTokenizer.call({ lexer: this }, src, tokens)) { + src = src.substring(token.raw.length); + tokens.push(token); + return true; + } + return false; + })) { + continue; + } + // escape + if (token = this.tokenizer.escape(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // tag + if (token = this.tokenizer.tag(src)) { + src = src.substring(token.raw.length); + lastToken = tokens[tokens.length - 1]; + if (lastToken && token.type === 'text' && lastToken.type === 'text') { + lastToken.raw += token.raw; + lastToken.text += token.text; + } + else { + tokens.push(token); + } + continue; + } + // link + if (token = this.tokenizer.link(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // reflink, nolink + if (token = this.tokenizer.reflink(src, this.tokens.links)) { + src = src.substring(token.raw.length); + lastToken = tokens[tokens.length - 1]; + if (lastToken && token.type === 'text' && lastToken.type === 'text') { + lastToken.raw += token.raw; + lastToken.text += token.text; + } + else { + tokens.push(token); + } + continue; + } + // em & strong + if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // code + if (token = this.tokenizer.codespan(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // br + if (token = this.tokenizer.br(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // del (gfm) + if (token = this.tokenizer.del(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // autolink + if (token = this.tokenizer.autolink(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // url (gfm) + if (!this.state.inLink && (token = this.tokenizer.url(src))) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // text + // prevent inlineText consuming extensions by clipping 'src' to extension start + cutSrc = src; + if (this.options.extensions && this.options.extensions.startInline) { + let startIndex = Infinity; + const tempSrc = src.slice(1); + let tempStart; + this.options.extensions.startInline.forEach((getStartIndex) => { + tempStart = getStartIndex.call({ lexer: this }, tempSrc); + if (typeof tempStart === 'number' && tempStart >= 0) { + startIndex = Math.min(startIndex, tempStart); + } + }); + if (startIndex < Infinity && startIndex >= 0) { + cutSrc = src.substring(0, startIndex + 1); + } + } + if (token = this.tokenizer.inlineText(cutSrc)) { + src = src.substring(token.raw.length); + if (token.raw.slice(-1) !== '_') { // Track prevChar before string of ____ started + prevChar = token.raw.slice(-1); + } + keepPrevChar = true; + lastToken = tokens[tokens.length - 1]; + if (lastToken && lastToken.type === 'text') { + lastToken.raw += token.raw; + lastToken.text += token.text; + } + else { + tokens.push(token); + } + continue; + } + if (src) { + const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0); + if (this.options.silent) { + console.error(errMsg); + break; + } + else { + throw new Error(errMsg); + } + } + } + return tokens; + } +} + +/** + * Renderer + */ +class _Renderer { + options; + parser; // set by the parser + constructor(options) { + this.options = options || exports.defaults; + } + space(token) { + return ''; + } + code({ text, lang, escaped }) { + const langString = (lang || '').match(/^\S*/)?.[0]; + const code = text.replace(/\n$/, '') + '\n'; + if (!langString) { + return '
'
+                + (escaped ? code : escape$1(code, true))
+                + '
\n'; + } + return '
'
+            + (escaped ? code : escape$1(code, true))
+            + '
\n'; + } + blockquote({ tokens }) { + const body = this.parser.parse(tokens); + return `
\n${body}
\n`; + } + html({ text }) { + return text; + } + heading({ tokens, depth }) { + return `${this.parser.parseInline(tokens)}\n`; + } + hr(token) { + return '
\n'; + } + list(token) { + const ordered = token.ordered; + const start = token.start; + let body = ''; + for (let j = 0; j < token.items.length; j++) { + const item = token.items[j]; + body += this.listitem(item); + } + const type = ordered ? 'ol' : 'ul'; + const startAttr = (ordered && start !== 1) ? (' start="' + start + '"') : ''; + return '<' + type + startAttr + '>\n' + body + '\n'; + } + listitem(item) { + let itemBody = ''; + if (item.task) { + const checkbox = this.checkbox({ checked: !!item.checked }); + if (item.loose) { + if (item.tokens.length > 0 && item.tokens[0].type === 'paragraph') { + item.tokens[0].text = checkbox + ' ' + item.tokens[0].text; + if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') { + item.tokens[0].tokens[0].text = checkbox + ' ' + item.tokens[0].tokens[0].text; + } + } + else { + item.tokens.unshift({ + type: 'text', + raw: checkbox + ' ', + text: checkbox + ' ' + }); + } + } + else { + itemBody += checkbox + ' '; + } + } + itemBody += this.parser.parse(item.tokens, !!item.loose); + return `
  • ${itemBody}
  • \n`; + } + checkbox({ checked }) { + return ''; + } + paragraph({ tokens }) { + return `

    ${this.parser.parseInline(tokens)}

    \n`; + } + table(token) { + let header = ''; + // header + let cell = ''; + for (let j = 0; j < token.header.length; j++) { + cell += this.tablecell(token.header[j]); + } + header += this.tablerow({ text: cell }); + let body = ''; + for (let j = 0; j < token.rows.length; j++) { + const row = token.rows[j]; + cell = ''; + for (let k = 0; k < row.length; k++) { + cell += this.tablecell(row[k]); + } + body += this.tablerow({ text: cell }); + } + if (body) + body = `${body}`; + return '\n' + + '\n' + + header + + '\n' + + body + + '
    \n'; + } + tablerow({ text }) { + return `\n${text}\n`; + } + tablecell(token) { + const content = this.parser.parseInline(token.tokens); + const type = token.header ? 'th' : 'td'; + const tag = token.align + ? `<${type} align="${token.align}">` + : `<${type}>`; + return tag + content + `\n`; + } + /** + * span level renderer + */ + strong({ tokens }) { + return `${this.parser.parseInline(tokens)}`; + } + em({ tokens }) { + return `${this.parser.parseInline(tokens)}`; + } + codespan({ text }) { + return `${text}`; + } + br(token) { + return '
    '; + } + del({ tokens }) { + return `${this.parser.parseInline(tokens)}`; + } + link({ href, title, tokens }) { + const text = this.parser.parseInline(tokens); + const cleanHref = cleanUrl(href); + if (cleanHref === null) { + return text; + } + href = cleanHref; + let out = '
    '; + return out; + } + image({ href, title, text }) { + const cleanHref = cleanUrl(href); + if (cleanHref === null) { + return text; + } + href = cleanHref; + let out = `${text} { + const tokens = genericToken[childTokens].flat(Infinity); + values = values.concat(this.walkTokens(tokens, callback)); + }); + } + else if (genericToken.tokens) { + values = values.concat(this.walkTokens(genericToken.tokens, callback)); + } + } + } + } + return values; + } + use(...args) { + const extensions = this.defaults.extensions || { renderers: {}, childTokens: {} }; + args.forEach((pack) => { + // copy options to new object + const opts = { ...pack }; + // set async to true if it was set to true before + opts.async = this.defaults.async || opts.async || false; + // ==-- Parse "addon" extensions --== // + if (pack.extensions) { + pack.extensions.forEach((ext) => { + if (!ext.name) { + throw new Error('extension name required'); + } + if ('renderer' in ext) { // Renderer extensions + const prevRenderer = extensions.renderers[ext.name]; + if (prevRenderer) { + // Replace extension with func to run new extension but fall back if false + extensions.renderers[ext.name] = function (...args) { + let ret = ext.renderer.apply(this, args); + if (ret === false) { + ret = prevRenderer.apply(this, args); + } + return ret; + }; + } + else { + extensions.renderers[ext.name] = ext.renderer; + } + } + if ('tokenizer' in ext) { // Tokenizer Extensions + if (!ext.level || (ext.level !== 'block' && ext.level !== 'inline')) { + throw new Error("extension level must be 'block' or 'inline'"); + } + const extLevel = extensions[ext.level]; + if (extLevel) { + extLevel.unshift(ext.tokenizer); + } + else { + extensions[ext.level] = [ext.tokenizer]; + } + if (ext.start) { // Function to check for start of token + if (ext.level === 'block') { + if (extensions.startBlock) { + extensions.startBlock.push(ext.start); + } + else { + extensions.startBlock = [ext.start]; + } + } + else if (ext.level === 'inline') { + if (extensions.startInline) { + extensions.startInline.push(ext.start); + } + else { + extensions.startInline = [ext.start]; + } + } + } + } + if ('childTokens' in ext && ext.childTokens) { // Child tokens to be visited by walkTokens + extensions.childTokens[ext.name] = ext.childTokens; + } + }); + opts.extensions = extensions; + } + // ==-- Parse "overwrite" extensions --== // + if (pack.renderer) { + const renderer = this.defaults.renderer || new _Renderer(this.defaults); + for (const prop in pack.renderer) { + if (!(prop in renderer)) { + throw new Error(`renderer '${prop}' does not exist`); + } + if (['options', 'parser'].includes(prop)) { + // ignore options property + continue; + } + const rendererProp = prop; + let rendererFunc = pack.renderer[rendererProp]; + const prevRenderer = renderer[rendererProp]; + // Replace renderer with func to run extension, but fall back if false + renderer[rendererProp] = (...args) => { + if (!pack.useNewRenderer) { + // TODO: Remove this in next major version + rendererFunc = this.#convertRendererFunction(rendererFunc, rendererProp, renderer); + } + let ret = rendererFunc.apply(renderer, args); + if (ret === false) { + ret = prevRenderer.apply(renderer, args); + } + return ret || ''; + }; + } + opts.renderer = renderer; + } + if (pack.tokenizer) { + const tokenizer = this.defaults.tokenizer || new _Tokenizer(this.defaults); + for (const prop in pack.tokenizer) { + if (!(prop in tokenizer)) { + throw new Error(`tokenizer '${prop}' does not exist`); + } + if (['options', 'rules', 'lexer'].includes(prop)) { + // ignore options, rules, and lexer properties + continue; + } + const tokenizerProp = prop; + const tokenizerFunc = pack.tokenizer[tokenizerProp]; + const prevTokenizer = tokenizer[tokenizerProp]; + // Replace tokenizer with func to run extension, but fall back if false + // @ts-expect-error cannot type tokenizer function dynamically + tokenizer[tokenizerProp] = (...args) => { + let ret = tokenizerFunc.apply(tokenizer, args); + if (ret === false) { + ret = prevTokenizer.apply(tokenizer, args); + } + return ret; + }; + } + opts.tokenizer = tokenizer; + } + // ==-- Parse Hooks extensions --== // + if (pack.hooks) { + const hooks = this.defaults.hooks || new _Hooks(); + for (const prop in pack.hooks) { + if (!(prop in hooks)) { + throw new Error(`hook '${prop}' does not exist`); + } + if (prop === 'options') { + // ignore options property + continue; + } + const hooksProp = prop; + const hooksFunc = pack.hooks[hooksProp]; + const prevHook = hooks[hooksProp]; + if (_Hooks.passThroughHooks.has(prop)) { + // @ts-expect-error cannot type hook function dynamically + hooks[hooksProp] = (arg) => { + if (this.defaults.async) { + return Promise.resolve(hooksFunc.call(hooks, arg)).then(ret => { + return prevHook.call(hooks, ret); + }); + } + const ret = hooksFunc.call(hooks, arg); + return prevHook.call(hooks, ret); + }; + } + else { + // @ts-expect-error cannot type hook function dynamically + hooks[hooksProp] = (...args) => { + let ret = hooksFunc.apply(hooks, args); + if (ret === false) { + ret = prevHook.apply(hooks, args); + } + return ret; + }; + } + } + opts.hooks = hooks; + } + // ==-- Parse WalkTokens extensions --== // + if (pack.walkTokens) { + const walkTokens = this.defaults.walkTokens; + const packWalktokens = pack.walkTokens; + opts.walkTokens = function (token) { + let values = []; + values.push(packWalktokens.call(this, token)); + if (walkTokens) { + values = values.concat(walkTokens.call(this, token)); + } + return values; + }; + } + this.defaults = { ...this.defaults, ...opts }; + }); + return this; + } + // TODO: Remove this in next major release + #convertRendererFunction(func, prop, renderer) { + switch (prop) { + case 'heading': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + return func.call(this, renderer.parser.parseInline(token.tokens), token.depth, unescape(renderer.parser.parseInline(token.tokens, renderer.parser.textRenderer))); + }; + case 'code': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + return func.call(this, token.text, token.lang, !!token.escaped); + }; + case 'table': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + let header = ''; + // header + let cell = ''; + for (let j = 0; j < token.header.length; j++) { + cell += this.tablecell({ + text: token.header[j].text, + tokens: token.header[j].tokens, + header: true, + align: token.align[j] + }); + } + header += this.tablerow({ text: cell }); + let body = ''; + for (let j = 0; j < token.rows.length; j++) { + const row = token.rows[j]; + cell = ''; + for (let k = 0; k < row.length; k++) { + cell += this.tablecell({ + text: row[k].text, + tokens: row[k].tokens, + header: false, + align: token.align[k] + }); + } + body += this.tablerow({ text: cell }); + } + return func.call(this, header, body); + }; + case 'blockquote': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + const body = this.parser.parse(token.tokens); + return func.call(this, body); + }; + case 'list': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + const ordered = token.ordered; + const start = token.start; + const loose = token.loose; + let body = ''; + for (let j = 0; j < token.items.length; j++) { + const item = token.items[j]; + const checked = item.checked; + const task = item.task; + let itemBody = ''; + if (item.task) { + const checkbox = this.checkbox({ checked: !!checked }); + if (loose) { + if (item.tokens.length > 0 && item.tokens[0].type === 'paragraph') { + item.tokens[0].text = checkbox + ' ' + item.tokens[0].text; + if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') { + item.tokens[0].tokens[0].text = checkbox + ' ' + item.tokens[0].tokens[0].text; + } + } + else { + item.tokens.unshift({ + type: 'text', + text: checkbox + ' ' + }); + } + } + else { + itemBody += checkbox + ' '; + } + } + itemBody += this.parser.parse(item.tokens, loose); + body += this.listitem({ + type: 'list_item', + raw: itemBody, + text: itemBody, + task, + checked: !!checked, + loose, + tokens: item.tokens + }); + } + return func.call(this, body, ordered, start); + }; + case 'html': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + return func.call(this, token.text, token.block); + }; + case 'paragraph': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + return func.call(this, this.parser.parseInline(token.tokens)); + }; + case 'escape': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + return func.call(this, token.text); + }; + case 'link': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + return func.call(this, token.href, token.title, this.parser.parseInline(token.tokens)); + }; + case 'image': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + return func.call(this, token.href, token.title, token.text); + }; + case 'strong': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + return func.call(this, this.parser.parseInline(token.tokens)); + }; + case 'em': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + return func.call(this, this.parser.parseInline(token.tokens)); + }; + case 'codespan': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + return func.call(this, token.text); + }; + case 'del': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + return func.call(this, this.parser.parseInline(token.tokens)); + }; + case 'text': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + return func.call(this, token.text); + }; + // do nothing + } + return func; + } + setOptions(opt) { + this.defaults = { ...this.defaults, ...opt }; + return this; + } + lexer(src, options) { + return _Lexer.lex(src, options ?? this.defaults); + } + parser(tokens, options) { + return _Parser.parse(tokens, options ?? this.defaults); + } + #parseMarkdown(lexer, parser) { + return (src, options) => { + const origOpt = { ...options }; + const opt = { ...this.defaults, ...origOpt }; + // Show warning if an extension set async to true but the parse was called with async: false + if (this.defaults.async === true && origOpt.async === false) { + if (!opt.silent) { + console.warn('marked(): The async option was set to true by an extension. The async: false option sent to parse will be ignored.'); + } + opt.async = true; + } + const throwError = this.#onError(!!opt.silent, !!opt.async); + // throw error in case of non string input + if (typeof src === 'undefined' || src === null) { + return throwError(new Error('marked(): input parameter is undefined or null')); + } + if (typeof src !== 'string') { + return throwError(new Error('marked(): input parameter is of type ' + + Object.prototype.toString.call(src) + ', string expected')); + } + if (opt.hooks) { + opt.hooks.options = opt; + } + if (opt.async) { + return Promise.resolve(opt.hooks ? opt.hooks.preprocess(src) : src) + .then(src => lexer(src, opt)) + .then(tokens => opt.hooks ? opt.hooks.processAllTokens(tokens) : tokens) + .then(tokens => opt.walkTokens ? Promise.all(this.walkTokens(tokens, opt.walkTokens)).then(() => tokens) : tokens) + .then(tokens => parser(tokens, opt)) + .then(html => opt.hooks ? opt.hooks.postprocess(html) : html) + .catch(throwError); + } + try { + if (opt.hooks) { + src = opt.hooks.preprocess(src); + } + let tokens = lexer(src, opt); + if (opt.hooks) { + tokens = opt.hooks.processAllTokens(tokens); + } + if (opt.walkTokens) { + this.walkTokens(tokens, opt.walkTokens); + } + let html = parser(tokens, opt); + if (opt.hooks) { + html = opt.hooks.postprocess(html); + } + return html; + } + catch (e) { + return throwError(e); + } + }; + } + #onError(silent, async) { + return (e) => { + e.message += '\nPlease report this to https://github.com/markedjs/marked.'; + if (silent) { + const msg = '

    An error occurred:

    '
    +                    + escape$1(e.message + '', true)
    +                    + '
    '; + if (async) { + return Promise.resolve(msg); + } + return msg; + } + if (async) { + return Promise.reject(e); + } + throw e; + }; + } +} + +const markedInstance = new Marked(); +function marked(src, opt) { + return markedInstance.parse(src, opt); +} +/** + * Sets the default options. + * + * @param options Hash of options + */ +marked.options = + marked.setOptions = function (options) { + markedInstance.setOptions(options); + marked.defaults = markedInstance.defaults; + changeDefaults(marked.defaults); + return marked; + }; +/** + * Gets the original marked default options. + */ +marked.getDefaults = _getDefaults; +marked.defaults = exports.defaults; +/** + * Use Extension + */ +marked.use = function (...args) { + markedInstance.use(...args); + marked.defaults = markedInstance.defaults; + changeDefaults(marked.defaults); + return marked; +}; +/** + * Run callback for every token + */ +marked.walkTokens = function (tokens, callback) { + return markedInstance.walkTokens(tokens, callback); +}; +/** + * Compiles markdown to HTML without enclosing `p` tag. + * + * @param src String of markdown source to be compiled + * @param options Hash of options + * @return String of compiled HTML + */ +marked.parseInline = markedInstance.parseInline; +/** + * Expose + */ +marked.Parser = _Parser; +marked.parser = _Parser.parse; +marked.Renderer = _Renderer; +marked.TextRenderer = _TextRenderer; +marked.Lexer = _Lexer; +marked.lexer = _Lexer.lex; +marked.Tokenizer = _Tokenizer; +marked.Hooks = _Hooks; +marked.parse = marked; +const options = marked.options; +const setOptions = marked.setOptions; +const use = marked.use; +const walkTokens = marked.walkTokens; +const parseInline = marked.parseInline; +const parse = marked; +const parser = _Parser.parse; +const lexer = _Lexer.lex; + +exports.Hooks = _Hooks; +exports.Lexer = _Lexer; +exports.Marked = Marked; +exports.Parser = _Parser; +exports.Renderer = _Renderer; +exports.TextRenderer = _TextRenderer; +exports.Tokenizer = _Tokenizer; +exports.getDefaults = _getDefaults; +exports.lexer = lexer; +exports.marked = marked; +exports.options = options; +exports.parse = parse; +exports.parseInline = parseInline; +exports.parser = parser; +exports.setOptions = setOptions; +exports.use = use; +exports.walkTokens = walkTokens; +//# sourceMappingURL=marked.cjs.map diff --git a/scripts/node_modules/marked/lib/marked.cjs.map b/scripts/node_modules/marked/lib/marked.cjs.map new file mode 100644 index 000000000..063d5f544 --- /dev/null +++ b/scripts/node_modules/marked/lib/marked.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"marked.cjs","sources":["../src/defaults.ts","../src/helpers.ts","../src/Tokenizer.ts","../src/rules.ts","../src/Lexer.ts","../src/Renderer.ts","../src/TextRenderer.ts","../src/Parser.ts","../src/Hooks.ts","../src/Instance.ts","../src/marked.ts"],"sourcesContent":["/**\n * Gets the original marked default options.\n */\nexport function _getDefaults() {\n return {\n async: false,\n breaks: false,\n extensions: null,\n gfm: true,\n hooks: null,\n pedantic: false,\n renderer: null,\n silent: false,\n tokenizer: null,\n walkTokens: null\n };\n}\nexport let _defaults = _getDefaults();\nexport function changeDefaults(newDefaults) {\n _defaults = newDefaults;\n}\n","/**\n * Helpers\n */\nconst escapeTest = /[&<>\"']/;\nconst escapeReplace = new RegExp(escapeTest.source, 'g');\nconst escapeTestNoEncode = /[<>\"']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/;\nconst escapeReplaceNoEncode = new RegExp(escapeTestNoEncode.source, 'g');\nconst escapeReplacements = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": '''\n};\nconst getEscapeReplacement = (ch) => escapeReplacements[ch];\nexport function escape(html, encode) {\n if (encode) {\n if (escapeTest.test(html)) {\n return html.replace(escapeReplace, getEscapeReplacement);\n }\n }\n else {\n if (escapeTestNoEncode.test(html)) {\n return html.replace(escapeReplaceNoEncode, getEscapeReplacement);\n }\n }\n return html;\n}\nconst unescapeTest = /&(#(?:\\d+)|(?:#x[0-9A-Fa-f]+)|(?:\\w+));?/ig;\nexport function unescape(html) {\n // explicitly match decimal, hex, and named HTML entities\n return html.replace(unescapeTest, (_, n) => {\n n = n.toLowerCase();\n if (n === 'colon')\n return ':';\n if (n.charAt(0) === '#') {\n return n.charAt(1) === 'x'\n ? String.fromCharCode(parseInt(n.substring(2), 16))\n : String.fromCharCode(+n.substring(1));\n }\n return '';\n });\n}\nconst caret = /(^|[^\\[])\\^/g;\nexport function edit(regex, opt) {\n let source = typeof regex === 'string' ? regex : regex.source;\n opt = opt || '';\n const obj = {\n replace: (name, val) => {\n let valSource = typeof val === 'string' ? val : val.source;\n valSource = valSource.replace(caret, '$1');\n source = source.replace(name, valSource);\n return obj;\n },\n getRegex: () => {\n return new RegExp(source, opt);\n }\n };\n return obj;\n}\nexport function cleanUrl(href) {\n try {\n href = encodeURI(href).replace(/%25/g, '%');\n }\n catch (e) {\n return null;\n }\n return href;\n}\nexport const noopTest = { exec: () => null };\nexport function splitCells(tableRow, count) {\n // ensure that every cell-delimiting pipe has a space\n // before it to distinguish it from an escaped pipe\n const row = tableRow.replace(/\\|/g, (match, offset, str) => {\n let escaped = false;\n let curr = offset;\n while (--curr >= 0 && str[curr] === '\\\\')\n escaped = !escaped;\n if (escaped) {\n // odd number of slashes means | is escaped\n // so we leave it alone\n return '|';\n }\n else {\n // add space before unescaped |\n return ' |';\n }\n }), cells = row.split(/ \\|/);\n let i = 0;\n // First/last cell in a row cannot be empty if it has no leading/trailing pipe\n if (!cells[0].trim()) {\n cells.shift();\n }\n if (cells.length > 0 && !cells[cells.length - 1].trim()) {\n cells.pop();\n }\n if (count) {\n if (cells.length > count) {\n cells.splice(count);\n }\n else {\n while (cells.length < count)\n cells.push('');\n }\n }\n for (; i < cells.length; i++) {\n // leading or trailing whitespace is ignored per the gfm spec\n cells[i] = cells[i].trim().replace(/\\\\\\|/g, '|');\n }\n return cells;\n}\n/**\n * Remove trailing 'c's. Equivalent to str.replace(/c*$/, '').\n * /c*$/ is vulnerable to REDOS.\n *\n * @param str\n * @param c\n * @param invert Remove suffix of non-c chars instead. Default falsey.\n */\nexport function rtrim(str, c, invert) {\n const l = str.length;\n if (l === 0) {\n return '';\n }\n // Length of suffix matching the invert condition.\n let suffLen = 0;\n // Step left until we fail to match the invert condition.\n while (suffLen < l) {\n const currChar = str.charAt(l - suffLen - 1);\n if (currChar === c && !invert) {\n suffLen++;\n }\n else if (currChar !== c && invert) {\n suffLen++;\n }\n else {\n break;\n }\n }\n return str.slice(0, l - suffLen);\n}\nexport function findClosingBracket(str, b) {\n if (str.indexOf(b[1]) === -1) {\n return -1;\n }\n let level = 0;\n for (let i = 0; i < str.length; i++) {\n if (str[i] === '\\\\') {\n i++;\n }\n else if (str[i] === b[0]) {\n level++;\n }\n else if (str[i] === b[1]) {\n level--;\n if (level < 0) {\n return i;\n }\n }\n }\n return -1;\n}\n","import { _defaults } from './defaults.ts';\nimport { rtrim, splitCells, escape, findClosingBracket } from './helpers.ts';\nfunction outputLink(cap, link, raw, lexer) {\n const href = link.href;\n const title = link.title ? escape(link.title) : null;\n const text = cap[1].replace(/\\\\([\\[\\]])/g, '$1');\n if (cap[0].charAt(0) !== '!') {\n lexer.state.inLink = true;\n const token = {\n type: 'link',\n raw,\n href,\n title,\n text,\n tokens: lexer.inlineTokens(text)\n };\n lexer.state.inLink = false;\n return token;\n }\n return {\n type: 'image',\n raw,\n href,\n title,\n text: escape(text)\n };\n}\nfunction indentCodeCompensation(raw, text) {\n const matchIndentToCode = raw.match(/^(\\s+)(?:```)/);\n if (matchIndentToCode === null) {\n return text;\n }\n const indentToCode = matchIndentToCode[1];\n return text\n .split('\\n')\n .map(node => {\n const matchIndentInNode = node.match(/^\\s+/);\n if (matchIndentInNode === null) {\n return node;\n }\n const [indentInNode] = matchIndentInNode;\n if (indentInNode.length >= indentToCode.length) {\n return node.slice(indentToCode.length);\n }\n return node;\n })\n .join('\\n');\n}\n/**\n * Tokenizer\n */\nexport class _Tokenizer {\n options;\n rules; // set by the lexer\n lexer; // set by the lexer\n constructor(options) {\n this.options = options || _defaults;\n }\n space(src) {\n const cap = this.rules.block.newline.exec(src);\n if (cap && cap[0].length > 0) {\n return {\n type: 'space',\n raw: cap[0]\n };\n }\n }\n code(src) {\n const cap = this.rules.block.code.exec(src);\n if (cap) {\n const text = cap[0].replace(/^ {1,4}/gm, '');\n return {\n type: 'code',\n raw: cap[0],\n codeBlockStyle: 'indented',\n text: !this.options.pedantic\n ? rtrim(text, '\\n')\n : text\n };\n }\n }\n fences(src) {\n const cap = this.rules.block.fences.exec(src);\n if (cap) {\n const raw = cap[0];\n const text = indentCodeCompensation(raw, cap[3] || '');\n return {\n type: 'code',\n raw,\n lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, '$1') : cap[2],\n text\n };\n }\n }\n heading(src) {\n const cap = this.rules.block.heading.exec(src);\n if (cap) {\n let text = cap[2].trim();\n // remove trailing #s\n if (/#$/.test(text)) {\n const trimmed = rtrim(text, '#');\n if (this.options.pedantic) {\n text = trimmed.trim();\n }\n else if (!trimmed || / $/.test(trimmed)) {\n // CommonMark requires space before trailing #s\n text = trimmed.trim();\n }\n }\n return {\n type: 'heading',\n raw: cap[0],\n depth: cap[1].length,\n text,\n tokens: this.lexer.inline(text)\n };\n }\n }\n hr(src) {\n const cap = this.rules.block.hr.exec(src);\n if (cap) {\n return {\n type: 'hr',\n raw: rtrim(cap[0], '\\n')\n };\n }\n }\n blockquote(src) {\n const cap = this.rules.block.blockquote.exec(src);\n if (cap) {\n let lines = rtrim(cap[0], '\\n').split('\\n');\n let raw = '';\n let text = '';\n const tokens = [];\n while (lines.length > 0) {\n let inBlockquote = false;\n const currentLines = [];\n let i;\n for (i = 0; i < lines.length; i++) {\n // get lines up to a continuation\n if (/^ {0,3}>/.test(lines[i])) {\n currentLines.push(lines[i]);\n inBlockquote = true;\n }\n else if (!inBlockquote) {\n currentLines.push(lines[i]);\n }\n else {\n break;\n }\n }\n lines = lines.slice(i);\n const currentRaw = currentLines.join('\\n');\n const currentText = currentRaw\n // precede setext continuation with 4 spaces so it isn't a setext\n .replace(/\\n {0,3}((?:=+|-+) *)(?=\\n|$)/g, '\\n $1')\n .replace(/^ {0,3}>[ \\t]?/gm, '');\n raw = raw ? `${raw}\\n${currentRaw}` : currentRaw;\n text = text ? `${text}\\n${currentText}` : currentText;\n // parse blockquote lines as top level tokens\n // merge paragraphs if this is a continuation\n const top = this.lexer.state.top;\n this.lexer.state.top = true;\n this.lexer.blockTokens(currentText, tokens, true);\n this.lexer.state.top = top;\n // if there is no continuation then we are done\n if (lines.length === 0) {\n break;\n }\n const lastToken = tokens[tokens.length - 1];\n if (lastToken?.type === 'code') {\n // blockquote continuation cannot be preceded by a code block\n break;\n }\n else if (lastToken?.type === 'blockquote') {\n // include continuation in nested blockquote\n const oldToken = lastToken;\n const newText = oldToken.raw + '\\n' + lines.join('\\n');\n const newToken = this.blockquote(newText);\n tokens[tokens.length - 1] = newToken;\n raw = raw.substring(0, raw.length - oldToken.raw.length) + newToken.raw;\n text = text.substring(0, text.length - oldToken.text.length) + newToken.text;\n break;\n }\n else if (lastToken?.type === 'list') {\n // include continuation in nested list\n const oldToken = lastToken;\n const newText = oldToken.raw + '\\n' + lines.join('\\n');\n const newToken = this.list(newText);\n tokens[tokens.length - 1] = newToken;\n raw = raw.substring(0, raw.length - lastToken.raw.length) + newToken.raw;\n text = text.substring(0, text.length - oldToken.raw.length) + newToken.raw;\n lines = newText.substring(tokens[tokens.length - 1].raw.length).split('\\n');\n continue;\n }\n }\n return {\n type: 'blockquote',\n raw,\n tokens,\n text\n };\n }\n }\n list(src) {\n let cap = this.rules.block.list.exec(src);\n if (cap) {\n let bull = cap[1].trim();\n const isordered = bull.length > 1;\n const list = {\n type: 'list',\n raw: '',\n ordered: isordered,\n start: isordered ? +bull.slice(0, -1) : '',\n loose: false,\n items: []\n };\n bull = isordered ? `\\\\d{1,9}\\\\${bull.slice(-1)}` : `\\\\${bull}`;\n if (this.options.pedantic) {\n bull = isordered ? bull : '[*+-]';\n }\n // Get next list item\n const itemRegex = new RegExp(`^( {0,3}${bull})((?:[\\t ][^\\\\n]*)?(?:\\\\n|$))`);\n let raw = '';\n let itemContents = '';\n let endsWithBlankLine = false;\n // Check if current bullet point can start a new List Item\n while (src) {\n let endEarly = false;\n if (!(cap = itemRegex.exec(src))) {\n break;\n }\n if (this.rules.block.hr.test(src)) { // End list if bullet was actually HR (possibly move into itemRegex?)\n break;\n }\n raw = cap[0];\n src = src.substring(raw.length);\n let line = cap[2].split('\\n', 1)[0].replace(/^\\t+/, (t) => ' '.repeat(3 * t.length));\n let nextLine = src.split('\\n', 1)[0];\n let indent = 0;\n if (this.options.pedantic) {\n indent = 2;\n itemContents = line.trimStart();\n }\n else {\n indent = cap[2].search(/[^ ]/); // Find first non-space char\n indent = indent > 4 ? 1 : indent; // Treat indented code blocks (> 4 spaces) as having only 1 indent\n itemContents = line.slice(indent);\n indent += cap[1].length;\n }\n let blankLine = false;\n if (!line && /^ *$/.test(nextLine)) { // Items begin with at most one blank line\n raw += nextLine + '\\n';\n src = src.substring(nextLine.length + 1);\n endEarly = true;\n }\n if (!endEarly) {\n const nextBulletRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\\\d{1,9}[.)])((?:[ \\t][^\\\\n]*)?(?:\\\\n|$))`);\n const hrRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\\\* *){3,})(?:\\\\n+|$)`);\n const fencesBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\\`\\`\\`|~~~)`);\n const headingBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`);\n // Check if following lines should be included in List Item\n while (src) {\n const rawLine = src.split('\\n', 1)[0];\n nextLine = rawLine;\n // Re-align to follow commonmark nesting rules\n if (this.options.pedantic) {\n nextLine = nextLine.replace(/^ {1,4}(?=( {4})*[^ ])/g, ' ');\n }\n // End list item if found code fences\n if (fencesBeginRegex.test(nextLine)) {\n break;\n }\n // End list item if found start of new heading\n if (headingBeginRegex.test(nextLine)) {\n break;\n }\n // End list item if found start of new bullet\n if (nextBulletRegex.test(nextLine)) {\n break;\n }\n // Horizontal rule found\n if (hrRegex.test(src)) {\n break;\n }\n if (nextLine.search(/[^ ]/) >= indent || !nextLine.trim()) { // Dedent if possible\n itemContents += '\\n' + nextLine.slice(indent);\n }\n else {\n // not enough indentation\n if (blankLine) {\n break;\n }\n // paragraph continuation unless last line was a different block level element\n if (line.search(/[^ ]/) >= 4) { // indented code block\n break;\n }\n if (fencesBeginRegex.test(line)) {\n break;\n }\n if (headingBeginRegex.test(line)) {\n break;\n }\n if (hrRegex.test(line)) {\n break;\n }\n itemContents += '\\n' + nextLine;\n }\n if (!blankLine && !nextLine.trim()) { // Check if current line is blank\n blankLine = true;\n }\n raw += rawLine + '\\n';\n src = src.substring(rawLine.length + 1);\n line = nextLine.slice(indent);\n }\n }\n if (!list.loose) {\n // If the previous item ended with a blank line, the list is loose\n if (endsWithBlankLine) {\n list.loose = true;\n }\n else if (/\\n *\\n *$/.test(raw)) {\n endsWithBlankLine = true;\n }\n }\n let istask = null;\n let ischecked;\n // Check for task list items\n if (this.options.gfm) {\n istask = /^\\[[ xX]\\] /.exec(itemContents);\n if (istask) {\n ischecked = istask[0] !== '[ ] ';\n itemContents = itemContents.replace(/^\\[[ xX]\\] +/, '');\n }\n }\n list.items.push({\n type: 'list_item',\n raw,\n task: !!istask,\n checked: ischecked,\n loose: false,\n text: itemContents,\n tokens: []\n });\n list.raw += raw;\n }\n // Do not consume newlines at end of final item. Alternatively, make itemRegex *start* with any newlines to simplify/speed up endsWithBlankLine logic\n list.items[list.items.length - 1].raw = raw.trimEnd();\n (list.items[list.items.length - 1]).text = itemContents.trimEnd();\n list.raw = list.raw.trimEnd();\n // Item child tokens handled here at end because we needed to have the final item to trim it first\n for (let i = 0; i < list.items.length; i++) {\n this.lexer.state.top = false;\n list.items[i].tokens = this.lexer.blockTokens(list.items[i].text, []);\n if (!list.loose) {\n // Check if list should be loose\n const spacers = list.items[i].tokens.filter(t => t.type === 'space');\n const hasMultipleLineBreaks = spacers.length > 0 && spacers.some(t => /\\n.*\\n/.test(t.raw));\n list.loose = hasMultipleLineBreaks;\n }\n }\n // Set all items to loose if list is loose\n if (list.loose) {\n for (let i = 0; i < list.items.length; i++) {\n list.items[i].loose = true;\n }\n }\n return list;\n }\n }\n html(src) {\n const cap = this.rules.block.html.exec(src);\n if (cap) {\n const token = {\n type: 'html',\n block: true,\n raw: cap[0],\n pre: cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style',\n text: cap[0]\n };\n return token;\n }\n }\n def(src) {\n const cap = this.rules.block.def.exec(src);\n if (cap) {\n const tag = cap[1].toLowerCase().replace(/\\s+/g, ' ');\n const href = cap[2] ? cap[2].replace(/^<(.*)>$/, '$1').replace(this.rules.inline.anyPunctuation, '$1') : '';\n const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, '$1') : cap[3];\n return {\n type: 'def',\n tag,\n raw: cap[0],\n href,\n title\n };\n }\n }\n table(src) {\n const cap = this.rules.block.table.exec(src);\n if (!cap) {\n return;\n }\n if (!/[:|]/.test(cap[2])) {\n // delimiter row must have a pipe (|) or colon (:) otherwise it is a setext heading\n return;\n }\n const headers = splitCells(cap[1]);\n const aligns = cap[2].replace(/^\\||\\| *$/g, '').split('|');\n const rows = cap[3] && cap[3].trim() ? cap[3].replace(/\\n[ \\t]*$/, '').split('\\n') : [];\n const item = {\n type: 'table',\n raw: cap[0],\n header: [],\n align: [],\n rows: []\n };\n if (headers.length !== aligns.length) {\n // header and align columns must be equal, rows can be different.\n return;\n }\n for (const align of aligns) {\n if (/^ *-+: *$/.test(align)) {\n item.align.push('right');\n }\n else if (/^ *:-+: *$/.test(align)) {\n item.align.push('center');\n }\n else if (/^ *:-+ *$/.test(align)) {\n item.align.push('left');\n }\n else {\n item.align.push(null);\n }\n }\n for (let i = 0; i < headers.length; i++) {\n item.header.push({\n text: headers[i],\n tokens: this.lexer.inline(headers[i]),\n header: true,\n align: item.align[i]\n });\n }\n for (const row of rows) {\n item.rows.push(splitCells(row, item.header.length).map((cell, i) => {\n return {\n text: cell,\n tokens: this.lexer.inline(cell),\n header: false,\n align: item.align[i]\n };\n }));\n }\n return item;\n }\n lheading(src) {\n const cap = this.rules.block.lheading.exec(src);\n if (cap) {\n return {\n type: 'heading',\n raw: cap[0],\n depth: cap[2].charAt(0) === '=' ? 1 : 2,\n text: cap[1],\n tokens: this.lexer.inline(cap[1])\n };\n }\n }\n paragraph(src) {\n const cap = this.rules.block.paragraph.exec(src);\n if (cap) {\n const text = cap[1].charAt(cap[1].length - 1) === '\\n'\n ? cap[1].slice(0, -1)\n : cap[1];\n return {\n type: 'paragraph',\n raw: cap[0],\n text,\n tokens: this.lexer.inline(text)\n };\n }\n }\n text(src) {\n const cap = this.rules.block.text.exec(src);\n if (cap) {\n return {\n type: 'text',\n raw: cap[0],\n text: cap[0],\n tokens: this.lexer.inline(cap[0])\n };\n }\n }\n escape(src) {\n const cap = this.rules.inline.escape.exec(src);\n if (cap) {\n return {\n type: 'escape',\n raw: cap[0],\n text: escape(cap[1])\n };\n }\n }\n tag(src) {\n const cap = this.rules.inline.tag.exec(src);\n if (cap) {\n if (!this.lexer.state.inLink && /^
    /i.test(cap[0])) {\n this.lexer.state.inLink = false;\n }\n if (!this.lexer.state.inRawBlock && /^<(pre|code|kbd|script)(\\s|>)/i.test(cap[0])) {\n this.lexer.state.inRawBlock = true;\n }\n else if (this.lexer.state.inRawBlock && /^<\\/(pre|code|kbd|script)(\\s|>)/i.test(cap[0])) {\n this.lexer.state.inRawBlock = false;\n }\n return {\n type: 'html',\n raw: cap[0],\n inLink: this.lexer.state.inLink,\n inRawBlock: this.lexer.state.inRawBlock,\n block: false,\n text: cap[0]\n };\n }\n }\n link(src) {\n const cap = this.rules.inline.link.exec(src);\n if (cap) {\n const trimmedUrl = cap[2].trim();\n if (!this.options.pedantic && /^$/.test(trimmedUrl))) {\n return;\n }\n // ending angle bracket cannot be escaped\n const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), '\\\\');\n if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) {\n return;\n }\n }\n else {\n // find closing parenthesis\n const lastParenIndex = findClosingBracket(cap[2], '()');\n if (lastParenIndex > -1) {\n const start = cap[0].indexOf('!') === 0 ? 5 : 4;\n const linkLen = start + cap[1].length + lastParenIndex;\n cap[2] = cap[2].substring(0, lastParenIndex);\n cap[0] = cap[0].substring(0, linkLen).trim();\n cap[3] = '';\n }\n }\n let href = cap[2];\n let title = '';\n if (this.options.pedantic) {\n // split pedantic href and title\n const link = /^([^'\"]*[^\\s])\\s+(['\"])(.*)\\2/.exec(href);\n if (link) {\n href = link[1];\n title = link[3];\n }\n }\n else {\n title = cap[3] ? cap[3].slice(1, -1) : '';\n }\n href = href.trim();\n if (/^$/.test(trimmedUrl))) {\n // pedantic allows starting angle bracket without ending angle bracket\n href = href.slice(1);\n }\n else {\n href = href.slice(1, -1);\n }\n }\n return outputLink(cap, {\n href: href ? href.replace(this.rules.inline.anyPunctuation, '$1') : href,\n title: title ? title.replace(this.rules.inline.anyPunctuation, '$1') : title\n }, cap[0], this.lexer);\n }\n }\n reflink(src, links) {\n let cap;\n if ((cap = this.rules.inline.reflink.exec(src))\n || (cap = this.rules.inline.nolink.exec(src))) {\n const linkString = (cap[2] || cap[1]).replace(/\\s+/g, ' ');\n const link = links[linkString.toLowerCase()];\n if (!link) {\n const text = cap[0].charAt(0);\n return {\n type: 'text',\n raw: text,\n text\n };\n }\n return outputLink(cap, link, cap[0], this.lexer);\n }\n }\n emStrong(src, maskedSrc, prevChar = '') {\n let match = this.rules.inline.emStrongLDelim.exec(src);\n if (!match)\n return;\n // _ can't be between two alphanumerics. \\p{L}\\p{N} includes non-english alphabet/numbers as well\n if (match[3] && prevChar.match(/[\\p{L}\\p{N}]/u))\n return;\n const nextChar = match[1] || match[2] || '';\n if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) {\n // unicode Regex counts emoji as 1 char; spread into array for proper count (used multiple times below)\n const lLength = [...match[0]].length - 1;\n let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0;\n const endReg = match[0][0] === '*' ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;\n endReg.lastIndex = 0;\n // Clip maskedSrc to same section of string as src (move to lexer?)\n maskedSrc = maskedSrc.slice(-1 * src.length + lLength);\n while ((match = endReg.exec(maskedSrc)) != null) {\n rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6];\n if (!rDelim)\n continue; // skip single * in __abc*abc__\n rLength = [...rDelim].length;\n if (match[3] || match[4]) { // found another Left Delim\n delimTotal += rLength;\n continue;\n }\n else if (match[5] || match[6]) { // either Left or Right Delim\n if (lLength % 3 && !((lLength + rLength) % 3)) {\n midDelimTotal += rLength;\n continue; // CommonMark Emphasis Rules 9-10\n }\n }\n delimTotal -= rLength;\n if (delimTotal > 0)\n continue; // Haven't found enough closing delimiters\n // Remove extra characters. *a*** -> *a*\n rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal);\n // char length can be >1 for unicode characters;\n const lastCharLength = [...match[0]][0].length;\n const raw = src.slice(0, lLength + match.index + lastCharLength + rLength);\n // Create `em` if smallest delimiter has odd char count. *a***\n if (Math.min(lLength, rLength) % 2) {\n const text = raw.slice(1, -1);\n return {\n type: 'em',\n raw,\n text,\n tokens: this.lexer.inlineTokens(text)\n };\n }\n // Create 'strong' if smallest delimiter has even char count. **a***\n const text = raw.slice(2, -2);\n return {\n type: 'strong',\n raw,\n text,\n tokens: this.lexer.inlineTokens(text)\n };\n }\n }\n }\n codespan(src) {\n const cap = this.rules.inline.code.exec(src);\n if (cap) {\n let text = cap[2].replace(/\\n/g, ' ');\n const hasNonSpaceChars = /[^ ]/.test(text);\n const hasSpaceCharsOnBothEnds = /^ /.test(text) && / $/.test(text);\n if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {\n text = text.substring(1, text.length - 1);\n }\n text = escape(text, true);\n return {\n type: 'codespan',\n raw: cap[0],\n text\n };\n }\n }\n br(src) {\n const cap = this.rules.inline.br.exec(src);\n if (cap) {\n return {\n type: 'br',\n raw: cap[0]\n };\n }\n }\n del(src) {\n const cap = this.rules.inline.del.exec(src);\n if (cap) {\n return {\n type: 'del',\n raw: cap[0],\n text: cap[2],\n tokens: this.lexer.inlineTokens(cap[2])\n };\n }\n }\n autolink(src) {\n const cap = this.rules.inline.autolink.exec(src);\n if (cap) {\n let text, href;\n if (cap[2] === '@') {\n text = escape(cap[1]);\n href = 'mailto:' + text;\n }\n else {\n text = escape(cap[1]);\n href = text;\n }\n return {\n type: 'link',\n raw: cap[0],\n text,\n href,\n tokens: [\n {\n type: 'text',\n raw: text,\n text\n }\n ]\n };\n }\n }\n url(src) {\n let cap;\n if (cap = this.rules.inline.url.exec(src)) {\n let text, href;\n if (cap[2] === '@') {\n text = escape(cap[0]);\n href = 'mailto:' + text;\n }\n else {\n // do extended autolink path validation\n let prevCapZero;\n do {\n prevCapZero = cap[0];\n cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? '';\n } while (prevCapZero !== cap[0]);\n text = escape(cap[0]);\n if (cap[1] === 'www.') {\n href = 'http://' + cap[0];\n }\n else {\n href = cap[0];\n }\n }\n return {\n type: 'link',\n raw: cap[0],\n text,\n href,\n tokens: [\n {\n type: 'text',\n raw: text,\n text\n }\n ]\n };\n }\n }\n inlineText(src) {\n const cap = this.rules.inline.text.exec(src);\n if (cap) {\n let text;\n if (this.lexer.state.inRawBlock) {\n text = cap[0];\n }\n else {\n text = escape(cap[0]);\n }\n return {\n type: 'text',\n raw: cap[0],\n text\n };\n }\n }\n}\n","import { edit, noopTest } from './helpers.ts';\n/**\n * Block-Level Grammar\n */\nconst newline = /^(?: *(?:\\n|$))+/;\nconst blockCode = /^( {4}[^\\n]+(?:\\n(?: *(?:\\n|$))*)?)+/;\nconst fences = /^ {0,3}(`{3,}(?=[^`\\n]*(?:\\n|$))|~{3,})([^\\n]*)(?:\\n|$)(?:|([\\s\\S]*?)(?:\\n|$))(?: {0,3}\\1[~`]* *(?=\\n|$)|$)/;\nconst hr = /^ {0,3}((?:-[\\t ]*){3,}|(?:_[ \\t]*){3,}|(?:\\*[ \\t]*){3,})(?:\\n+|$)/;\nconst heading = /^ {0,3}(#{1,6})(?=\\s|$)(.*)(?:\\n+|$)/;\nconst bullet = /(?:[*+-]|\\d{1,9}[.)])/;\nconst lheading = edit(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\\n(?!\\s*?\\n|bull |blockCode|fences|blockquote|heading|html))+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/)\n .replace(/bull/g, bullet) // lists can interrupt\n .replace(/blockCode/g, / {4}/) // indented code blocks can interrupt\n .replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/) // fenced code blocks can interrupt\n .replace(/blockquote/g, / {0,3}>/) // blockquote can interrupt\n .replace(/heading/g, / {0,3}#{1,6}/) // ATX heading can interrupt\n .replace(/html/g, / {0,3}<[^\\n>]+>\\n/) // block html can interrupt\n .getRegex();\nconst _paragraph = /^([^\\n]+(?:\\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\\n)[^\\n]+)*)/;\nconst blockText = /^[^\\n]+/;\nconst _blockLabel = /(?!\\s*\\])(?:\\\\.|[^\\[\\]\\\\])+/;\nconst def = edit(/^ {0,3}\\[(label)\\]: *(?:\\n *)?([^<\\s][^\\s]*|<.*?>)(?:(?: +(?:\\n *)?| *\\n *)(title))? *(?:\\n+|$)/)\n .replace('label', _blockLabel)\n .replace('title', /(?:\"(?:\\\\\"?|[^\"\\\\])*\"|'[^'\\n]*(?:\\n[^'\\n]+)*\\n?'|\\([^()]*\\))/)\n .getRegex();\nconst list = edit(/^( {0,3}bull)([ \\t][^\\n]+?)?(?:\\n|$)/)\n .replace(/bull/g, bullet)\n .getRegex();\nconst _tag = 'address|article|aside|base|basefont|blockquote|body|caption'\n + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption'\n + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe'\n + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option'\n + '|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title'\n + '|tr|track|ul';\nconst _comment = /|$))/;\nconst html = edit('^ {0,3}(?:' // optional indentation\n + '<(script|pre|style|textarea)[\\\\s>][\\\\s\\\\S]*?(?:[^\\\\n]*\\\\n+|$)' // (1)\n + '|comment[^\\\\n]*(\\\\n+|$)' // (2)\n + '|<\\\\?[\\\\s\\\\S]*?(?:\\\\?>\\\\n*|$)' // (3)\n + '|\\\\n*|$)' // (4)\n + '|\\\\n*|$)' // (5)\n + '|)[\\\\s\\\\S]*?(?:(?:\\\\n *)+\\\\n|$)' // (6)\n + '|<(?!script|pre|style|textarea)([a-z][\\\\w-]*)(?:attribute)*? */?>(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n *)+\\\\n|$)' // (7) open tag\n + '|(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n *)+\\\\n|$)' // (7) closing tag\n + ')', 'i')\n .replace('comment', _comment)\n .replace('tag', _tag)\n .replace('attribute', / +[a-zA-Z:_][\\w.:-]*(?: *= *\"[^\"\\n]*\"| *= *'[^'\\n]*'| *= *[^\\s\"'=<>`]+)?/)\n .getRegex();\nconst paragraph = edit(_paragraph)\n .replace('hr', hr)\n .replace('heading', ' {0,3}#{1,6}(?:\\\\s|$)')\n .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs\n .replace('|table', '')\n .replace('blockquote', ' {0,3}>')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n')\n .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt\n .replace('html', ')|<(?:script|pre|style|textarea|!--)')\n .replace('tag', _tag) // pars can be interrupted by type (6) html blocks\n .getRegex();\nconst blockquote = edit(/^( {0,3}> ?(paragraph|[^\\n]*)(?:\\n|$))+/)\n .replace('paragraph', paragraph)\n .getRegex();\n/**\n * Normal Block Grammar\n */\nconst blockNormal = {\n blockquote,\n code: blockCode,\n def,\n fences,\n heading,\n hr,\n html,\n lheading,\n list,\n newline,\n paragraph,\n table: noopTest,\n text: blockText\n};\n/**\n * GFM Block Grammar\n */\nconst gfmTable = edit('^ *([^\\\\n ].*)\\\\n' // Header\n + ' {0,3}((?:\\\\| *)?:?-+:? *(?:\\\\| *:?-+:? *)*(?:\\\\| *)?)' // Align\n + '(?:\\\\n((?:(?! *\\\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\\\n|$))*)\\\\n*|$)') // Cells\n .replace('hr', hr)\n .replace('heading', ' {0,3}#{1,6}(?:\\\\s|$)')\n .replace('blockquote', ' {0,3}>')\n .replace('code', ' {4}[^\\\\n]')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n')\n .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt\n .replace('html', ')|<(?:script|pre|style|textarea|!--)')\n .replace('tag', _tag) // tables can be interrupted by type (6) html blocks\n .getRegex();\nconst blockGfm = {\n ...blockNormal,\n table: gfmTable,\n paragraph: edit(_paragraph)\n .replace('hr', hr)\n .replace('heading', ' {0,3}#{1,6}(?:\\\\s|$)')\n .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs\n .replace('table', gfmTable) // interrupt paragraphs with table\n .replace('blockquote', ' {0,3}>')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n')\n .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt\n .replace('html', ')|<(?:script|pre|style|textarea|!--)')\n .replace('tag', _tag) // pars can be interrupted by type (6) html blocks\n .getRegex()\n};\n/**\n * Pedantic grammar (original John Gruber's loose markdown specification)\n */\nconst blockPedantic = {\n ...blockNormal,\n html: edit('^ *(?:comment *(?:\\\\n|\\\\s*$)'\n + '|<(tag)[\\\\s\\\\S]+? *(?:\\\\n{2,}|\\\\s*$)' // closed tag\n + '|\\\\s]*)*?/?> *(?:\\\\n{2,}|\\\\s*$))')\n .replace('comment', _comment)\n .replace(/tag/g, '(?!(?:'\n + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub'\n + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)'\n + '\\\\b)\\\\w+(?!:|[^\\\\w\\\\s@]*@)\\\\b')\n .getRegex(),\n def: /^ *\\[([^\\]]+)\\]: *]+)>?(?: +([\"(][^\\n]+[\")]))? *(?:\\n+|$)/,\n heading: /^(#{1,6})(.*)(?:\\n+|$)/,\n fences: noopTest, // fences not supported\n lheading: /^(.+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/,\n paragraph: edit(_paragraph)\n .replace('hr', hr)\n .replace('heading', ' *#{1,6} *[^\\n]')\n .replace('lheading', lheading)\n .replace('|table', '')\n .replace('blockquote', ' {0,3}>')\n .replace('|fences', '')\n .replace('|list', '')\n .replace('|html', '')\n .replace('|tag', '')\n .getRegex()\n};\n/**\n * Inline-Level Grammar\n */\nconst escape = /^\\\\([!\"#$%&'()*+,\\-./:;<=>?@\\[\\]\\\\^_`{|}~])/;\nconst inlineCode = /^(`+)([^`]|[^`][\\s\\S]*?[^`])\\1(?!`)/;\nconst br = /^( {2,}|\\\\)\\n(?!\\s*$)/;\nconst inlineText = /^(`+|[^`])(?:(?= {2,}\\n)|[\\s\\S]*?(?:(?=[\\\\\nconst blockSkip = /\\[[^[\\]]*?\\]\\([^\\(\\)]*?\\)|`[^`]*?`|<[^<>]*?>/g;\nconst emStrongLDelim = edit(/^(?:\\*+(?:((?!\\*)[punct])|[^\\s*]))|^_+(?:((?!_)[punct])|([^\\s_]))/, 'u')\n .replace(/punct/g, _punctuation)\n .getRegex();\nconst emStrongRDelimAst = edit('^[^_*]*?__[^_*]*?\\\\*[^_*]*?(?=__)' // Skip orphan inside strong\n + '|[^*]+(?=[^*])' // Consume to delim\n + '|(?!\\\\*)[punct](\\\\*+)(?=[\\\\s]|$)' // (1) #*** can only be a Right Delimiter\n + '|[^punct\\\\s](\\\\*+)(?!\\\\*)(?=[punct\\\\s]|$)' // (2) a***#, a*** can only be a Right Delimiter\n + '|(?!\\\\*)[punct\\\\s](\\\\*+)(?=[^punct\\\\s])' // (3) #***a, ***a can only be Left Delimiter\n + '|[\\\\s](\\\\*+)(?!\\\\*)(?=[punct])' // (4) ***# can only be Left Delimiter\n + '|(?!\\\\*)[punct](\\\\*+)(?!\\\\*)(?=[punct])' // (5) #***# can be either Left or Right Delimiter\n + '|[^punct\\\\s](\\\\*+)(?=[^punct\\\\s])', 'gu') // (6) a***a can be either Left or Right Delimiter\n .replace(/punct/g, _punctuation)\n .getRegex();\n// (6) Not allowed for _\nconst emStrongRDelimUnd = edit('^[^_*]*?\\\\*\\\\*[^_*]*?_[^_*]*?(?=\\\\*\\\\*)' // Skip orphan inside strong\n + '|[^_]+(?=[^_])' // Consume to delim\n + '|(?!_)[punct](_+)(?=[\\\\s]|$)' // (1) #___ can only be a Right Delimiter\n + '|[^punct\\\\s](_+)(?!_)(?=[punct\\\\s]|$)' // (2) a___#, a___ can only be a Right Delimiter\n + '|(?!_)[punct\\\\s](_+)(?=[^punct\\\\s])' // (3) #___a, ___a can only be Left Delimiter\n + '|[\\\\s](_+)(?!_)(?=[punct])' // (4) ___# can only be Left Delimiter\n + '|(?!_)[punct](_+)(?!_)(?=[punct])', 'gu') // (5) #___# can be either Left or Right Delimiter\n .replace(/punct/g, _punctuation)\n .getRegex();\nconst anyPunctuation = edit(/\\\\([punct])/, 'gu')\n .replace(/punct/g, _punctuation)\n .getRegex();\nconst autolink = edit(/^<(scheme:[^\\s\\x00-\\x1f<>]*|email)>/)\n .replace('scheme', /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/)\n .replace('email', /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/)\n .getRegex();\nconst _inlineComment = edit(_comment).replace('(?:-->|$)', '-->').getRegex();\nconst tag = edit('^comment'\n + '|^' // self-closing tag\n + '|^<[a-zA-Z][\\\\w-]*(?:attribute)*?\\\\s*/?>' // open tag\n + '|^<\\\\?[\\\\s\\\\S]*?\\\\?>' // processing instruction, e.g. \n + '|^' // declaration, e.g. \n + '|^') // CDATA section\n .replace('comment', _inlineComment)\n .replace('attribute', /\\s+[a-zA-Z:_][\\w.:-]*(?:\\s*=\\s*\"[^\"]*\"|\\s*=\\s*'[^']*'|\\s*=\\s*[^\\s\"'=<>`]+)?/)\n .getRegex();\nconst _inlineLabel = /(?:\\[(?:\\\\.|[^\\[\\]\\\\])*\\]|\\\\.|`[^`]*`|[^\\[\\]\\\\`])*?/;\nconst link = edit(/^!?\\[(label)\\]\\(\\s*(href)(?:\\s+(title))?\\s*\\)/)\n .replace('label', _inlineLabel)\n .replace('href', /<(?:\\\\.|[^\\n<>\\\\])+>|[^\\s\\x00-\\x1f]*/)\n .replace('title', /\"(?:\\\\\"?|[^\"\\\\])*\"|'(?:\\\\'?|[^'\\\\])*'|\\((?:\\\\\\)?|[^)\\\\])*\\)/)\n .getRegex();\nconst reflink = edit(/^!?\\[(label)\\]\\[(ref)\\]/)\n .replace('label', _inlineLabel)\n .replace('ref', _blockLabel)\n .getRegex();\nconst nolink = edit(/^!?\\[(ref)\\](?:\\[\\])?/)\n .replace('ref', _blockLabel)\n .getRegex();\nconst reflinkSearch = edit('reflink|nolink(?!\\\\()', 'g')\n .replace('reflink', reflink)\n .replace('nolink', nolink)\n .getRegex();\n/**\n * Normal Inline Grammar\n */\nconst inlineNormal = {\n _backpedal: noopTest, // only used for GFM url\n anyPunctuation,\n autolink,\n blockSkip,\n br,\n code: inlineCode,\n del: noopTest,\n emStrongLDelim,\n emStrongRDelimAst,\n emStrongRDelimUnd,\n escape,\n link,\n nolink,\n punctuation,\n reflink,\n reflinkSearch,\n tag,\n text: inlineText,\n url: noopTest\n};\n/**\n * Pedantic Inline Grammar\n */\nconst inlinePedantic = {\n ...inlineNormal,\n link: edit(/^!?\\[(label)\\]\\((.*?)\\)/)\n .replace('label', _inlineLabel)\n .getRegex(),\n reflink: edit(/^!?\\[(label)\\]\\s*\\[([^\\]]*)\\]/)\n .replace('label', _inlineLabel)\n .getRegex()\n};\n/**\n * GFM Inline Grammar\n */\nconst inlineGfm = {\n ...inlineNormal,\n escape: edit(escape).replace('])', '~|])').getRegex(),\n url: edit(/^((?:ftp|https?):\\/\\/|www\\.)(?:[a-zA-Z0-9\\-]+\\.?)+[^\\s<]*|^email/, 'i')\n .replace('email', /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/)\n .getRegex(),\n _backpedal: /(?:[^?!.,:;*_'\"~()&]+|\\([^)]*\\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'\"~)]+(?!$))+/,\n del: /^(~~?)(?=[^\\s~])([\\s\\S]*?[^\\s~])\\1(?=[^~]|$)/,\n text: /^([`~]+|[^`~])(?:(?= {2,}\\n)|(?=[a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-]+@)|[\\s\\S]*?(?:(?=[\\\\ {\n return leading + ' '.repeat(tabs.length);\n });\n }\n let token;\n let lastToken;\n let cutSrc;\n while (src) {\n if (this.options.extensions\n && this.options.extensions.block\n && this.options.extensions.block.some((extTokenizer) => {\n if (token = extTokenizer.call({ lexer: this }, src, tokens)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n return true;\n }\n return false;\n })) {\n continue;\n }\n // newline\n if (token = this.tokenizer.space(src)) {\n src = src.substring(token.raw.length);\n if (token.raw.length === 1 && tokens.length > 0) {\n // if there's a single \\n as a spacer, it's terminating the last line,\n // so move it there so that we don't get unnecessary paragraph tags\n tokens[tokens.length - 1].raw += '\\n';\n }\n else {\n tokens.push(token);\n }\n continue;\n }\n // code\n if (token = this.tokenizer.code(src)) {\n src = src.substring(token.raw.length);\n lastToken = tokens[tokens.length - 1];\n // An indented code block cannot interrupt a paragraph.\n if (lastToken && (lastToken.type === 'paragraph' || lastToken.type === 'text')) {\n lastToken.raw += '\\n' + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;\n }\n else {\n tokens.push(token);\n }\n continue;\n }\n // fences\n if (token = this.tokenizer.fences(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // heading\n if (token = this.tokenizer.heading(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // hr\n if (token = this.tokenizer.hr(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // blockquote\n if (token = this.tokenizer.blockquote(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // list\n if (token = this.tokenizer.list(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // html\n if (token = this.tokenizer.html(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // def\n if (token = this.tokenizer.def(src)) {\n src = src.substring(token.raw.length);\n lastToken = tokens[tokens.length - 1];\n if (lastToken && (lastToken.type === 'paragraph' || lastToken.type === 'text')) {\n lastToken.raw += '\\n' + token.raw;\n lastToken.text += '\\n' + token.raw;\n this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;\n }\n else if (!this.tokens.links[token.tag]) {\n this.tokens.links[token.tag] = {\n href: token.href,\n title: token.title\n };\n }\n continue;\n }\n // table (gfm)\n if (token = this.tokenizer.table(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // lheading\n if (token = this.tokenizer.lheading(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // top-level paragraph\n // prevent paragraph consuming extensions by clipping 'src' to extension start\n cutSrc = src;\n if (this.options.extensions && this.options.extensions.startBlock) {\n let startIndex = Infinity;\n const tempSrc = src.slice(1);\n let tempStart;\n this.options.extensions.startBlock.forEach((getStartIndex) => {\n tempStart = getStartIndex.call({ lexer: this }, tempSrc);\n if (typeof tempStart === 'number' && tempStart >= 0) {\n startIndex = Math.min(startIndex, tempStart);\n }\n });\n if (startIndex < Infinity && startIndex >= 0) {\n cutSrc = src.substring(0, startIndex + 1);\n }\n }\n if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) {\n lastToken = tokens[tokens.length - 1];\n if (lastParagraphClipped && lastToken?.type === 'paragraph') {\n lastToken.raw += '\\n' + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.pop();\n this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;\n }\n else {\n tokens.push(token);\n }\n lastParagraphClipped = (cutSrc.length !== src.length);\n src = src.substring(token.raw.length);\n continue;\n }\n // text\n if (token = this.tokenizer.text(src)) {\n src = src.substring(token.raw.length);\n lastToken = tokens[tokens.length - 1];\n if (lastToken && lastToken.type === 'text') {\n lastToken.raw += '\\n' + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.pop();\n this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;\n }\n else {\n tokens.push(token);\n }\n continue;\n }\n if (src) {\n const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);\n if (this.options.silent) {\n console.error(errMsg);\n break;\n }\n else {\n throw new Error(errMsg);\n }\n }\n }\n this.state.top = true;\n return tokens;\n }\n inline(src, tokens = []) {\n this.inlineQueue.push({ src, tokens });\n return tokens;\n }\n /**\n * Lexing/Compiling\n */\n inlineTokens(src, tokens = []) {\n let token, lastToken, cutSrc;\n // String with links masked to avoid interference with em and strong\n let maskedSrc = src;\n let match;\n let keepPrevChar, prevChar;\n // Mask out reflinks\n if (this.tokens.links) {\n const links = Object.keys(this.tokens.links);\n if (links.length > 0) {\n while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) {\n if (links.includes(match[0].slice(match[0].lastIndexOf('[') + 1, -1))) {\n maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex);\n }\n }\n }\n }\n // Mask out other blocks\n while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) {\n maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);\n }\n // Mask out escaped characters\n while ((match = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) != null) {\n maskedSrc = maskedSrc.slice(0, match.index) + '++' + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);\n }\n while (src) {\n if (!keepPrevChar) {\n prevChar = '';\n }\n keepPrevChar = false;\n // extensions\n if (this.options.extensions\n && this.options.extensions.inline\n && this.options.extensions.inline.some((extTokenizer) => {\n if (token = extTokenizer.call({ lexer: this }, src, tokens)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n return true;\n }\n return false;\n })) {\n continue;\n }\n // escape\n if (token = this.tokenizer.escape(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // tag\n if (token = this.tokenizer.tag(src)) {\n src = src.substring(token.raw.length);\n lastToken = tokens[tokens.length - 1];\n if (lastToken && token.type === 'text' && lastToken.type === 'text') {\n lastToken.raw += token.raw;\n lastToken.text += token.text;\n }\n else {\n tokens.push(token);\n }\n continue;\n }\n // link\n if (token = this.tokenizer.link(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // reflink, nolink\n if (token = this.tokenizer.reflink(src, this.tokens.links)) {\n src = src.substring(token.raw.length);\n lastToken = tokens[tokens.length - 1];\n if (lastToken && token.type === 'text' && lastToken.type === 'text') {\n lastToken.raw += token.raw;\n lastToken.text += token.text;\n }\n else {\n tokens.push(token);\n }\n continue;\n }\n // em & strong\n if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // code\n if (token = this.tokenizer.codespan(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // br\n if (token = this.tokenizer.br(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // del (gfm)\n if (token = this.tokenizer.del(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // autolink\n if (token = this.tokenizer.autolink(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // url (gfm)\n if (!this.state.inLink && (token = this.tokenizer.url(src))) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // text\n // prevent inlineText consuming extensions by clipping 'src' to extension start\n cutSrc = src;\n if (this.options.extensions && this.options.extensions.startInline) {\n let startIndex = Infinity;\n const tempSrc = src.slice(1);\n let tempStart;\n this.options.extensions.startInline.forEach((getStartIndex) => {\n tempStart = getStartIndex.call({ lexer: this }, tempSrc);\n if (typeof tempStart === 'number' && tempStart >= 0) {\n startIndex = Math.min(startIndex, tempStart);\n }\n });\n if (startIndex < Infinity && startIndex >= 0) {\n cutSrc = src.substring(0, startIndex + 1);\n }\n }\n if (token = this.tokenizer.inlineText(cutSrc)) {\n src = src.substring(token.raw.length);\n if (token.raw.slice(-1) !== '_') { // Track prevChar before string of ____ started\n prevChar = token.raw.slice(-1);\n }\n keepPrevChar = true;\n lastToken = tokens[tokens.length - 1];\n if (lastToken && lastToken.type === 'text') {\n lastToken.raw += token.raw;\n lastToken.text += token.text;\n }\n else {\n tokens.push(token);\n }\n continue;\n }\n if (src) {\n const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);\n if (this.options.silent) {\n console.error(errMsg);\n break;\n }\n else {\n throw new Error(errMsg);\n }\n }\n }\n return tokens;\n }\n}\n","import { _defaults } from './defaults.ts';\nimport { cleanUrl, escape } from './helpers.ts';\n/**\n * Renderer\n */\nexport class _Renderer {\n options;\n parser; // set by the parser\n constructor(options) {\n this.options = options || _defaults;\n }\n space(token) {\n return '';\n }\n code({ text, lang, escaped }) {\n const langString = (lang || '').match(/^\\S*/)?.[0];\n const code = text.replace(/\\n$/, '') + '\\n';\n if (!langString) {\n return '
    '\n                + (escaped ? code : escape(code, true))\n                + '
    \\n';\n }\n return '
    '\n            + (escaped ? code : escape(code, true))\n            + '
    \\n';\n }\n blockquote({ tokens }) {\n const body = this.parser.parse(tokens);\n return `
    \\n${body}
    \\n`;\n }\n html({ text }) {\n return text;\n }\n heading({ tokens, depth }) {\n return `${this.parser.parseInline(tokens)}\\n`;\n }\n hr(token) {\n return '
    \\n';\n }\n list(token) {\n const ordered = token.ordered;\n const start = token.start;\n let body = '';\n for (let j = 0; j < token.items.length; j++) {\n const item = token.items[j];\n body += this.listitem(item);\n }\n const type = ordered ? 'ol' : 'ul';\n const startAttr = (ordered && start !== 1) ? (' start=\"' + start + '\"') : '';\n return '<' + type + startAttr + '>\\n' + body + '\\n';\n }\n listitem(item) {\n let itemBody = '';\n if (item.task) {\n const checkbox = this.checkbox({ checked: !!item.checked });\n if (item.loose) {\n if (item.tokens.length > 0 && item.tokens[0].type === 'paragraph') {\n item.tokens[0].text = checkbox + ' ' + item.tokens[0].text;\n if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') {\n item.tokens[0].tokens[0].text = checkbox + ' ' + item.tokens[0].tokens[0].text;\n }\n }\n else {\n item.tokens.unshift({\n type: 'text',\n raw: checkbox + ' ',\n text: checkbox + ' '\n });\n }\n }\n else {\n itemBody += checkbox + ' ';\n }\n }\n itemBody += this.parser.parse(item.tokens, !!item.loose);\n return `
  • ${itemBody}
  • \\n`;\n }\n checkbox({ checked }) {\n return '';\n }\n paragraph({ tokens }) {\n return `

    ${this.parser.parseInline(tokens)}

    \\n`;\n }\n table(token) {\n let header = '';\n // header\n let cell = '';\n for (let j = 0; j < token.header.length; j++) {\n cell += this.tablecell(token.header[j]);\n }\n header += this.tablerow({ text: cell });\n let body = '';\n for (let j = 0; j < token.rows.length; j++) {\n const row = token.rows[j];\n cell = '';\n for (let k = 0; k < row.length; k++) {\n cell += this.tablecell(row[k]);\n }\n body += this.tablerow({ text: cell });\n }\n if (body)\n body = `${body}`;\n return '\\n'\n + '\\n'\n + header\n + '\\n'\n + body\n + '
    \\n';\n }\n tablerow({ text }) {\n return `\\n${text}\\n`;\n }\n tablecell(token) {\n const content = this.parser.parseInline(token.tokens);\n const type = token.header ? 'th' : 'td';\n const tag = token.align\n ? `<${type} align=\"${token.align}\">`\n : `<${type}>`;\n return tag + content + `\\n`;\n }\n /**\n * span level renderer\n */\n strong({ tokens }) {\n return `${this.parser.parseInline(tokens)}`;\n }\n em({ tokens }) {\n return `${this.parser.parseInline(tokens)}`;\n }\n codespan({ text }) {\n return `${text}`;\n }\n br(token) {\n return '
    ';\n }\n del({ tokens }) {\n return `${this.parser.parseInline(tokens)}`;\n }\n link({ href, title, tokens }) {\n const text = this.parser.parseInline(tokens);\n const cleanHref = cleanUrl(href);\n if (cleanHref === null) {\n return text;\n }\n href = cleanHref;\n let out = '
    ';\n return out;\n }\n image({ href, title, text }) {\n const cleanHref = cleanUrl(href);\n if (cleanHref === null) {\n return text;\n }\n href = cleanHref;\n let out = `\"${text}\"`;\n {\n const tokens = genericToken[childTokens].flat(Infinity);\n values = values.concat(this.walkTokens(tokens, callback));\n });\n }\n else if (genericToken.tokens) {\n values = values.concat(this.walkTokens(genericToken.tokens, callback));\n }\n }\n }\n }\n return values;\n }\n use(...args) {\n const extensions = this.defaults.extensions || { renderers: {}, childTokens: {} };\n args.forEach((pack) => {\n // copy options to new object\n const opts = { ...pack };\n // set async to true if it was set to true before\n opts.async = this.defaults.async || opts.async || false;\n // ==-- Parse \"addon\" extensions --== //\n if (pack.extensions) {\n pack.extensions.forEach((ext) => {\n if (!ext.name) {\n throw new Error('extension name required');\n }\n if ('renderer' in ext) { // Renderer extensions\n const prevRenderer = extensions.renderers[ext.name];\n if (prevRenderer) {\n // Replace extension with func to run new extension but fall back if false\n extensions.renderers[ext.name] = function (...args) {\n let ret = ext.renderer.apply(this, args);\n if (ret === false) {\n ret = prevRenderer.apply(this, args);\n }\n return ret;\n };\n }\n else {\n extensions.renderers[ext.name] = ext.renderer;\n }\n }\n if ('tokenizer' in ext) { // Tokenizer Extensions\n if (!ext.level || (ext.level !== 'block' && ext.level !== 'inline')) {\n throw new Error(\"extension level must be 'block' or 'inline'\");\n }\n const extLevel = extensions[ext.level];\n if (extLevel) {\n extLevel.unshift(ext.tokenizer);\n }\n else {\n extensions[ext.level] = [ext.tokenizer];\n }\n if (ext.start) { // Function to check for start of token\n if (ext.level === 'block') {\n if (extensions.startBlock) {\n extensions.startBlock.push(ext.start);\n }\n else {\n extensions.startBlock = [ext.start];\n }\n }\n else if (ext.level === 'inline') {\n if (extensions.startInline) {\n extensions.startInline.push(ext.start);\n }\n else {\n extensions.startInline = [ext.start];\n }\n }\n }\n }\n if ('childTokens' in ext && ext.childTokens) { // Child tokens to be visited by walkTokens\n extensions.childTokens[ext.name] = ext.childTokens;\n }\n });\n opts.extensions = extensions;\n }\n // ==-- Parse \"overwrite\" extensions --== //\n if (pack.renderer) {\n const renderer = this.defaults.renderer || new _Renderer(this.defaults);\n for (const prop in pack.renderer) {\n if (!(prop in renderer)) {\n throw new Error(`renderer '${prop}' does not exist`);\n }\n if (['options', 'parser'].includes(prop)) {\n // ignore options property\n continue;\n }\n const rendererProp = prop;\n let rendererFunc = pack.renderer[rendererProp];\n const prevRenderer = renderer[rendererProp];\n // Replace renderer with func to run extension, but fall back if false\n renderer[rendererProp] = (...args) => {\n if (!pack.useNewRenderer) {\n // TODO: Remove this in next major version\n rendererFunc = this.#convertRendererFunction(rendererFunc, rendererProp, renderer);\n }\n let ret = rendererFunc.apply(renderer, args);\n if (ret === false) {\n ret = prevRenderer.apply(renderer, args);\n }\n return ret || '';\n };\n }\n opts.renderer = renderer;\n }\n if (pack.tokenizer) {\n const tokenizer = this.defaults.tokenizer || new _Tokenizer(this.defaults);\n for (const prop in pack.tokenizer) {\n if (!(prop in tokenizer)) {\n throw new Error(`tokenizer '${prop}' does not exist`);\n }\n if (['options', 'rules', 'lexer'].includes(prop)) {\n // ignore options, rules, and lexer properties\n continue;\n }\n const tokenizerProp = prop;\n const tokenizerFunc = pack.tokenizer[tokenizerProp];\n const prevTokenizer = tokenizer[tokenizerProp];\n // Replace tokenizer with func to run extension, but fall back if false\n // @ts-expect-error cannot type tokenizer function dynamically\n tokenizer[tokenizerProp] = (...args) => {\n let ret = tokenizerFunc.apply(tokenizer, args);\n if (ret === false) {\n ret = prevTokenizer.apply(tokenizer, args);\n }\n return ret;\n };\n }\n opts.tokenizer = tokenizer;\n }\n // ==-- Parse Hooks extensions --== //\n if (pack.hooks) {\n const hooks = this.defaults.hooks || new _Hooks();\n for (const prop in pack.hooks) {\n if (!(prop in hooks)) {\n throw new Error(`hook '${prop}' does not exist`);\n }\n if (prop === 'options') {\n // ignore options property\n continue;\n }\n const hooksProp = prop;\n const hooksFunc = pack.hooks[hooksProp];\n const prevHook = hooks[hooksProp];\n if (_Hooks.passThroughHooks.has(prop)) {\n // @ts-expect-error cannot type hook function dynamically\n hooks[hooksProp] = (arg) => {\n if (this.defaults.async) {\n return Promise.resolve(hooksFunc.call(hooks, arg)).then(ret => {\n return prevHook.call(hooks, ret);\n });\n }\n const ret = hooksFunc.call(hooks, arg);\n return prevHook.call(hooks, ret);\n };\n }\n else {\n // @ts-expect-error cannot type hook function dynamically\n hooks[hooksProp] = (...args) => {\n let ret = hooksFunc.apply(hooks, args);\n if (ret === false) {\n ret = prevHook.apply(hooks, args);\n }\n return ret;\n };\n }\n }\n opts.hooks = hooks;\n }\n // ==-- Parse WalkTokens extensions --== //\n if (pack.walkTokens) {\n const walkTokens = this.defaults.walkTokens;\n const packWalktokens = pack.walkTokens;\n opts.walkTokens = function (token) {\n let values = [];\n values.push(packWalktokens.call(this, token));\n if (walkTokens) {\n values = values.concat(walkTokens.call(this, token));\n }\n return values;\n };\n }\n this.defaults = { ...this.defaults, ...opts };\n });\n return this;\n }\n // TODO: Remove this in next major release\n #convertRendererFunction(func, prop, renderer) {\n switch (prop) {\n case 'heading':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n return func.call(this, renderer.parser.parseInline(token.tokens), token.depth, unescape(renderer.parser.parseInline(token.tokens, renderer.parser.textRenderer)));\n };\n case 'code':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n return func.call(this, token.text, token.lang, !!token.escaped);\n };\n case 'table':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n let header = '';\n // header\n let cell = '';\n for (let j = 0; j < token.header.length; j++) {\n cell += this.tablecell({\n text: token.header[j].text,\n tokens: token.header[j].tokens,\n header: true,\n align: token.align[j]\n });\n }\n header += this.tablerow({ text: cell });\n let body = '';\n for (let j = 0; j < token.rows.length; j++) {\n const row = token.rows[j];\n cell = '';\n for (let k = 0; k < row.length; k++) {\n cell += this.tablecell({\n text: row[k].text,\n tokens: row[k].tokens,\n header: false,\n align: token.align[k]\n });\n }\n body += this.tablerow({ text: cell });\n }\n return func.call(this, header, body);\n };\n case 'blockquote':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n const body = this.parser.parse(token.tokens);\n return func.call(this, body);\n };\n case 'list':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n const ordered = token.ordered;\n const start = token.start;\n const loose = token.loose;\n let body = '';\n for (let j = 0; j < token.items.length; j++) {\n const item = token.items[j];\n const checked = item.checked;\n const task = item.task;\n let itemBody = '';\n if (item.task) {\n const checkbox = this.checkbox({ checked: !!checked });\n if (loose) {\n if (item.tokens.length > 0 && item.tokens[0].type === 'paragraph') {\n item.tokens[0].text = checkbox + ' ' + item.tokens[0].text;\n if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') {\n item.tokens[0].tokens[0].text = checkbox + ' ' + item.tokens[0].tokens[0].text;\n }\n }\n else {\n item.tokens.unshift({\n type: 'text',\n text: checkbox + ' '\n });\n }\n }\n else {\n itemBody += checkbox + ' ';\n }\n }\n itemBody += this.parser.parse(item.tokens, loose);\n body += this.listitem({\n type: 'list_item',\n raw: itemBody,\n text: itemBody,\n task,\n checked: !!checked,\n loose,\n tokens: item.tokens\n });\n }\n return func.call(this, body, ordered, start);\n };\n case 'html':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n return func.call(this, token.text, token.block);\n };\n case 'paragraph':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n return func.call(this, this.parser.parseInline(token.tokens));\n };\n case 'escape':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n return func.call(this, token.text);\n };\n case 'link':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n return func.call(this, token.href, token.title, this.parser.parseInline(token.tokens));\n };\n case 'image':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n return func.call(this, token.href, token.title, token.text);\n };\n case 'strong':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n return func.call(this, this.parser.parseInline(token.tokens));\n };\n case 'em':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n return func.call(this, this.parser.parseInline(token.tokens));\n };\n case 'codespan':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n return func.call(this, token.text);\n };\n case 'del':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n return func.call(this, this.parser.parseInline(token.tokens));\n };\n case 'text':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n return func.call(this, token.text);\n };\n default:\n // do nothing\n }\n return func;\n }\n setOptions(opt) {\n this.defaults = { ...this.defaults, ...opt };\n return this;\n }\n lexer(src, options) {\n return _Lexer.lex(src, options ?? this.defaults);\n }\n parser(tokens, options) {\n return _Parser.parse(tokens, options ?? this.defaults);\n }\n #parseMarkdown(lexer, parser) {\n return (src, options) => {\n const origOpt = { ...options };\n const opt = { ...this.defaults, ...origOpt };\n // Show warning if an extension set async to true but the parse was called with async: false\n if (this.defaults.async === true && origOpt.async === false) {\n if (!opt.silent) {\n console.warn('marked(): The async option was set to true by an extension. The async: false option sent to parse will be ignored.');\n }\n opt.async = true;\n }\n const throwError = this.#onError(!!opt.silent, !!opt.async);\n // throw error in case of non string input\n if (typeof src === 'undefined' || src === null) {\n return throwError(new Error('marked(): input parameter is undefined or null'));\n }\n if (typeof src !== 'string') {\n return throwError(new Error('marked(): input parameter is of type '\n + Object.prototype.toString.call(src) + ', string expected'));\n }\n if (opt.hooks) {\n opt.hooks.options = opt;\n }\n if (opt.async) {\n return Promise.resolve(opt.hooks ? opt.hooks.preprocess(src) : src)\n .then(src => lexer(src, opt))\n .then(tokens => opt.hooks ? opt.hooks.processAllTokens(tokens) : tokens)\n .then(tokens => opt.walkTokens ? Promise.all(this.walkTokens(tokens, opt.walkTokens)).then(() => tokens) : tokens)\n .then(tokens => parser(tokens, opt))\n .then(html => opt.hooks ? opt.hooks.postprocess(html) : html)\n .catch(throwError);\n }\n try {\n if (opt.hooks) {\n src = opt.hooks.preprocess(src);\n }\n let tokens = lexer(src, opt);\n if (opt.hooks) {\n tokens = opt.hooks.processAllTokens(tokens);\n }\n if (opt.walkTokens) {\n this.walkTokens(tokens, opt.walkTokens);\n }\n let html = parser(tokens, opt);\n if (opt.hooks) {\n html = opt.hooks.postprocess(html);\n }\n return html;\n }\n catch (e) {\n return throwError(e);\n }\n };\n }\n #onError(silent, async) {\n return (e) => {\n e.message += '\\nPlease report this to https://github.com/markedjs/marked.';\n if (silent) {\n const msg = '

    An error occurred:

    '\n                    + escape(e.message + '', true)\n                    + '
    ';\n if (async) {\n return Promise.resolve(msg);\n }\n return msg;\n }\n if (async) {\n return Promise.reject(e);\n }\n throw e;\n };\n }\n}\n","import { _Lexer } from './Lexer.ts';\nimport { _Parser } from './Parser.ts';\nimport { _Tokenizer } from './Tokenizer.ts';\nimport { _Renderer } from './Renderer.ts';\nimport { _TextRenderer } from './TextRenderer.ts';\nimport { _Hooks } from './Hooks.ts';\nimport { Marked } from './Instance.ts';\nimport { _getDefaults, changeDefaults, _defaults } from './defaults.ts';\nconst markedInstance = new Marked();\nexport function marked(src, opt) {\n return markedInstance.parse(src, opt);\n}\n/**\n * Sets the default options.\n *\n * @param options Hash of options\n */\nmarked.options =\n marked.setOptions = function (options) {\n markedInstance.setOptions(options);\n marked.defaults = markedInstance.defaults;\n changeDefaults(marked.defaults);\n return marked;\n };\n/**\n * Gets the original marked default options.\n */\nmarked.getDefaults = _getDefaults;\nmarked.defaults = _defaults;\n/**\n * Use Extension\n */\nmarked.use = function (...args) {\n markedInstance.use(...args);\n marked.defaults = markedInstance.defaults;\n changeDefaults(marked.defaults);\n return marked;\n};\n/**\n * Run callback for every token\n */\nmarked.walkTokens = function (tokens, callback) {\n return markedInstance.walkTokens(tokens, callback);\n};\n/**\n * Compiles markdown to HTML without enclosing `p` tag.\n *\n * @param src String of markdown source to be compiled\n * @param options Hash of options\n * @return String of compiled HTML\n */\nmarked.parseInline = markedInstance.parseInline;\n/**\n * Expose\n */\nmarked.Parser = _Parser;\nmarked.parser = _Parser.parse;\nmarked.Renderer = _Renderer;\nmarked.TextRenderer = _TextRenderer;\nmarked.Lexer = _Lexer;\nmarked.lexer = _Lexer.lex;\nmarked.Tokenizer = _Tokenizer;\nmarked.Hooks = _Hooks;\nmarked.parse = marked;\nexport const options = marked.options;\nexport const setOptions = marked.setOptions;\nexport const use = marked.use;\nexport const walkTokens = marked.walkTokens;\nexport const parseInline = marked.parseInline;\nexport const parse = marked;\nexport const parser = _Parser.parse;\nexport const lexer = _Lexer.lex;\nexport { _defaults as defaults, _getDefaults as getDefaults } from './defaults.ts';\nexport { _Lexer as Lexer } from './Lexer.ts';\nexport { _Parser as Parser } from './Parser.ts';\nexport { _Tokenizer as Tokenizer } from './Tokenizer.ts';\nexport { _Renderer as Renderer } from './Renderer.ts';\nexport { _TextRenderer as TextRenderer } from './TextRenderer.ts';\nexport { _Hooks as Hooks } from './Hooks.ts';\nexport { Marked } from './Instance.ts';\n"],"names":["_defaults","escape"],"mappings":";;;;;;;;;;;;;AAAA;AACA;AACA;AACO,SAAS,YAAY,GAAG;AAC/B,IAAI,OAAO;AACX,QAAQ,KAAK,EAAE,KAAK;AACpB,QAAQ,MAAM,EAAE,KAAK;AACrB,QAAQ,UAAU,EAAE,IAAI;AACxB,QAAQ,GAAG,EAAE,IAAI;AACjB,QAAQ,KAAK,EAAE,IAAI;AACnB,QAAQ,QAAQ,EAAE,KAAK;AACvB,QAAQ,QAAQ,EAAE,IAAI;AACtB,QAAQ,MAAM,EAAE,KAAK;AACrB,QAAQ,SAAS,EAAE,IAAI;AACvB,QAAQ,UAAU,EAAE,IAAI;AACxB,KAAK,CAAC;AACN,CAAC;AACUA,gBAAS,GAAG,YAAY,GAAG;AAC/B,SAAS,cAAc,CAAC,WAAW,EAAE;AAC5C,IAAIA,gBAAS,GAAG,WAAW,CAAC;AAC5B;;ACpBA;AACA;AACA;A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AAG,OAAO;AAChB,MAAC,MAAM,GAAG,OAAO,CAAC,MAAM;AACxB,MAAC,KAAK,GAAG,MAAM,CAAC;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/scripts/node_modules/marked/lib/marked.d.cts b/scripts/node_modules/marked/lib/marked.d.cts new file mode 100644 index 000000000..c0535639b --- /dev/null +++ b/scripts/node_modules/marked/lib/marked.d.cts @@ -0,0 +1,670 @@ +// Generated by dts-bundle-generator v9.5.1 + +export type MarkedToken = (Tokens.Space | Tokens.Code | Tokens.Heading | Tokens.Table | Tokens.Hr | Tokens.Blockquote | Tokens.List | Tokens.ListItem | Tokens.Paragraph | Tokens.HTML | Tokens.Text | Tokens.Def | Tokens.Escape | Tokens.Tag | Tokens.Image | Tokens.Link | Tokens.Strong | Tokens.Em | Tokens.Codespan | Tokens.Br | Tokens.Del); +export type Token = (MarkedToken | Tokens.Generic); +export declare namespace Tokens { + interface Space { + type: "space"; + raw: string; + } + interface Code { + type: "code"; + raw: string; + codeBlockStyle?: "indented" | undefined; + lang?: string | undefined; + text: string; + escaped?: boolean; + } + interface Heading { + type: "heading"; + raw: string; + depth: number; + text: string; + tokens: Token[]; + } + interface Table { + type: "table"; + raw: string; + align: Array<"center" | "left" | "right" | null>; + header: TableCell[]; + rows: TableCell[][]; + } + interface TableRow { + text: string; + } + interface TableCell { + text: string; + tokens: Token[]; + header: boolean; + align: "center" | "left" | "right" | null; + } + interface Hr { + type: "hr"; + raw: string; + } + interface Blockquote { + type: "blockquote"; + raw: string; + text: string; + tokens: Token[]; + } + interface List { + type: "list"; + raw: string; + ordered: boolean; + start: number | ""; + loose: boolean; + items: ListItem[]; + } + interface ListItem { + type: "list_item"; + raw: string; + task: boolean; + checked?: boolean | undefined; + loose: boolean; + text: string; + tokens: Token[]; + } + interface Checkbox { + checked: boolean; + } + interface Paragraph { + type: "paragraph"; + raw: string; + pre?: boolean | undefined; + text: string; + tokens: Token[]; + } + interface HTML { + type: "html"; + raw: string; + pre: boolean; + text: string; + block: boolean; + } + interface Text { + type: "text"; + raw: string; + text: string; + tokens?: Token[]; + } + interface Def { + type: "def"; + raw: string; + tag: string; + href: string; + title: string; + } + interface Escape { + type: "escape"; + raw: string; + text: string; + } + interface Tag { + type: "text" | "html"; + raw: string; + inLink: boolean; + inRawBlock: boolean; + text: string; + block: boolean; + } + interface Link { + type: "link"; + raw: string; + href: string; + title?: string | null; + text: string; + tokens: Token[]; + } + interface Image { + type: "image"; + raw: string; + href: string; + title: string | null; + text: string; + } + interface Strong { + type: "strong"; + raw: string; + text: string; + tokens: Token[]; + } + interface Em { + type: "em"; + raw: string; + text: string; + tokens: Token[]; + } + interface Codespan { + type: "codespan"; + raw: string; + text: string; + } + interface Br { + type: "br"; + raw: string; + } + interface Del { + type: "del"; + raw: string; + text: string; + tokens: Token[]; + } + interface Generic { + [index: string]: any; + type: string; + raw: string; + tokens?: Token[] | undefined; + } +} +export type Links = Record>; +export type TokensList = Token[] & { + links: Links; +}; +/** + * Renderer + */ +declare class _Renderer { + options: MarkedOptions; + parser: _Parser; + constructor(options?: MarkedOptions); + space(token: Tokens.Space): string; + code({ text, lang, escaped }: Tokens.Code): string; + blockquote({ tokens }: Tokens.Blockquote): string; + html({ text }: Tokens.HTML | Tokens.Tag): string; + heading({ tokens, depth }: Tokens.Heading): string; + hr(token: Tokens.Hr): string; + list(token: Tokens.List): string; + listitem(item: Tokens.ListItem): string; + checkbox({ checked }: Tokens.Checkbox): string; + paragraph({ tokens }: Tokens.Paragraph): string; + table(token: Tokens.Table): string; + tablerow({ text }: Tokens.TableRow): string; + tablecell(token: Tokens.TableCell): string; + /** + * span level renderer + */ + strong({ tokens }: Tokens.Strong): string; + em({ tokens }: Tokens.Em): string; + codespan({ text }: Tokens.Codespan): string; + br(token: Tokens.Br): string; + del({ tokens }: Tokens.Del): string; + link({ href, title, tokens }: Tokens.Link): string; + image({ href, title, text }: Tokens.Image): string; + text(token: Tokens.Text | Tokens.Escape | Tokens.Tag): string; +} +/** + * TextRenderer + * returns only the textual part of the token + */ +declare class _TextRenderer { + strong({ text }: Tokens.Strong): string; + em({ text }: Tokens.Em): string; + codespan({ text }: Tokens.Codespan): string; + del({ text }: Tokens.Del): string; + html({ text }: Tokens.HTML | Tokens.Tag): string; + text({ text }: Tokens.Text | Tokens.Escape | Tokens.Tag): string; + link({ text }: Tokens.Link): string; + image({ text }: Tokens.Image): string; + br(): string; +} +/** + * Parsing & Compiling + */ +declare class _Parser { + options: MarkedOptions; + renderer: _Renderer; + textRenderer: _TextRenderer; + constructor(options?: MarkedOptions); + /** + * Static Parse Method + */ + static parse(tokens: Token[], options?: MarkedOptions): string; + /** + * Static Parse Inline Method + */ + static parseInline(tokens: Token[], options?: MarkedOptions): string; + /** + * Parse Loop + */ + parse(tokens: Token[], top?: boolean): string; + /** + * Parse Inline Tokens + */ + parseInline(tokens: Token[], renderer?: _Renderer | _TextRenderer): string; +} +declare const blockNormal: { + blockquote: RegExp; + code: RegExp; + def: RegExp; + fences: RegExp; + heading: RegExp; + hr: RegExp; + html: RegExp; + lheading: RegExp; + list: RegExp; + newline: RegExp; + paragraph: RegExp; + table: RegExp; + text: RegExp; +}; +export type BlockKeys = keyof typeof blockNormal; +declare const inlineNormal: { + _backpedal: RegExp; + anyPunctuation: RegExp; + autolink: RegExp; + blockSkip: RegExp; + br: RegExp; + code: RegExp; + del: RegExp; + emStrongLDelim: RegExp; + emStrongRDelimAst: RegExp; + emStrongRDelimUnd: RegExp; + escape: RegExp; + link: RegExp; + nolink: RegExp; + punctuation: RegExp; + reflink: RegExp; + reflinkSearch: RegExp; + tag: RegExp; + text: RegExp; + url: RegExp; +}; +export type InlineKeys = keyof typeof inlineNormal; +/** + * exports + */ +export declare const block: { + normal: { + blockquote: RegExp; + code: RegExp; + def: RegExp; + fences: RegExp; + heading: RegExp; + hr: RegExp; + html: RegExp; + lheading: RegExp; + list: RegExp; + newline: RegExp; + paragraph: RegExp; + table: RegExp; + text: RegExp; + }; + gfm: Record<"code" | "blockquote" | "hr" | "html" | "table" | "text" | "heading" | "list" | "paragraph" | "def" | "fences" | "lheading" | "newline", RegExp>; + pedantic: Record<"code" | "blockquote" | "hr" | "html" | "table" | "text" | "heading" | "list" | "paragraph" | "def" | "fences" | "lheading" | "newline", RegExp>; +}; +export declare const inline: { + normal: { + _backpedal: RegExp; + anyPunctuation: RegExp; + autolink: RegExp; + blockSkip: RegExp; + br: RegExp; + code: RegExp; + del: RegExp; + emStrongLDelim: RegExp; + emStrongRDelimAst: RegExp; + emStrongRDelimUnd: RegExp; + escape: RegExp; + link: RegExp; + nolink: RegExp; + punctuation: RegExp; + reflink: RegExp; + reflinkSearch: RegExp; + tag: RegExp; + text: RegExp; + url: RegExp; + }; + gfm: Record<"link" | "code" | "url" | "br" | "del" | "text" | "escape" | "tag" | "reflink" | "autolink" | "nolink" | "_backpedal" | "anyPunctuation" | "blockSkip" | "emStrongLDelim" | "emStrongRDelimAst" | "emStrongRDelimUnd" | "punctuation" | "reflinkSearch", RegExp>; + breaks: Record<"link" | "code" | "url" | "br" | "del" | "text" | "escape" | "tag" | "reflink" | "autolink" | "nolink" | "_backpedal" | "anyPunctuation" | "blockSkip" | "emStrongLDelim" | "emStrongRDelimAst" | "emStrongRDelimUnd" | "punctuation" | "reflinkSearch", RegExp>; + pedantic: Record<"link" | "code" | "url" | "br" | "del" | "text" | "escape" | "tag" | "reflink" | "autolink" | "nolink" | "_backpedal" | "anyPunctuation" | "blockSkip" | "emStrongLDelim" | "emStrongRDelimAst" | "emStrongRDelimUnd" | "punctuation" | "reflinkSearch", RegExp>; +}; +export interface Rules { + block: Record; + inline: Record; +} +/** + * Tokenizer + */ +declare class _Tokenizer { + options: MarkedOptions; + rules: Rules; + lexer: _Lexer; + constructor(options?: MarkedOptions); + space(src: string): Tokens.Space | undefined; + code(src: string): Tokens.Code | undefined; + fences(src: string): Tokens.Code | undefined; + heading(src: string): Tokens.Heading | undefined; + hr(src: string): Tokens.Hr | undefined; + blockquote(src: string): Tokens.Blockquote | undefined; + list(src: string): Tokens.List | undefined; + html(src: string): Tokens.HTML | undefined; + def(src: string): Tokens.Def | undefined; + table(src: string): Tokens.Table | undefined; + lheading(src: string): Tokens.Heading | undefined; + paragraph(src: string): Tokens.Paragraph | undefined; + text(src: string): Tokens.Text | undefined; + escape(src: string): Tokens.Escape | undefined; + tag(src: string): Tokens.Tag | undefined; + link(src: string): Tokens.Link | Tokens.Image | undefined; + reflink(src: string, links: Links): Tokens.Link | Tokens.Image | Tokens.Text | undefined; + emStrong(src: string, maskedSrc: string, prevChar?: string): Tokens.Em | Tokens.Strong | undefined; + codespan(src: string): Tokens.Codespan | undefined; + br(src: string): Tokens.Br | undefined; + del(src: string): Tokens.Del | undefined; + autolink(src: string): Tokens.Link | undefined; + url(src: string): Tokens.Link | undefined; + inlineText(src: string): Tokens.Text | undefined; +} +declare class _Hooks { + options: MarkedOptions; + constructor(options?: MarkedOptions); + static passThroughHooks: Set; + /** + * Process markdown before marked + */ + preprocess(markdown: string): string; + /** + * Process HTML after marked is finished + */ + postprocess(html: string): string; + /** + * Process all tokens before walk tokens + */ + processAllTokens(tokens: Token[] | TokensList): Token[] | TokensList; +} +export interface TokenizerThis { + lexer: _Lexer; +} +export type TokenizerExtensionFunction = (this: TokenizerThis, src: string, tokens: Token[] | TokensList) => Tokens.Generic | undefined; +export type TokenizerStartFunction = (this: TokenizerThis, src: string) => number | void; +export interface TokenizerExtension { + name: string; + level: "block" | "inline"; + start?: TokenizerStartFunction | undefined; + tokenizer: TokenizerExtensionFunction; + childTokens?: string[] | undefined; +} +export interface RendererThis { + parser: _Parser; +} +export type RendererExtensionFunction = (this: RendererThis, token: Tokens.Generic) => string | false | undefined; +export interface RendererExtension { + name: string; + renderer: RendererExtensionFunction; +} +export type TokenizerAndRendererExtension = TokenizerExtension | RendererExtension | (TokenizerExtension & RendererExtension); +export type HooksApi = Omit<_Hooks, "constructor" | "options">; +export type HooksObject = { + [K in keyof HooksApi]?: (this: _Hooks, ...args: Parameters) => ReturnType | Promise>; +}; +export type RendererApi = Omit<_Renderer, "constructor" | "options" | "parser">; +export type RendererObject = { + [K in keyof RendererApi]?: (this: _Renderer, ...args: Parameters) => ReturnType | false; +}; +export type TokenizerApi = Omit<_Tokenizer, "constructor" | "options" | "rules" | "lexer">; +export type TokenizerObject = { + [K in keyof TokenizerApi]?: (this: _Tokenizer, ...args: Parameters) => ReturnType | false; +}; +export interface MarkedExtension { + /** + * True will tell marked to await any walkTokens functions before parsing the tokens and returning an HTML string. + */ + async?: boolean; + /** + * Enable GFM line breaks. This option requires the gfm option to be true. + */ + breaks?: boolean | undefined; + /** + * Add tokenizers and renderers to marked + */ + extensions?: TokenizerAndRendererExtension[] | undefined | null; + /** + * Enable GitHub flavored markdown. + */ + gfm?: boolean | undefined; + /** + * Hooks are methods that hook into some part of marked. + * preprocess is called to process markdown before sending it to marked. + * processAllTokens is called with the TokensList before walkTokens. + * postprocess is called to process html after marked has finished parsing. + */ + hooks?: HooksObject | undefined | null; + /** + * Conform to obscure parts of markdown.pl as much as possible. Don't fix any of the original markdown bugs or poor behavior. + */ + pedantic?: boolean | undefined; + /** + * Type: object Default: new Renderer() + * + * An object containing functions to render tokens to HTML. + */ + renderer?: RendererObject | undefined | null; + /** + * Shows an HTML error message when rendering fails. + */ + silent?: boolean | undefined; + /** + * The tokenizer defines how to turn markdown text into tokens. + */ + tokenizer?: TokenizerObject | undefined | null; + /** + * The walkTokens function gets called with every token. + * Child tokens are called before moving on to sibling tokens. + * Each token is passed by reference so updates are persisted when passed to the parser. + * The return value of the function is ignored. + */ + walkTokens?: ((token: Token) => void | Promise) | undefined | null; + /** + * Use the new renderer that accepts an object instead of individual parameters. + * This option will be removed and default to true in the next major version. + */ + useNewRenderer?: boolean | undefined; +} +export interface MarkedOptions extends Omit { + /** + * Hooks are methods that hook into some part of marked. + */ + hooks?: _Hooks | undefined | null; + /** + * Type: object Default: new Renderer() + * + * An object containing functions to render tokens to HTML. + */ + renderer?: _Renderer | undefined | null; + /** + * The tokenizer defines how to turn markdown text into tokens. + */ + tokenizer?: _Tokenizer | undefined | null; + /** + * Custom extensions + */ + extensions?: null | { + renderers: { + [name: string]: RendererExtensionFunction; + }; + childTokens: { + [name: string]: string[]; + }; + inline?: TokenizerExtensionFunction[]; + block?: TokenizerExtensionFunction[]; + startInline?: TokenizerStartFunction[]; + startBlock?: TokenizerStartFunction[]; + }; + /** + * walkTokens function returns array of values for Promise.all + */ + walkTokens?: null | ((token: Token) => void | Promise | (void | Promise)[]); +} +/** + * Block Lexer + */ +declare class _Lexer { + tokens: TokensList; + options: MarkedOptions; + state: { + inLink: boolean; + inRawBlock: boolean; + top: boolean; + }; + private tokenizer; + private inlineQueue; + constructor(options?: MarkedOptions); + /** + * Expose Rules + */ + static get rules(): { + block: { + normal: { + blockquote: RegExp; + code: RegExp; + def: RegExp; + fences: RegExp; + heading: RegExp; + hr: RegExp; + html: RegExp; + lheading: RegExp; + list: RegExp; + newline: RegExp; + paragraph: RegExp; + table: RegExp; + text: RegExp; + }; + gfm: Record<"code" | "blockquote" | "hr" | "html" | "table" | "text" | "heading" | "list" | "paragraph" | "def" | "fences" | "lheading" | "newline", RegExp>; + pedantic: Record<"code" | "blockquote" | "hr" | "html" | "table" | "text" | "heading" | "list" | "paragraph" | "def" | "fences" | "lheading" | "newline", RegExp>; + }; + inline: { + normal: { + _backpedal: RegExp; + anyPunctuation: RegExp; + autolink: RegExp; + blockSkip: RegExp; + br: RegExp; + code: RegExp; + del: RegExp; + emStrongLDelim: RegExp; + emStrongRDelimAst: RegExp; + emStrongRDelimUnd: RegExp; + escape: RegExp; + link: RegExp; + nolink: RegExp; + punctuation: RegExp; + reflink: RegExp; + reflinkSearch: RegExp; + tag: RegExp; + text: RegExp; + url: RegExp; + }; + gfm: Record<"link" | "code" | "url" | "br" | "del" | "text" | "escape" | "tag" | "reflink" | "autolink" | "nolink" | "_backpedal" | "anyPunctuation" | "blockSkip" | "emStrongLDelim" | "emStrongRDelimAst" | "emStrongRDelimUnd" | "punctuation" | "reflinkSearch", RegExp>; + breaks: Record<"link" | "code" | "url" | "br" | "del" | "text" | "escape" | "tag" | "reflink" | "autolink" | "nolink" | "_backpedal" | "anyPunctuation" | "blockSkip" | "emStrongLDelim" | "emStrongRDelimAst" | "emStrongRDelimUnd" | "punctuation" | "reflinkSearch", RegExp>; + pedantic: Record<"link" | "code" | "url" | "br" | "del" | "text" | "escape" | "tag" | "reflink" | "autolink" | "nolink" | "_backpedal" | "anyPunctuation" | "blockSkip" | "emStrongLDelim" | "emStrongRDelimAst" | "emStrongRDelimUnd" | "punctuation" | "reflinkSearch", RegExp>; + }; + }; + /** + * Static Lex Method + */ + static lex(src: string, options?: MarkedOptions): TokensList; + /** + * Static Lex Inline Method + */ + static lexInline(src: string, options?: MarkedOptions): Token[]; + /** + * Preprocessing + */ + lex(src: string): TokensList; + /** + * Lexing + */ + blockTokens(src: string, tokens?: Token[], lastParagraphClipped?: boolean): Token[]; + blockTokens(src: string, tokens?: TokensList, lastParagraphClipped?: boolean): TokensList; + inline(src: string, tokens?: Token[]): Token[]; + /** + * Lexing/Compiling + */ + inlineTokens(src: string, tokens?: Token[]): Token[]; +} +/** + * Gets the original marked default options. + */ +declare function _getDefaults(): MarkedOptions; +declare let _defaults: MarkedOptions; +export type MaybePromise = void | Promise; +export declare class Marked { + #private; + defaults: MarkedOptions; + options: (opt: MarkedOptions) => this; + parse: (src: string, options?: MarkedOptions | undefined | null) => string | Promise; + parseInline: (src: string, options?: MarkedOptions | undefined | null) => string | Promise; + Parser: typeof _Parser; + Renderer: typeof _Renderer; + TextRenderer: typeof _TextRenderer; + Lexer: typeof _Lexer; + Tokenizer: typeof _Tokenizer; + Hooks: typeof _Hooks; + constructor(...args: MarkedExtension[]); + /** + * Run callback for every token + */ + walkTokens(tokens: Token[] | TokensList, callback: (token: Token) => MaybePromise | MaybePromise[]): MaybePromise[]; + use(...args: MarkedExtension[]): this; + setOptions(opt: MarkedOptions): this; + lexer(src: string, options?: MarkedOptions): TokensList; + parser(tokens: Token[], options?: MarkedOptions): string; +} +/** + * Compiles markdown to HTML asynchronously. + * + * @param src String of markdown source to be compiled + * @param options Hash of options, having async: true + * @return Promise of string of compiled HTML + */ +export declare function marked(src: string, options: MarkedOptions & { + async: true; +}): Promise; +/** + * Compiles markdown to HTML. + * + * @param src String of markdown source to be compiled + * @param options Optional hash of options + * @return String of compiled HTML. Will be a Promise of string if async is set to true by any extensions. + */ +export declare function marked(src: string, options?: MarkedOptions): string | Promise; +export declare namespace marked { + var options: (options: MarkedOptions) => typeof marked; + var setOptions: (options: MarkedOptions) => typeof marked; + var getDefaults: typeof _getDefaults; + var defaults: MarkedOptions; + var use: (...args: MarkedExtension[]) => typeof marked; + var walkTokens: (tokens: Token[] | TokensList, callback: (token: Token) => MaybePromise | MaybePromise[]) => MaybePromise[]; + var parseInline: (src: string, options?: MarkedOptions | null | undefined) => string | Promise; + var Parser: typeof _Parser; + var parser: typeof _Parser.parse; + var Renderer: typeof _Renderer; + var TextRenderer: typeof _TextRenderer; + var Lexer: typeof _Lexer; + var lexer: typeof _Lexer.lex; + var Tokenizer: typeof _Tokenizer; + var Hooks: typeof _Hooks; + var parse: typeof marked; +} +export declare const options: (options: MarkedOptions) => typeof marked; +export declare const setOptions: (options: MarkedOptions) => typeof marked; +export declare const use: (...args: MarkedExtension[]) => typeof marked; +export declare const walkTokens: (tokens: Token[] | TokensList, callback: (token: Token) => MaybePromise | MaybePromise[]) => MaybePromise[]; +export declare const parseInline: (src: string, options?: MarkedOptions | null | undefined) => string | Promise; +export declare const parse: typeof marked; +export declare const parser: typeof _Parser.parse; +export declare const lexer: typeof _Lexer.lex; + +export { + _Hooks as Hooks, + _Lexer as Lexer, + _Parser as Parser, + _Renderer as Renderer, + _TextRenderer as TextRenderer, + _Tokenizer as Tokenizer, + _defaults as defaults, + _getDefaults as getDefaults, +}; + +export {}; diff --git a/scripts/node_modules/marked/lib/marked.d.ts b/scripts/node_modules/marked/lib/marked.d.ts new file mode 100644 index 000000000..c0535639b --- /dev/null +++ b/scripts/node_modules/marked/lib/marked.d.ts @@ -0,0 +1,670 @@ +// Generated by dts-bundle-generator v9.5.1 + +export type MarkedToken = (Tokens.Space | Tokens.Code | Tokens.Heading | Tokens.Table | Tokens.Hr | Tokens.Blockquote | Tokens.List | Tokens.ListItem | Tokens.Paragraph | Tokens.HTML | Tokens.Text | Tokens.Def | Tokens.Escape | Tokens.Tag | Tokens.Image | Tokens.Link | Tokens.Strong | Tokens.Em | Tokens.Codespan | Tokens.Br | Tokens.Del); +export type Token = (MarkedToken | Tokens.Generic); +export declare namespace Tokens { + interface Space { + type: "space"; + raw: string; + } + interface Code { + type: "code"; + raw: string; + codeBlockStyle?: "indented" | undefined; + lang?: string | undefined; + text: string; + escaped?: boolean; + } + interface Heading { + type: "heading"; + raw: string; + depth: number; + text: string; + tokens: Token[]; + } + interface Table { + type: "table"; + raw: string; + align: Array<"center" | "left" | "right" | null>; + header: TableCell[]; + rows: TableCell[][]; + } + interface TableRow { + text: string; + } + interface TableCell { + text: string; + tokens: Token[]; + header: boolean; + align: "center" | "left" | "right" | null; + } + interface Hr { + type: "hr"; + raw: string; + } + interface Blockquote { + type: "blockquote"; + raw: string; + text: string; + tokens: Token[]; + } + interface List { + type: "list"; + raw: string; + ordered: boolean; + start: number | ""; + loose: boolean; + items: ListItem[]; + } + interface ListItem { + type: "list_item"; + raw: string; + task: boolean; + checked?: boolean | undefined; + loose: boolean; + text: string; + tokens: Token[]; + } + interface Checkbox { + checked: boolean; + } + interface Paragraph { + type: "paragraph"; + raw: string; + pre?: boolean | undefined; + text: string; + tokens: Token[]; + } + interface HTML { + type: "html"; + raw: string; + pre: boolean; + text: string; + block: boolean; + } + interface Text { + type: "text"; + raw: string; + text: string; + tokens?: Token[]; + } + interface Def { + type: "def"; + raw: string; + tag: string; + href: string; + title: string; + } + interface Escape { + type: "escape"; + raw: string; + text: string; + } + interface Tag { + type: "text" | "html"; + raw: string; + inLink: boolean; + inRawBlock: boolean; + text: string; + block: boolean; + } + interface Link { + type: "link"; + raw: string; + href: string; + title?: string | null; + text: string; + tokens: Token[]; + } + interface Image { + type: "image"; + raw: string; + href: string; + title: string | null; + text: string; + } + interface Strong { + type: "strong"; + raw: string; + text: string; + tokens: Token[]; + } + interface Em { + type: "em"; + raw: string; + text: string; + tokens: Token[]; + } + interface Codespan { + type: "codespan"; + raw: string; + text: string; + } + interface Br { + type: "br"; + raw: string; + } + interface Del { + type: "del"; + raw: string; + text: string; + tokens: Token[]; + } + interface Generic { + [index: string]: any; + type: string; + raw: string; + tokens?: Token[] | undefined; + } +} +export type Links = Record>; +export type TokensList = Token[] & { + links: Links; +}; +/** + * Renderer + */ +declare class _Renderer { + options: MarkedOptions; + parser: _Parser; + constructor(options?: MarkedOptions); + space(token: Tokens.Space): string; + code({ text, lang, escaped }: Tokens.Code): string; + blockquote({ tokens }: Tokens.Blockquote): string; + html({ text }: Tokens.HTML | Tokens.Tag): string; + heading({ tokens, depth }: Tokens.Heading): string; + hr(token: Tokens.Hr): string; + list(token: Tokens.List): string; + listitem(item: Tokens.ListItem): string; + checkbox({ checked }: Tokens.Checkbox): string; + paragraph({ tokens }: Tokens.Paragraph): string; + table(token: Tokens.Table): string; + tablerow({ text }: Tokens.TableRow): string; + tablecell(token: Tokens.TableCell): string; + /** + * span level renderer + */ + strong({ tokens }: Tokens.Strong): string; + em({ tokens }: Tokens.Em): string; + codespan({ text }: Tokens.Codespan): string; + br(token: Tokens.Br): string; + del({ tokens }: Tokens.Del): string; + link({ href, title, tokens }: Tokens.Link): string; + image({ href, title, text }: Tokens.Image): string; + text(token: Tokens.Text | Tokens.Escape | Tokens.Tag): string; +} +/** + * TextRenderer + * returns only the textual part of the token + */ +declare class _TextRenderer { + strong({ text }: Tokens.Strong): string; + em({ text }: Tokens.Em): string; + codespan({ text }: Tokens.Codespan): string; + del({ text }: Tokens.Del): string; + html({ text }: Tokens.HTML | Tokens.Tag): string; + text({ text }: Tokens.Text | Tokens.Escape | Tokens.Tag): string; + link({ text }: Tokens.Link): string; + image({ text }: Tokens.Image): string; + br(): string; +} +/** + * Parsing & Compiling + */ +declare class _Parser { + options: MarkedOptions; + renderer: _Renderer; + textRenderer: _TextRenderer; + constructor(options?: MarkedOptions); + /** + * Static Parse Method + */ + static parse(tokens: Token[], options?: MarkedOptions): string; + /** + * Static Parse Inline Method + */ + static parseInline(tokens: Token[], options?: MarkedOptions): string; + /** + * Parse Loop + */ + parse(tokens: Token[], top?: boolean): string; + /** + * Parse Inline Tokens + */ + parseInline(tokens: Token[], renderer?: _Renderer | _TextRenderer): string; +} +declare const blockNormal: { + blockquote: RegExp; + code: RegExp; + def: RegExp; + fences: RegExp; + heading: RegExp; + hr: RegExp; + html: RegExp; + lheading: RegExp; + list: RegExp; + newline: RegExp; + paragraph: RegExp; + table: RegExp; + text: RegExp; +}; +export type BlockKeys = keyof typeof blockNormal; +declare const inlineNormal: { + _backpedal: RegExp; + anyPunctuation: RegExp; + autolink: RegExp; + blockSkip: RegExp; + br: RegExp; + code: RegExp; + del: RegExp; + emStrongLDelim: RegExp; + emStrongRDelimAst: RegExp; + emStrongRDelimUnd: RegExp; + escape: RegExp; + link: RegExp; + nolink: RegExp; + punctuation: RegExp; + reflink: RegExp; + reflinkSearch: RegExp; + tag: RegExp; + text: RegExp; + url: RegExp; +}; +export type InlineKeys = keyof typeof inlineNormal; +/** + * exports + */ +export declare const block: { + normal: { + blockquote: RegExp; + code: RegExp; + def: RegExp; + fences: RegExp; + heading: RegExp; + hr: RegExp; + html: RegExp; + lheading: RegExp; + list: RegExp; + newline: RegExp; + paragraph: RegExp; + table: RegExp; + text: RegExp; + }; + gfm: Record<"code" | "blockquote" | "hr" | "html" | "table" | "text" | "heading" | "list" | "paragraph" | "def" | "fences" | "lheading" | "newline", RegExp>; + pedantic: Record<"code" | "blockquote" | "hr" | "html" | "table" | "text" | "heading" | "list" | "paragraph" | "def" | "fences" | "lheading" | "newline", RegExp>; +}; +export declare const inline: { + normal: { + _backpedal: RegExp; + anyPunctuation: RegExp; + autolink: RegExp; + blockSkip: RegExp; + br: RegExp; + code: RegExp; + del: RegExp; + emStrongLDelim: RegExp; + emStrongRDelimAst: RegExp; + emStrongRDelimUnd: RegExp; + escape: RegExp; + link: RegExp; + nolink: RegExp; + punctuation: RegExp; + reflink: RegExp; + reflinkSearch: RegExp; + tag: RegExp; + text: RegExp; + url: RegExp; + }; + gfm: Record<"link" | "code" | "url" | "br" | "del" | "text" | "escape" | "tag" | "reflink" | "autolink" | "nolink" | "_backpedal" | "anyPunctuation" | "blockSkip" | "emStrongLDelim" | "emStrongRDelimAst" | "emStrongRDelimUnd" | "punctuation" | "reflinkSearch", RegExp>; + breaks: Record<"link" | "code" | "url" | "br" | "del" | "text" | "escape" | "tag" | "reflink" | "autolink" | "nolink" | "_backpedal" | "anyPunctuation" | "blockSkip" | "emStrongLDelim" | "emStrongRDelimAst" | "emStrongRDelimUnd" | "punctuation" | "reflinkSearch", RegExp>; + pedantic: Record<"link" | "code" | "url" | "br" | "del" | "text" | "escape" | "tag" | "reflink" | "autolink" | "nolink" | "_backpedal" | "anyPunctuation" | "blockSkip" | "emStrongLDelim" | "emStrongRDelimAst" | "emStrongRDelimUnd" | "punctuation" | "reflinkSearch", RegExp>; +}; +export interface Rules { + block: Record; + inline: Record; +} +/** + * Tokenizer + */ +declare class _Tokenizer { + options: MarkedOptions; + rules: Rules; + lexer: _Lexer; + constructor(options?: MarkedOptions); + space(src: string): Tokens.Space | undefined; + code(src: string): Tokens.Code | undefined; + fences(src: string): Tokens.Code | undefined; + heading(src: string): Tokens.Heading | undefined; + hr(src: string): Tokens.Hr | undefined; + blockquote(src: string): Tokens.Blockquote | undefined; + list(src: string): Tokens.List | undefined; + html(src: string): Tokens.HTML | undefined; + def(src: string): Tokens.Def | undefined; + table(src: string): Tokens.Table | undefined; + lheading(src: string): Tokens.Heading | undefined; + paragraph(src: string): Tokens.Paragraph | undefined; + text(src: string): Tokens.Text | undefined; + escape(src: string): Tokens.Escape | undefined; + tag(src: string): Tokens.Tag | undefined; + link(src: string): Tokens.Link | Tokens.Image | undefined; + reflink(src: string, links: Links): Tokens.Link | Tokens.Image | Tokens.Text | undefined; + emStrong(src: string, maskedSrc: string, prevChar?: string): Tokens.Em | Tokens.Strong | undefined; + codespan(src: string): Tokens.Codespan | undefined; + br(src: string): Tokens.Br | undefined; + del(src: string): Tokens.Del | undefined; + autolink(src: string): Tokens.Link | undefined; + url(src: string): Tokens.Link | undefined; + inlineText(src: string): Tokens.Text | undefined; +} +declare class _Hooks { + options: MarkedOptions; + constructor(options?: MarkedOptions); + static passThroughHooks: Set; + /** + * Process markdown before marked + */ + preprocess(markdown: string): string; + /** + * Process HTML after marked is finished + */ + postprocess(html: string): string; + /** + * Process all tokens before walk tokens + */ + processAllTokens(tokens: Token[] | TokensList): Token[] | TokensList; +} +export interface TokenizerThis { + lexer: _Lexer; +} +export type TokenizerExtensionFunction = (this: TokenizerThis, src: string, tokens: Token[] | TokensList) => Tokens.Generic | undefined; +export type TokenizerStartFunction = (this: TokenizerThis, src: string) => number | void; +export interface TokenizerExtension { + name: string; + level: "block" | "inline"; + start?: TokenizerStartFunction | undefined; + tokenizer: TokenizerExtensionFunction; + childTokens?: string[] | undefined; +} +export interface RendererThis { + parser: _Parser; +} +export type RendererExtensionFunction = (this: RendererThis, token: Tokens.Generic) => string | false | undefined; +export interface RendererExtension { + name: string; + renderer: RendererExtensionFunction; +} +export type TokenizerAndRendererExtension = TokenizerExtension | RendererExtension | (TokenizerExtension & RendererExtension); +export type HooksApi = Omit<_Hooks, "constructor" | "options">; +export type HooksObject = { + [K in keyof HooksApi]?: (this: _Hooks, ...args: Parameters) => ReturnType | Promise>; +}; +export type RendererApi = Omit<_Renderer, "constructor" | "options" | "parser">; +export type RendererObject = { + [K in keyof RendererApi]?: (this: _Renderer, ...args: Parameters) => ReturnType | false; +}; +export type TokenizerApi = Omit<_Tokenizer, "constructor" | "options" | "rules" | "lexer">; +export type TokenizerObject = { + [K in keyof TokenizerApi]?: (this: _Tokenizer, ...args: Parameters) => ReturnType | false; +}; +export interface MarkedExtension { + /** + * True will tell marked to await any walkTokens functions before parsing the tokens and returning an HTML string. + */ + async?: boolean; + /** + * Enable GFM line breaks. This option requires the gfm option to be true. + */ + breaks?: boolean | undefined; + /** + * Add tokenizers and renderers to marked + */ + extensions?: TokenizerAndRendererExtension[] | undefined | null; + /** + * Enable GitHub flavored markdown. + */ + gfm?: boolean | undefined; + /** + * Hooks are methods that hook into some part of marked. + * preprocess is called to process markdown before sending it to marked. + * processAllTokens is called with the TokensList before walkTokens. + * postprocess is called to process html after marked has finished parsing. + */ + hooks?: HooksObject | undefined | null; + /** + * Conform to obscure parts of markdown.pl as much as possible. Don't fix any of the original markdown bugs or poor behavior. + */ + pedantic?: boolean | undefined; + /** + * Type: object Default: new Renderer() + * + * An object containing functions to render tokens to HTML. + */ + renderer?: RendererObject | undefined | null; + /** + * Shows an HTML error message when rendering fails. + */ + silent?: boolean | undefined; + /** + * The tokenizer defines how to turn markdown text into tokens. + */ + tokenizer?: TokenizerObject | undefined | null; + /** + * The walkTokens function gets called with every token. + * Child tokens are called before moving on to sibling tokens. + * Each token is passed by reference so updates are persisted when passed to the parser. + * The return value of the function is ignored. + */ + walkTokens?: ((token: Token) => void | Promise) | undefined | null; + /** + * Use the new renderer that accepts an object instead of individual parameters. + * This option will be removed and default to true in the next major version. + */ + useNewRenderer?: boolean | undefined; +} +export interface MarkedOptions extends Omit { + /** + * Hooks are methods that hook into some part of marked. + */ + hooks?: _Hooks | undefined | null; + /** + * Type: object Default: new Renderer() + * + * An object containing functions to render tokens to HTML. + */ + renderer?: _Renderer | undefined | null; + /** + * The tokenizer defines how to turn markdown text into tokens. + */ + tokenizer?: _Tokenizer | undefined | null; + /** + * Custom extensions + */ + extensions?: null | { + renderers: { + [name: string]: RendererExtensionFunction; + }; + childTokens: { + [name: string]: string[]; + }; + inline?: TokenizerExtensionFunction[]; + block?: TokenizerExtensionFunction[]; + startInline?: TokenizerStartFunction[]; + startBlock?: TokenizerStartFunction[]; + }; + /** + * walkTokens function returns array of values for Promise.all + */ + walkTokens?: null | ((token: Token) => void | Promise | (void | Promise)[]); +} +/** + * Block Lexer + */ +declare class _Lexer { + tokens: TokensList; + options: MarkedOptions; + state: { + inLink: boolean; + inRawBlock: boolean; + top: boolean; + }; + private tokenizer; + private inlineQueue; + constructor(options?: MarkedOptions); + /** + * Expose Rules + */ + static get rules(): { + block: { + normal: { + blockquote: RegExp; + code: RegExp; + def: RegExp; + fences: RegExp; + heading: RegExp; + hr: RegExp; + html: RegExp; + lheading: RegExp; + list: RegExp; + newline: RegExp; + paragraph: RegExp; + table: RegExp; + text: RegExp; + }; + gfm: Record<"code" | "blockquote" | "hr" | "html" | "table" | "text" | "heading" | "list" | "paragraph" | "def" | "fences" | "lheading" | "newline", RegExp>; + pedantic: Record<"code" | "blockquote" | "hr" | "html" | "table" | "text" | "heading" | "list" | "paragraph" | "def" | "fences" | "lheading" | "newline", RegExp>; + }; + inline: { + normal: { + _backpedal: RegExp; + anyPunctuation: RegExp; + autolink: RegExp; + blockSkip: RegExp; + br: RegExp; + code: RegExp; + del: RegExp; + emStrongLDelim: RegExp; + emStrongRDelimAst: RegExp; + emStrongRDelimUnd: RegExp; + escape: RegExp; + link: RegExp; + nolink: RegExp; + punctuation: RegExp; + reflink: RegExp; + reflinkSearch: RegExp; + tag: RegExp; + text: RegExp; + url: RegExp; + }; + gfm: Record<"link" | "code" | "url" | "br" | "del" | "text" | "escape" | "tag" | "reflink" | "autolink" | "nolink" | "_backpedal" | "anyPunctuation" | "blockSkip" | "emStrongLDelim" | "emStrongRDelimAst" | "emStrongRDelimUnd" | "punctuation" | "reflinkSearch", RegExp>; + breaks: Record<"link" | "code" | "url" | "br" | "del" | "text" | "escape" | "tag" | "reflink" | "autolink" | "nolink" | "_backpedal" | "anyPunctuation" | "blockSkip" | "emStrongLDelim" | "emStrongRDelimAst" | "emStrongRDelimUnd" | "punctuation" | "reflinkSearch", RegExp>; + pedantic: Record<"link" | "code" | "url" | "br" | "del" | "text" | "escape" | "tag" | "reflink" | "autolink" | "nolink" | "_backpedal" | "anyPunctuation" | "blockSkip" | "emStrongLDelim" | "emStrongRDelimAst" | "emStrongRDelimUnd" | "punctuation" | "reflinkSearch", RegExp>; + }; + }; + /** + * Static Lex Method + */ + static lex(src: string, options?: MarkedOptions): TokensList; + /** + * Static Lex Inline Method + */ + static lexInline(src: string, options?: MarkedOptions): Token[]; + /** + * Preprocessing + */ + lex(src: string): TokensList; + /** + * Lexing + */ + blockTokens(src: string, tokens?: Token[], lastParagraphClipped?: boolean): Token[]; + blockTokens(src: string, tokens?: TokensList, lastParagraphClipped?: boolean): TokensList; + inline(src: string, tokens?: Token[]): Token[]; + /** + * Lexing/Compiling + */ + inlineTokens(src: string, tokens?: Token[]): Token[]; +} +/** + * Gets the original marked default options. + */ +declare function _getDefaults(): MarkedOptions; +declare let _defaults: MarkedOptions; +export type MaybePromise = void | Promise; +export declare class Marked { + #private; + defaults: MarkedOptions; + options: (opt: MarkedOptions) => this; + parse: (src: string, options?: MarkedOptions | undefined | null) => string | Promise; + parseInline: (src: string, options?: MarkedOptions | undefined | null) => string | Promise; + Parser: typeof _Parser; + Renderer: typeof _Renderer; + TextRenderer: typeof _TextRenderer; + Lexer: typeof _Lexer; + Tokenizer: typeof _Tokenizer; + Hooks: typeof _Hooks; + constructor(...args: MarkedExtension[]); + /** + * Run callback for every token + */ + walkTokens(tokens: Token[] | TokensList, callback: (token: Token) => MaybePromise | MaybePromise[]): MaybePromise[]; + use(...args: MarkedExtension[]): this; + setOptions(opt: MarkedOptions): this; + lexer(src: string, options?: MarkedOptions): TokensList; + parser(tokens: Token[], options?: MarkedOptions): string; +} +/** + * Compiles markdown to HTML asynchronously. + * + * @param src String of markdown source to be compiled + * @param options Hash of options, having async: true + * @return Promise of string of compiled HTML + */ +export declare function marked(src: string, options: MarkedOptions & { + async: true; +}): Promise; +/** + * Compiles markdown to HTML. + * + * @param src String of markdown source to be compiled + * @param options Optional hash of options + * @return String of compiled HTML. Will be a Promise of string if async is set to true by any extensions. + */ +export declare function marked(src: string, options?: MarkedOptions): string | Promise; +export declare namespace marked { + var options: (options: MarkedOptions) => typeof marked; + var setOptions: (options: MarkedOptions) => typeof marked; + var getDefaults: typeof _getDefaults; + var defaults: MarkedOptions; + var use: (...args: MarkedExtension[]) => typeof marked; + var walkTokens: (tokens: Token[] | TokensList, callback: (token: Token) => MaybePromise | MaybePromise[]) => MaybePromise[]; + var parseInline: (src: string, options?: MarkedOptions | null | undefined) => string | Promise; + var Parser: typeof _Parser; + var parser: typeof _Parser.parse; + var Renderer: typeof _Renderer; + var TextRenderer: typeof _TextRenderer; + var Lexer: typeof _Lexer; + var lexer: typeof _Lexer.lex; + var Tokenizer: typeof _Tokenizer; + var Hooks: typeof _Hooks; + var parse: typeof marked; +} +export declare const options: (options: MarkedOptions) => typeof marked; +export declare const setOptions: (options: MarkedOptions) => typeof marked; +export declare const use: (...args: MarkedExtension[]) => typeof marked; +export declare const walkTokens: (tokens: Token[] | TokensList, callback: (token: Token) => MaybePromise | MaybePromise[]) => MaybePromise[]; +export declare const parseInline: (src: string, options?: MarkedOptions | null | undefined) => string | Promise; +export declare const parse: typeof marked; +export declare const parser: typeof _Parser.parse; +export declare const lexer: typeof _Lexer.lex; + +export { + _Hooks as Hooks, + _Lexer as Lexer, + _Parser as Parser, + _Renderer as Renderer, + _TextRenderer as TextRenderer, + _Tokenizer as Tokenizer, + _defaults as defaults, + _getDefaults as getDefaults, +}; + +export {}; diff --git a/scripts/node_modules/marked/lib/marked.esm.js b/scripts/node_modules/marked/lib/marked.esm.js new file mode 100644 index 000000000..ff860d6f8 --- /dev/null +++ b/scripts/node_modules/marked/lib/marked.esm.js @@ -0,0 +1,2708 @@ +/** + * marked v13.0.1 - a markdown parser + * Copyright (c) 2011-2024, Christopher Jeffrey. (MIT Licensed) + * https://github.com/markedjs/marked + */ + +/** + * DO NOT EDIT THIS FILE + * The code in this file is generated from files in ./src/ + */ + +/** + * Gets the original marked default options. + */ +function _getDefaults() { + return { + async: false, + breaks: false, + extensions: null, + gfm: true, + hooks: null, + pedantic: false, + renderer: null, + silent: false, + tokenizer: null, + walkTokens: null + }; +} +let _defaults = _getDefaults(); +function changeDefaults(newDefaults) { + _defaults = newDefaults; +} + +/** + * Helpers + */ +const escapeTest = /[&<>"']/; +const escapeReplace = new RegExp(escapeTest.source, 'g'); +const escapeTestNoEncode = /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/; +const escapeReplaceNoEncode = new RegExp(escapeTestNoEncode.source, 'g'); +const escapeReplacements = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' +}; +const getEscapeReplacement = (ch) => escapeReplacements[ch]; +function escape$1(html, encode) { + if (encode) { + if (escapeTest.test(html)) { + return html.replace(escapeReplace, getEscapeReplacement); + } + } + else { + if (escapeTestNoEncode.test(html)) { + return html.replace(escapeReplaceNoEncode, getEscapeReplacement); + } + } + return html; +} +const unescapeTest = /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig; +function unescape(html) { + // explicitly match decimal, hex, and named HTML entities + return html.replace(unescapeTest, (_, n) => { + n = n.toLowerCase(); + if (n === 'colon') + return ':'; + if (n.charAt(0) === '#') { + return n.charAt(1) === 'x' + ? String.fromCharCode(parseInt(n.substring(2), 16)) + : String.fromCharCode(+n.substring(1)); + } + return ''; + }); +} +const caret = /(^|[^\[])\^/g; +function edit(regex, opt) { + let source = typeof regex === 'string' ? regex : regex.source; + opt = opt || ''; + const obj = { + replace: (name, val) => { + let valSource = typeof val === 'string' ? val : val.source; + valSource = valSource.replace(caret, '$1'); + source = source.replace(name, valSource); + return obj; + }, + getRegex: () => { + return new RegExp(source, opt); + } + }; + return obj; +} +function cleanUrl(href) { + try { + href = encodeURI(href).replace(/%25/g, '%'); + } + catch (e) { + return null; + } + return href; +} +const noopTest = { exec: () => null }; +function splitCells(tableRow, count) { + // ensure that every cell-delimiting pipe has a space + // before it to distinguish it from an escaped pipe + const row = tableRow.replace(/\|/g, (match, offset, str) => { + let escaped = false; + let curr = offset; + while (--curr >= 0 && str[curr] === '\\') + escaped = !escaped; + if (escaped) { + // odd number of slashes means | is escaped + // so we leave it alone + return '|'; + } + else { + // add space before unescaped | + return ' |'; + } + }), cells = row.split(/ \|/); + let i = 0; + // First/last cell in a row cannot be empty if it has no leading/trailing pipe + if (!cells[0].trim()) { + cells.shift(); + } + if (cells.length > 0 && !cells[cells.length - 1].trim()) { + cells.pop(); + } + if (count) { + if (cells.length > count) { + cells.splice(count); + } + else { + while (cells.length < count) + cells.push(''); + } + } + for (; i < cells.length; i++) { + // leading or trailing whitespace is ignored per the gfm spec + cells[i] = cells[i].trim().replace(/\\\|/g, '|'); + } + return cells; +} +/** + * Remove trailing 'c's. Equivalent to str.replace(/c*$/, ''). + * /c*$/ is vulnerable to REDOS. + * + * @param str + * @param c + * @param invert Remove suffix of non-c chars instead. Default falsey. + */ +function rtrim(str, c, invert) { + const l = str.length; + if (l === 0) { + return ''; + } + // Length of suffix matching the invert condition. + let suffLen = 0; + // Step left until we fail to match the invert condition. + while (suffLen < l) { + const currChar = str.charAt(l - suffLen - 1); + if (currChar === c && !invert) { + suffLen++; + } + else if (currChar !== c && invert) { + suffLen++; + } + else { + break; + } + } + return str.slice(0, l - suffLen); +} +function findClosingBracket(str, b) { + if (str.indexOf(b[1]) === -1) { + return -1; + } + let level = 0; + for (let i = 0; i < str.length; i++) { + if (str[i] === '\\') { + i++; + } + else if (str[i] === b[0]) { + level++; + } + else if (str[i] === b[1]) { + level--; + if (level < 0) { + return i; + } + } + } + return -1; +} + +function outputLink(cap, link, raw, lexer) { + const href = link.href; + const title = link.title ? escape$1(link.title) : null; + const text = cap[1].replace(/\\([\[\]])/g, '$1'); + if (cap[0].charAt(0) !== '!') { + lexer.state.inLink = true; + const token = { + type: 'link', + raw, + href, + title, + text, + tokens: lexer.inlineTokens(text) + }; + lexer.state.inLink = false; + return token; + } + return { + type: 'image', + raw, + href, + title, + text: escape$1(text) + }; +} +function indentCodeCompensation(raw, text) { + const matchIndentToCode = raw.match(/^(\s+)(?:```)/); + if (matchIndentToCode === null) { + return text; + } + const indentToCode = matchIndentToCode[1]; + return text + .split('\n') + .map(node => { + const matchIndentInNode = node.match(/^\s+/); + if (matchIndentInNode === null) { + return node; + } + const [indentInNode] = matchIndentInNode; + if (indentInNode.length >= indentToCode.length) { + return node.slice(indentToCode.length); + } + return node; + }) + .join('\n'); +} +/** + * Tokenizer + */ +class _Tokenizer { + options; + rules; // set by the lexer + lexer; // set by the lexer + constructor(options) { + this.options = options || _defaults; + } + space(src) { + const cap = this.rules.block.newline.exec(src); + if (cap && cap[0].length > 0) { + return { + type: 'space', + raw: cap[0] + }; + } + } + code(src) { + const cap = this.rules.block.code.exec(src); + if (cap) { + const text = cap[0].replace(/^ {1,4}/gm, ''); + return { + type: 'code', + raw: cap[0], + codeBlockStyle: 'indented', + text: !this.options.pedantic + ? rtrim(text, '\n') + : text + }; + } + } + fences(src) { + const cap = this.rules.block.fences.exec(src); + if (cap) { + const raw = cap[0]; + const text = indentCodeCompensation(raw, cap[3] || ''); + return { + type: 'code', + raw, + lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, '$1') : cap[2], + text + }; + } + } + heading(src) { + const cap = this.rules.block.heading.exec(src); + if (cap) { + let text = cap[2].trim(); + // remove trailing #s + if (/#$/.test(text)) { + const trimmed = rtrim(text, '#'); + if (this.options.pedantic) { + text = trimmed.trim(); + } + else if (!trimmed || / $/.test(trimmed)) { + // CommonMark requires space before trailing #s + text = trimmed.trim(); + } + } + return { + type: 'heading', + raw: cap[0], + depth: cap[1].length, + text, + tokens: this.lexer.inline(text) + }; + } + } + hr(src) { + const cap = this.rules.block.hr.exec(src); + if (cap) { + return { + type: 'hr', + raw: rtrim(cap[0], '\n') + }; + } + } + blockquote(src) { + const cap = this.rules.block.blockquote.exec(src); + if (cap) { + let lines = rtrim(cap[0], '\n').split('\n'); + let raw = ''; + let text = ''; + const tokens = []; + while (lines.length > 0) { + let inBlockquote = false; + const currentLines = []; + let i; + for (i = 0; i < lines.length; i++) { + // get lines up to a continuation + if (/^ {0,3}>/.test(lines[i])) { + currentLines.push(lines[i]); + inBlockquote = true; + } + else if (!inBlockquote) { + currentLines.push(lines[i]); + } + else { + break; + } + } + lines = lines.slice(i); + const currentRaw = currentLines.join('\n'); + const currentText = currentRaw + // precede setext continuation with 4 spaces so it isn't a setext + .replace(/\n {0,3}((?:=+|-+) *)(?=\n|$)/g, '\n $1') + .replace(/^ {0,3}>[ \t]?/gm, ''); + raw = raw ? `${raw}\n${currentRaw}` : currentRaw; + text = text ? `${text}\n${currentText}` : currentText; + // parse blockquote lines as top level tokens + // merge paragraphs if this is a continuation + const top = this.lexer.state.top; + this.lexer.state.top = true; + this.lexer.blockTokens(currentText, tokens, true); + this.lexer.state.top = top; + // if there is no continuation then we are done + if (lines.length === 0) { + break; + } + const lastToken = tokens[tokens.length - 1]; + if (lastToken?.type === 'code') { + // blockquote continuation cannot be preceded by a code block + break; + } + else if (lastToken?.type === 'blockquote') { + // include continuation in nested blockquote + const oldToken = lastToken; + const newText = oldToken.raw + '\n' + lines.join('\n'); + const newToken = this.blockquote(newText); + tokens[tokens.length - 1] = newToken; + raw = raw.substring(0, raw.length - oldToken.raw.length) + newToken.raw; + text = text.substring(0, text.length - oldToken.text.length) + newToken.text; + break; + } + else if (lastToken?.type === 'list') { + // include continuation in nested list + const oldToken = lastToken; + const newText = oldToken.raw + '\n' + lines.join('\n'); + const newToken = this.list(newText); + tokens[tokens.length - 1] = newToken; + raw = raw.substring(0, raw.length - lastToken.raw.length) + newToken.raw; + text = text.substring(0, text.length - oldToken.raw.length) + newToken.raw; + lines = newText.substring(tokens[tokens.length - 1].raw.length).split('\n'); + continue; + } + } + return { + type: 'blockquote', + raw, + tokens, + text + }; + } + } + list(src) { + let cap = this.rules.block.list.exec(src); + if (cap) { + let bull = cap[1].trim(); + const isordered = bull.length > 1; + const list = { + type: 'list', + raw: '', + ordered: isordered, + start: isordered ? +bull.slice(0, -1) : '', + loose: false, + items: [] + }; + bull = isordered ? `\\d{1,9}\\${bull.slice(-1)}` : `\\${bull}`; + if (this.options.pedantic) { + bull = isordered ? bull : '[*+-]'; + } + // Get next list item + const itemRegex = new RegExp(`^( {0,3}${bull})((?:[\t ][^\\n]*)?(?:\\n|$))`); + let raw = ''; + let itemContents = ''; + let endsWithBlankLine = false; + // Check if current bullet point can start a new List Item + while (src) { + let endEarly = false; + if (!(cap = itemRegex.exec(src))) { + break; + } + if (this.rules.block.hr.test(src)) { // End list if bullet was actually HR (possibly move into itemRegex?) + break; + } + raw = cap[0]; + src = src.substring(raw.length); + let line = cap[2].split('\n', 1)[0].replace(/^\t+/, (t) => ' '.repeat(3 * t.length)); + let nextLine = src.split('\n', 1)[0]; + let indent = 0; + if (this.options.pedantic) { + indent = 2; + itemContents = line.trimStart(); + } + else { + indent = cap[2].search(/[^ ]/); // Find first non-space char + indent = indent > 4 ? 1 : indent; // Treat indented code blocks (> 4 spaces) as having only 1 indent + itemContents = line.slice(indent); + indent += cap[1].length; + } + let blankLine = false; + if (!line && /^ *$/.test(nextLine)) { // Items begin with at most one blank line + raw += nextLine + '\n'; + src = src.substring(nextLine.length + 1); + endEarly = true; + } + if (!endEarly) { + const nextBulletRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ \t][^\\n]*)?(?:\\n|$))`); + const hrRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`); + const fencesBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\`\`\`|~~~)`); + const headingBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`); + // Check if following lines should be included in List Item + while (src) { + const rawLine = src.split('\n', 1)[0]; + nextLine = rawLine; + // Re-align to follow commonmark nesting rules + if (this.options.pedantic) { + nextLine = nextLine.replace(/^ {1,4}(?=( {4})*[^ ])/g, ' '); + } + // End list item if found code fences + if (fencesBeginRegex.test(nextLine)) { + break; + } + // End list item if found start of new heading + if (headingBeginRegex.test(nextLine)) { + break; + } + // End list item if found start of new bullet + if (nextBulletRegex.test(nextLine)) { + break; + } + // Horizontal rule found + if (hrRegex.test(src)) { + break; + } + if (nextLine.search(/[^ ]/) >= indent || !nextLine.trim()) { // Dedent if possible + itemContents += '\n' + nextLine.slice(indent); + } + else { + // not enough indentation + if (blankLine) { + break; + } + // paragraph continuation unless last line was a different block level element + if (line.search(/[^ ]/) >= 4) { // indented code block + break; + } + if (fencesBeginRegex.test(line)) { + break; + } + if (headingBeginRegex.test(line)) { + break; + } + if (hrRegex.test(line)) { + break; + } + itemContents += '\n' + nextLine; + } + if (!blankLine && !nextLine.trim()) { // Check if current line is blank + blankLine = true; + } + raw += rawLine + '\n'; + src = src.substring(rawLine.length + 1); + line = nextLine.slice(indent); + } + } + if (!list.loose) { + // If the previous item ended with a blank line, the list is loose + if (endsWithBlankLine) { + list.loose = true; + } + else if (/\n *\n *$/.test(raw)) { + endsWithBlankLine = true; + } + } + let istask = null; + let ischecked; + // Check for task list items + if (this.options.gfm) { + istask = /^\[[ xX]\] /.exec(itemContents); + if (istask) { + ischecked = istask[0] !== '[ ] '; + itemContents = itemContents.replace(/^\[[ xX]\] +/, ''); + } + } + list.items.push({ + type: 'list_item', + raw, + task: !!istask, + checked: ischecked, + loose: false, + text: itemContents, + tokens: [] + }); + list.raw += raw; + } + // Do not consume newlines at end of final item. Alternatively, make itemRegex *start* with any newlines to simplify/speed up endsWithBlankLine logic + list.items[list.items.length - 1].raw = raw.trimEnd(); + (list.items[list.items.length - 1]).text = itemContents.trimEnd(); + list.raw = list.raw.trimEnd(); + // Item child tokens handled here at end because we needed to have the final item to trim it first + for (let i = 0; i < list.items.length; i++) { + this.lexer.state.top = false; + list.items[i].tokens = this.lexer.blockTokens(list.items[i].text, []); + if (!list.loose) { + // Check if list should be loose + const spacers = list.items[i].tokens.filter(t => t.type === 'space'); + const hasMultipleLineBreaks = spacers.length > 0 && spacers.some(t => /\n.*\n/.test(t.raw)); + list.loose = hasMultipleLineBreaks; + } + } + // Set all items to loose if list is loose + if (list.loose) { + for (let i = 0; i < list.items.length; i++) { + list.items[i].loose = true; + } + } + return list; + } + } + html(src) { + const cap = this.rules.block.html.exec(src); + if (cap) { + const token = { + type: 'html', + block: true, + raw: cap[0], + pre: cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style', + text: cap[0] + }; + return token; + } + } + def(src) { + const cap = this.rules.block.def.exec(src); + if (cap) { + const tag = cap[1].toLowerCase().replace(/\s+/g, ' '); + const href = cap[2] ? cap[2].replace(/^<(.*)>$/, '$1').replace(this.rules.inline.anyPunctuation, '$1') : ''; + const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, '$1') : cap[3]; + return { + type: 'def', + tag, + raw: cap[0], + href, + title + }; + } + } + table(src) { + const cap = this.rules.block.table.exec(src); + if (!cap) { + return; + } + if (!/[:|]/.test(cap[2])) { + // delimiter row must have a pipe (|) or colon (:) otherwise it is a setext heading + return; + } + const headers = splitCells(cap[1]); + const aligns = cap[2].replace(/^\||\| *$/g, '').split('|'); + const rows = cap[3] && cap[3].trim() ? cap[3].replace(/\n[ \t]*$/, '').split('\n') : []; + const item = { + type: 'table', + raw: cap[0], + header: [], + align: [], + rows: [] + }; + if (headers.length !== aligns.length) { + // header and align columns must be equal, rows can be different. + return; + } + for (const align of aligns) { + if (/^ *-+: *$/.test(align)) { + item.align.push('right'); + } + else if (/^ *:-+: *$/.test(align)) { + item.align.push('center'); + } + else if (/^ *:-+ *$/.test(align)) { + item.align.push('left'); + } + else { + item.align.push(null); + } + } + for (let i = 0; i < headers.length; i++) { + item.header.push({ + text: headers[i], + tokens: this.lexer.inline(headers[i]), + header: true, + align: item.align[i] + }); + } + for (const row of rows) { + item.rows.push(splitCells(row, item.header.length).map((cell, i) => { + return { + text: cell, + tokens: this.lexer.inline(cell), + header: false, + align: item.align[i] + }; + })); + } + return item; + } + lheading(src) { + const cap = this.rules.block.lheading.exec(src); + if (cap) { + return { + type: 'heading', + raw: cap[0], + depth: cap[2].charAt(0) === '=' ? 1 : 2, + text: cap[1], + tokens: this.lexer.inline(cap[1]) + }; + } + } + paragraph(src) { + const cap = this.rules.block.paragraph.exec(src); + if (cap) { + const text = cap[1].charAt(cap[1].length - 1) === '\n' + ? cap[1].slice(0, -1) + : cap[1]; + return { + type: 'paragraph', + raw: cap[0], + text, + tokens: this.lexer.inline(text) + }; + } + } + text(src) { + const cap = this.rules.block.text.exec(src); + if (cap) { + return { + type: 'text', + raw: cap[0], + text: cap[0], + tokens: this.lexer.inline(cap[0]) + }; + } + } + escape(src) { + const cap = this.rules.inline.escape.exec(src); + if (cap) { + return { + type: 'escape', + raw: cap[0], + text: escape$1(cap[1]) + }; + } + } + tag(src) { + const cap = this.rules.inline.tag.exec(src); + if (cap) { + if (!this.lexer.state.inLink && /^
    /i.test(cap[0])) { + this.lexer.state.inLink = false; + } + if (!this.lexer.state.inRawBlock && /^<(pre|code|kbd|script)(\s|>)/i.test(cap[0])) { + this.lexer.state.inRawBlock = true; + } + else if (this.lexer.state.inRawBlock && /^<\/(pre|code|kbd|script)(\s|>)/i.test(cap[0])) { + this.lexer.state.inRawBlock = false; + } + return { + type: 'html', + raw: cap[0], + inLink: this.lexer.state.inLink, + inRawBlock: this.lexer.state.inRawBlock, + block: false, + text: cap[0] + }; + } + } + link(src) { + const cap = this.rules.inline.link.exec(src); + if (cap) { + const trimmedUrl = cap[2].trim(); + if (!this.options.pedantic && /^$/.test(trimmedUrl))) { + return; + } + // ending angle bracket cannot be escaped + const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), '\\'); + if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) { + return; + } + } + else { + // find closing parenthesis + const lastParenIndex = findClosingBracket(cap[2], '()'); + if (lastParenIndex > -1) { + const start = cap[0].indexOf('!') === 0 ? 5 : 4; + const linkLen = start + cap[1].length + lastParenIndex; + cap[2] = cap[2].substring(0, lastParenIndex); + cap[0] = cap[0].substring(0, linkLen).trim(); + cap[3] = ''; + } + } + let href = cap[2]; + let title = ''; + if (this.options.pedantic) { + // split pedantic href and title + const link = /^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(href); + if (link) { + href = link[1]; + title = link[3]; + } + } + else { + title = cap[3] ? cap[3].slice(1, -1) : ''; + } + href = href.trim(); + if (/^$/.test(trimmedUrl))) { + // pedantic allows starting angle bracket without ending angle bracket + href = href.slice(1); + } + else { + href = href.slice(1, -1); + } + } + return outputLink(cap, { + href: href ? href.replace(this.rules.inline.anyPunctuation, '$1') : href, + title: title ? title.replace(this.rules.inline.anyPunctuation, '$1') : title + }, cap[0], this.lexer); + } + } + reflink(src, links) { + let cap; + if ((cap = this.rules.inline.reflink.exec(src)) + || (cap = this.rules.inline.nolink.exec(src))) { + const linkString = (cap[2] || cap[1]).replace(/\s+/g, ' '); + const link = links[linkString.toLowerCase()]; + if (!link) { + const text = cap[0].charAt(0); + return { + type: 'text', + raw: text, + text + }; + } + return outputLink(cap, link, cap[0], this.lexer); + } + } + emStrong(src, maskedSrc, prevChar = '') { + let match = this.rules.inline.emStrongLDelim.exec(src); + if (!match) + return; + // _ can't be between two alphanumerics. \p{L}\p{N} includes non-english alphabet/numbers as well + if (match[3] && prevChar.match(/[\p{L}\p{N}]/u)) + return; + const nextChar = match[1] || match[2] || ''; + if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) { + // unicode Regex counts emoji as 1 char; spread into array for proper count (used multiple times below) + const lLength = [...match[0]].length - 1; + let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0; + const endReg = match[0][0] === '*' ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd; + endReg.lastIndex = 0; + // Clip maskedSrc to same section of string as src (move to lexer?) + maskedSrc = maskedSrc.slice(-1 * src.length + lLength); + while ((match = endReg.exec(maskedSrc)) != null) { + rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6]; + if (!rDelim) + continue; // skip single * in __abc*abc__ + rLength = [...rDelim].length; + if (match[3] || match[4]) { // found another Left Delim + delimTotal += rLength; + continue; + } + else if (match[5] || match[6]) { // either Left or Right Delim + if (lLength % 3 && !((lLength + rLength) % 3)) { + midDelimTotal += rLength; + continue; // CommonMark Emphasis Rules 9-10 + } + } + delimTotal -= rLength; + if (delimTotal > 0) + continue; // Haven't found enough closing delimiters + // Remove extra characters. *a*** -> *a* + rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal); + // char length can be >1 for unicode characters; + const lastCharLength = [...match[0]][0].length; + const raw = src.slice(0, lLength + match.index + lastCharLength + rLength); + // Create `em` if smallest delimiter has odd char count. *a*** + if (Math.min(lLength, rLength) % 2) { + const text = raw.slice(1, -1); + return { + type: 'em', + raw, + text, + tokens: this.lexer.inlineTokens(text) + }; + } + // Create 'strong' if smallest delimiter has even char count. **a*** + const text = raw.slice(2, -2); + return { + type: 'strong', + raw, + text, + tokens: this.lexer.inlineTokens(text) + }; + } + } + } + codespan(src) { + const cap = this.rules.inline.code.exec(src); + if (cap) { + let text = cap[2].replace(/\n/g, ' '); + const hasNonSpaceChars = /[^ ]/.test(text); + const hasSpaceCharsOnBothEnds = /^ /.test(text) && / $/.test(text); + if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) { + text = text.substring(1, text.length - 1); + } + text = escape$1(text, true); + return { + type: 'codespan', + raw: cap[0], + text + }; + } + } + br(src) { + const cap = this.rules.inline.br.exec(src); + if (cap) { + return { + type: 'br', + raw: cap[0] + }; + } + } + del(src) { + const cap = this.rules.inline.del.exec(src); + if (cap) { + return { + type: 'del', + raw: cap[0], + text: cap[2], + tokens: this.lexer.inlineTokens(cap[2]) + }; + } + } + autolink(src) { + const cap = this.rules.inline.autolink.exec(src); + if (cap) { + let text, href; + if (cap[2] === '@') { + text = escape$1(cap[1]); + href = 'mailto:' + text; + } + else { + text = escape$1(cap[1]); + href = text; + } + return { + type: 'link', + raw: cap[0], + text, + href, + tokens: [ + { + type: 'text', + raw: text, + text + } + ] + }; + } + } + url(src) { + let cap; + if (cap = this.rules.inline.url.exec(src)) { + let text, href; + if (cap[2] === '@') { + text = escape$1(cap[0]); + href = 'mailto:' + text; + } + else { + // do extended autolink path validation + let prevCapZero; + do { + prevCapZero = cap[0]; + cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? ''; + } while (prevCapZero !== cap[0]); + text = escape$1(cap[0]); + if (cap[1] === 'www.') { + href = 'http://' + cap[0]; + } + else { + href = cap[0]; + } + } + return { + type: 'link', + raw: cap[0], + text, + href, + tokens: [ + { + type: 'text', + raw: text, + text + } + ] + }; + } + } + inlineText(src) { + const cap = this.rules.inline.text.exec(src); + if (cap) { + let text; + if (this.lexer.state.inRawBlock) { + text = cap[0]; + } + else { + text = escape$1(cap[0]); + } + return { + type: 'text', + raw: cap[0], + text + }; + } + } +} + +/** + * Block-Level Grammar + */ +const newline = /^(?: *(?:\n|$))+/; +const blockCode = /^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/; +const fences = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/; +const hr = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/; +const heading = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/; +const bullet = /(?:[*+-]|\d{1,9}[.)])/; +const lheading = edit(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/) + .replace(/bull/g, bullet) // lists can interrupt + .replace(/blockCode/g, / {4}/) // indented code blocks can interrupt + .replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/) // fenced code blocks can interrupt + .replace(/blockquote/g, / {0,3}>/) // blockquote can interrupt + .replace(/heading/g, / {0,3}#{1,6}/) // ATX heading can interrupt + .replace(/html/g, / {0,3}<[^\n>]+>\n/) // block html can interrupt + .getRegex(); +const _paragraph = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/; +const blockText = /^[^\n]+/; +const _blockLabel = /(?!\s*\])(?:\\.|[^\[\]\\])+/; +const def = edit(/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/) + .replace('label', _blockLabel) + .replace('title', /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/) + .getRegex(); +const list = edit(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/) + .replace(/bull/g, bullet) + .getRegex(); +const _tag = 'address|article|aside|base|basefont|blockquote|body|caption' + + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption' + + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe' + + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option' + + '|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title' + + '|tr|track|ul'; +const _comment = /|$))/; +const html = edit('^ {0,3}(?:' // optional indentation + + '<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)' // (1) + + '|comment[^\\n]*(\\n+|$)' // (2) + + '|<\\?[\\s\\S]*?(?:\\?>\\n*|$)' // (3) + + '|\\n*|$)' // (4) + + '|\\n*|$)' // (5) + + '|)[\\s\\S]*?(?:(?:\\n *)+\\n|$)' // (6) + + '|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)' // (7) open tag + + '|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)' // (7) closing tag + + ')', 'i') + .replace('comment', _comment) + .replace('tag', _tag) + .replace('attribute', / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/) + .getRegex(); +const paragraph = edit(_paragraph) + .replace('hr', hr) + .replace('heading', ' {0,3}#{1,6}(?:\\s|$)') + .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs + .replace('|table', '') + .replace('blockquote', ' {0,3}>') + .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n') + .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt + .replace('html', ')|<(?:script|pre|style|textarea|!--)') + .replace('tag', _tag) // pars can be interrupted by type (6) html blocks + .getRegex(); +const blockquote = edit(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/) + .replace('paragraph', paragraph) + .getRegex(); +/** + * Normal Block Grammar + */ +const blockNormal = { + blockquote, + code: blockCode, + def, + fences, + heading, + hr, + html, + lheading, + list, + newline, + paragraph, + table: noopTest, + text: blockText +}; +/** + * GFM Block Grammar + */ +const gfmTable = edit('^ *([^\\n ].*)\\n' // Header + + ' {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)' // Align + + '(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)') // Cells + .replace('hr', hr) + .replace('heading', ' {0,3}#{1,6}(?:\\s|$)') + .replace('blockquote', ' {0,3}>') + .replace('code', ' {4}[^\\n]') + .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n') + .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt + .replace('html', ')|<(?:script|pre|style|textarea|!--)') + .replace('tag', _tag) // tables can be interrupted by type (6) html blocks + .getRegex(); +const blockGfm = { + ...blockNormal, + table: gfmTable, + paragraph: edit(_paragraph) + .replace('hr', hr) + .replace('heading', ' {0,3}#{1,6}(?:\\s|$)') + .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs + .replace('table', gfmTable) // interrupt paragraphs with table + .replace('blockquote', ' {0,3}>') + .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n') + .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt + .replace('html', ')|<(?:script|pre|style|textarea|!--)') + .replace('tag', _tag) // pars can be interrupted by type (6) html blocks + .getRegex() +}; +/** + * Pedantic grammar (original John Gruber's loose markdown specification) + */ +const blockPedantic = { + ...blockNormal, + html: edit('^ *(?:comment *(?:\\n|\\s*$)' + + '|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)' // closed tag + + '|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))') + .replace('comment', _comment) + .replace(/tag/g, '(?!(?:' + + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub' + + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)' + + '\\b)\\w+(?!:|[^\\w\\s@]*@)\\b') + .getRegex(), + def: /^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/, + heading: /^(#{1,6})(.*)(?:\n+|$)/, + fences: noopTest, // fences not supported + lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/, + paragraph: edit(_paragraph) + .replace('hr', hr) + .replace('heading', ' *#{1,6} *[^\n]') + .replace('lheading', lheading) + .replace('|table', '') + .replace('blockquote', ' {0,3}>') + .replace('|fences', '') + .replace('|list', '') + .replace('|html', '') + .replace('|tag', '') + .getRegex() +}; +/** + * Inline-Level Grammar + */ +const escape = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/; +const inlineCode = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/; +const br = /^( {2,}|\\)\n(?!\s*$)/; +const inlineText = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\ +const blockSkip = /\[[^[\]]*?\]\([^\(\)]*?\)|`[^`]*?`|<[^<>]*?>/g; +const emStrongLDelim = edit(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/, 'u') + .replace(/punct/g, _punctuation) + .getRegex(); +const emStrongRDelimAst = edit('^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)' // Skip orphan inside strong + + '|[^*]+(?=[^*])' // Consume to delim + + '|(?!\\*)[punct](\\*+)(?=[\\s]|$)' // (1) #*** can only be a Right Delimiter + + '|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)' // (2) a***#, a*** can only be a Right Delimiter + + '|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])' // (3) #***a, ***a can only be Left Delimiter + + '|[\\s](\\*+)(?!\\*)(?=[punct])' // (4) ***# can only be Left Delimiter + + '|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])' // (5) #***# can be either Left or Right Delimiter + + '|[^punct\\s](\\*+)(?=[^punct\\s])', 'gu') // (6) a***a can be either Left or Right Delimiter + .replace(/punct/g, _punctuation) + .getRegex(); +// (6) Not allowed for _ +const emStrongRDelimUnd = edit('^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)' // Skip orphan inside strong + + '|[^_]+(?=[^_])' // Consume to delim + + '|(?!_)[punct](_+)(?=[\\s]|$)' // (1) #___ can only be a Right Delimiter + + '|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)' // (2) a___#, a___ can only be a Right Delimiter + + '|(?!_)[punct\\s](_+)(?=[^punct\\s])' // (3) #___a, ___a can only be Left Delimiter + + '|[\\s](_+)(?!_)(?=[punct])' // (4) ___# can only be Left Delimiter + + '|(?!_)[punct](_+)(?!_)(?=[punct])', 'gu') // (5) #___# can be either Left or Right Delimiter + .replace(/punct/g, _punctuation) + .getRegex(); +const anyPunctuation = edit(/\\([punct])/, 'gu') + .replace(/punct/g, _punctuation) + .getRegex(); +const autolink = edit(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/) + .replace('scheme', /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/) + .replace('email', /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/) + .getRegex(); +const _inlineComment = edit(_comment).replace('(?:-->|$)', '-->').getRegex(); +const tag = edit('^comment' + + '|^' // self-closing tag + + '|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>' // open tag + + '|^<\\?[\\s\\S]*?\\?>' // processing instruction, e.g. + + '|^' // declaration, e.g. + + '|^') // CDATA section + .replace('comment', _inlineComment) + .replace('attribute', /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/) + .getRegex(); +const _inlineLabel = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/; +const link = edit(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/) + .replace('label', _inlineLabel) + .replace('href', /<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/) + .replace('title', /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/) + .getRegex(); +const reflink = edit(/^!?\[(label)\]\[(ref)\]/) + .replace('label', _inlineLabel) + .replace('ref', _blockLabel) + .getRegex(); +const nolink = edit(/^!?\[(ref)\](?:\[\])?/) + .replace('ref', _blockLabel) + .getRegex(); +const reflinkSearch = edit('reflink|nolink(?!\\()', 'g') + .replace('reflink', reflink) + .replace('nolink', nolink) + .getRegex(); +/** + * Normal Inline Grammar + */ +const inlineNormal = { + _backpedal: noopTest, // only used for GFM url + anyPunctuation, + autolink, + blockSkip, + br, + code: inlineCode, + del: noopTest, + emStrongLDelim, + emStrongRDelimAst, + emStrongRDelimUnd, + escape, + link, + nolink, + punctuation, + reflink, + reflinkSearch, + tag, + text: inlineText, + url: noopTest +}; +/** + * Pedantic Inline Grammar + */ +const inlinePedantic = { + ...inlineNormal, + link: edit(/^!?\[(label)\]\((.*?)\)/) + .replace('label', _inlineLabel) + .getRegex(), + reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/) + .replace('label', _inlineLabel) + .getRegex() +}; +/** + * GFM Inline Grammar + */ +const inlineGfm = { + ...inlineNormal, + escape: edit(escape).replace('])', '~|])').getRegex(), + url: edit(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/, 'i') + .replace('email', /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/) + .getRegex(), + _backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/, + del: /^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/, + text: /^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\ { + return leading + ' '.repeat(tabs.length); + }); + } + let token; + let lastToken; + let cutSrc; + while (src) { + if (this.options.extensions + && this.options.extensions.block + && this.options.extensions.block.some((extTokenizer) => { + if (token = extTokenizer.call({ lexer: this }, src, tokens)) { + src = src.substring(token.raw.length); + tokens.push(token); + return true; + } + return false; + })) { + continue; + } + // newline + if (token = this.tokenizer.space(src)) { + src = src.substring(token.raw.length); + if (token.raw.length === 1 && tokens.length > 0) { + // if there's a single \n as a spacer, it's terminating the last line, + // so move it there so that we don't get unnecessary paragraph tags + tokens[tokens.length - 1].raw += '\n'; + } + else { + tokens.push(token); + } + continue; + } + // code + if (token = this.tokenizer.code(src)) { + src = src.substring(token.raw.length); + lastToken = tokens[tokens.length - 1]; + // An indented code block cannot interrupt a paragraph. + if (lastToken && (lastToken.type === 'paragraph' || lastToken.type === 'text')) { + lastToken.raw += '\n' + token.raw; + lastToken.text += '\n' + token.text; + this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text; + } + else { + tokens.push(token); + } + continue; + } + // fences + if (token = this.tokenizer.fences(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // heading + if (token = this.tokenizer.heading(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // hr + if (token = this.tokenizer.hr(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // blockquote + if (token = this.tokenizer.blockquote(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // list + if (token = this.tokenizer.list(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // html + if (token = this.tokenizer.html(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // def + if (token = this.tokenizer.def(src)) { + src = src.substring(token.raw.length); + lastToken = tokens[tokens.length - 1]; + if (lastToken && (lastToken.type === 'paragraph' || lastToken.type === 'text')) { + lastToken.raw += '\n' + token.raw; + lastToken.text += '\n' + token.raw; + this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text; + } + else if (!this.tokens.links[token.tag]) { + this.tokens.links[token.tag] = { + href: token.href, + title: token.title + }; + } + continue; + } + // table (gfm) + if (token = this.tokenizer.table(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // lheading + if (token = this.tokenizer.lheading(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // top-level paragraph + // prevent paragraph consuming extensions by clipping 'src' to extension start + cutSrc = src; + if (this.options.extensions && this.options.extensions.startBlock) { + let startIndex = Infinity; + const tempSrc = src.slice(1); + let tempStart; + this.options.extensions.startBlock.forEach((getStartIndex) => { + tempStart = getStartIndex.call({ lexer: this }, tempSrc); + if (typeof tempStart === 'number' && tempStart >= 0) { + startIndex = Math.min(startIndex, tempStart); + } + }); + if (startIndex < Infinity && startIndex >= 0) { + cutSrc = src.substring(0, startIndex + 1); + } + } + if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) { + lastToken = tokens[tokens.length - 1]; + if (lastParagraphClipped && lastToken?.type === 'paragraph') { + lastToken.raw += '\n' + token.raw; + lastToken.text += '\n' + token.text; + this.inlineQueue.pop(); + this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text; + } + else { + tokens.push(token); + } + lastParagraphClipped = (cutSrc.length !== src.length); + src = src.substring(token.raw.length); + continue; + } + // text + if (token = this.tokenizer.text(src)) { + src = src.substring(token.raw.length); + lastToken = tokens[tokens.length - 1]; + if (lastToken && lastToken.type === 'text') { + lastToken.raw += '\n' + token.raw; + lastToken.text += '\n' + token.text; + this.inlineQueue.pop(); + this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text; + } + else { + tokens.push(token); + } + continue; + } + if (src) { + const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0); + if (this.options.silent) { + console.error(errMsg); + break; + } + else { + throw new Error(errMsg); + } + } + } + this.state.top = true; + return tokens; + } + inline(src, tokens = []) { + this.inlineQueue.push({ src, tokens }); + return tokens; + } + /** + * Lexing/Compiling + */ + inlineTokens(src, tokens = []) { + let token, lastToken, cutSrc; + // String with links masked to avoid interference with em and strong + let maskedSrc = src; + let match; + let keepPrevChar, prevChar; + // Mask out reflinks + if (this.tokens.links) { + const links = Object.keys(this.tokens.links); + if (links.length > 0) { + while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) { + if (links.includes(match[0].slice(match[0].lastIndexOf('[') + 1, -1))) { + maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex); + } + } + } + } + // Mask out other blocks + while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) { + maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex); + } + // Mask out escaped characters + while ((match = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) != null) { + maskedSrc = maskedSrc.slice(0, match.index) + '++' + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex); + } + while (src) { + if (!keepPrevChar) { + prevChar = ''; + } + keepPrevChar = false; + // extensions + if (this.options.extensions + && this.options.extensions.inline + && this.options.extensions.inline.some((extTokenizer) => { + if (token = extTokenizer.call({ lexer: this }, src, tokens)) { + src = src.substring(token.raw.length); + tokens.push(token); + return true; + } + return false; + })) { + continue; + } + // escape + if (token = this.tokenizer.escape(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // tag + if (token = this.tokenizer.tag(src)) { + src = src.substring(token.raw.length); + lastToken = tokens[tokens.length - 1]; + if (lastToken && token.type === 'text' && lastToken.type === 'text') { + lastToken.raw += token.raw; + lastToken.text += token.text; + } + else { + tokens.push(token); + } + continue; + } + // link + if (token = this.tokenizer.link(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // reflink, nolink + if (token = this.tokenizer.reflink(src, this.tokens.links)) { + src = src.substring(token.raw.length); + lastToken = tokens[tokens.length - 1]; + if (lastToken && token.type === 'text' && lastToken.type === 'text') { + lastToken.raw += token.raw; + lastToken.text += token.text; + } + else { + tokens.push(token); + } + continue; + } + // em & strong + if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // code + if (token = this.tokenizer.codespan(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // br + if (token = this.tokenizer.br(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // del (gfm) + if (token = this.tokenizer.del(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // autolink + if (token = this.tokenizer.autolink(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // url (gfm) + if (!this.state.inLink && (token = this.tokenizer.url(src))) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // text + // prevent inlineText consuming extensions by clipping 'src' to extension start + cutSrc = src; + if (this.options.extensions && this.options.extensions.startInline) { + let startIndex = Infinity; + const tempSrc = src.slice(1); + let tempStart; + this.options.extensions.startInline.forEach((getStartIndex) => { + tempStart = getStartIndex.call({ lexer: this }, tempSrc); + if (typeof tempStart === 'number' && tempStart >= 0) { + startIndex = Math.min(startIndex, tempStart); + } + }); + if (startIndex < Infinity && startIndex >= 0) { + cutSrc = src.substring(0, startIndex + 1); + } + } + if (token = this.tokenizer.inlineText(cutSrc)) { + src = src.substring(token.raw.length); + if (token.raw.slice(-1) !== '_') { // Track prevChar before string of ____ started + prevChar = token.raw.slice(-1); + } + keepPrevChar = true; + lastToken = tokens[tokens.length - 1]; + if (lastToken && lastToken.type === 'text') { + lastToken.raw += token.raw; + lastToken.text += token.text; + } + else { + tokens.push(token); + } + continue; + } + if (src) { + const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0); + if (this.options.silent) { + console.error(errMsg); + break; + } + else { + throw new Error(errMsg); + } + } + } + return tokens; + } +} + +/** + * Renderer + */ +class _Renderer { + options; + parser; // set by the parser + constructor(options) { + this.options = options || _defaults; + } + space(token) { + return ''; + } + code({ text, lang, escaped }) { + const langString = (lang || '').match(/^\S*/)?.[0]; + const code = text.replace(/\n$/, '') + '\n'; + if (!langString) { + return '
    '
    +                + (escaped ? code : escape$1(code, true))
    +                + '
    \n'; + } + return '
    '
    +            + (escaped ? code : escape$1(code, true))
    +            + '
    \n'; + } + blockquote({ tokens }) { + const body = this.parser.parse(tokens); + return `
    \n${body}
    \n`; + } + html({ text }) { + return text; + } + heading({ tokens, depth }) { + return `${this.parser.parseInline(tokens)}\n`; + } + hr(token) { + return '
    \n'; + } + list(token) { + const ordered = token.ordered; + const start = token.start; + let body = ''; + for (let j = 0; j < token.items.length; j++) { + const item = token.items[j]; + body += this.listitem(item); + } + const type = ordered ? 'ol' : 'ul'; + const startAttr = (ordered && start !== 1) ? (' start="' + start + '"') : ''; + return '<' + type + startAttr + '>\n' + body + '\n'; + } + listitem(item) { + let itemBody = ''; + if (item.task) { + const checkbox = this.checkbox({ checked: !!item.checked }); + if (item.loose) { + if (item.tokens.length > 0 && item.tokens[0].type === 'paragraph') { + item.tokens[0].text = checkbox + ' ' + item.tokens[0].text; + if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') { + item.tokens[0].tokens[0].text = checkbox + ' ' + item.tokens[0].tokens[0].text; + } + } + else { + item.tokens.unshift({ + type: 'text', + raw: checkbox + ' ', + text: checkbox + ' ' + }); + } + } + else { + itemBody += checkbox + ' '; + } + } + itemBody += this.parser.parse(item.tokens, !!item.loose); + return `
  • ${itemBody}
  • \n`; + } + checkbox({ checked }) { + return ''; + } + paragraph({ tokens }) { + return `

    ${this.parser.parseInline(tokens)}

    \n`; + } + table(token) { + let header = ''; + // header + let cell = ''; + for (let j = 0; j < token.header.length; j++) { + cell += this.tablecell(token.header[j]); + } + header += this.tablerow({ text: cell }); + let body = ''; + for (let j = 0; j < token.rows.length; j++) { + const row = token.rows[j]; + cell = ''; + for (let k = 0; k < row.length; k++) { + cell += this.tablecell(row[k]); + } + body += this.tablerow({ text: cell }); + } + if (body) + body = `${body}`; + return '\n' + + '\n' + + header + + '\n' + + body + + '
    \n'; + } + tablerow({ text }) { + return `\n${text}\n`; + } + tablecell(token) { + const content = this.parser.parseInline(token.tokens); + const type = token.header ? 'th' : 'td'; + const tag = token.align + ? `<${type} align="${token.align}">` + : `<${type}>`; + return tag + content + `\n`; + } + /** + * span level renderer + */ + strong({ tokens }) { + return `${this.parser.parseInline(tokens)}`; + } + em({ tokens }) { + return `${this.parser.parseInline(tokens)}`; + } + codespan({ text }) { + return `${text}`; + } + br(token) { + return '
    '; + } + del({ tokens }) { + return `${this.parser.parseInline(tokens)}`; + } + link({ href, title, tokens }) { + const text = this.parser.parseInline(tokens); + const cleanHref = cleanUrl(href); + if (cleanHref === null) { + return text; + } + href = cleanHref; + let out = '
    '; + return out; + } + image({ href, title, text }) { + const cleanHref = cleanUrl(href); + if (cleanHref === null) { + return text; + } + href = cleanHref; + let out = `${text} { + const tokens = genericToken[childTokens].flat(Infinity); + values = values.concat(this.walkTokens(tokens, callback)); + }); + } + else if (genericToken.tokens) { + values = values.concat(this.walkTokens(genericToken.tokens, callback)); + } + } + } + } + return values; + } + use(...args) { + const extensions = this.defaults.extensions || { renderers: {}, childTokens: {} }; + args.forEach((pack) => { + // copy options to new object + const opts = { ...pack }; + // set async to true if it was set to true before + opts.async = this.defaults.async || opts.async || false; + // ==-- Parse "addon" extensions --== // + if (pack.extensions) { + pack.extensions.forEach((ext) => { + if (!ext.name) { + throw new Error('extension name required'); + } + if ('renderer' in ext) { // Renderer extensions + const prevRenderer = extensions.renderers[ext.name]; + if (prevRenderer) { + // Replace extension with func to run new extension but fall back if false + extensions.renderers[ext.name] = function (...args) { + let ret = ext.renderer.apply(this, args); + if (ret === false) { + ret = prevRenderer.apply(this, args); + } + return ret; + }; + } + else { + extensions.renderers[ext.name] = ext.renderer; + } + } + if ('tokenizer' in ext) { // Tokenizer Extensions + if (!ext.level || (ext.level !== 'block' && ext.level !== 'inline')) { + throw new Error("extension level must be 'block' or 'inline'"); + } + const extLevel = extensions[ext.level]; + if (extLevel) { + extLevel.unshift(ext.tokenizer); + } + else { + extensions[ext.level] = [ext.tokenizer]; + } + if (ext.start) { // Function to check for start of token + if (ext.level === 'block') { + if (extensions.startBlock) { + extensions.startBlock.push(ext.start); + } + else { + extensions.startBlock = [ext.start]; + } + } + else if (ext.level === 'inline') { + if (extensions.startInline) { + extensions.startInline.push(ext.start); + } + else { + extensions.startInline = [ext.start]; + } + } + } + } + if ('childTokens' in ext && ext.childTokens) { // Child tokens to be visited by walkTokens + extensions.childTokens[ext.name] = ext.childTokens; + } + }); + opts.extensions = extensions; + } + // ==-- Parse "overwrite" extensions --== // + if (pack.renderer) { + const renderer = this.defaults.renderer || new _Renderer(this.defaults); + for (const prop in pack.renderer) { + if (!(prop in renderer)) { + throw new Error(`renderer '${prop}' does not exist`); + } + if (['options', 'parser'].includes(prop)) { + // ignore options property + continue; + } + const rendererProp = prop; + let rendererFunc = pack.renderer[rendererProp]; + const prevRenderer = renderer[rendererProp]; + // Replace renderer with func to run extension, but fall back if false + renderer[rendererProp] = (...args) => { + if (!pack.useNewRenderer) { + // TODO: Remove this in next major version + rendererFunc = this.#convertRendererFunction(rendererFunc, rendererProp, renderer); + } + let ret = rendererFunc.apply(renderer, args); + if (ret === false) { + ret = prevRenderer.apply(renderer, args); + } + return ret || ''; + }; + } + opts.renderer = renderer; + } + if (pack.tokenizer) { + const tokenizer = this.defaults.tokenizer || new _Tokenizer(this.defaults); + for (const prop in pack.tokenizer) { + if (!(prop in tokenizer)) { + throw new Error(`tokenizer '${prop}' does not exist`); + } + if (['options', 'rules', 'lexer'].includes(prop)) { + // ignore options, rules, and lexer properties + continue; + } + const tokenizerProp = prop; + const tokenizerFunc = pack.tokenizer[tokenizerProp]; + const prevTokenizer = tokenizer[tokenizerProp]; + // Replace tokenizer with func to run extension, but fall back if false + // @ts-expect-error cannot type tokenizer function dynamically + tokenizer[tokenizerProp] = (...args) => { + let ret = tokenizerFunc.apply(tokenizer, args); + if (ret === false) { + ret = prevTokenizer.apply(tokenizer, args); + } + return ret; + }; + } + opts.tokenizer = tokenizer; + } + // ==-- Parse Hooks extensions --== // + if (pack.hooks) { + const hooks = this.defaults.hooks || new _Hooks(); + for (const prop in pack.hooks) { + if (!(prop in hooks)) { + throw new Error(`hook '${prop}' does not exist`); + } + if (prop === 'options') { + // ignore options property + continue; + } + const hooksProp = prop; + const hooksFunc = pack.hooks[hooksProp]; + const prevHook = hooks[hooksProp]; + if (_Hooks.passThroughHooks.has(prop)) { + // @ts-expect-error cannot type hook function dynamically + hooks[hooksProp] = (arg) => { + if (this.defaults.async) { + return Promise.resolve(hooksFunc.call(hooks, arg)).then(ret => { + return prevHook.call(hooks, ret); + }); + } + const ret = hooksFunc.call(hooks, arg); + return prevHook.call(hooks, ret); + }; + } + else { + // @ts-expect-error cannot type hook function dynamically + hooks[hooksProp] = (...args) => { + let ret = hooksFunc.apply(hooks, args); + if (ret === false) { + ret = prevHook.apply(hooks, args); + } + return ret; + }; + } + } + opts.hooks = hooks; + } + // ==-- Parse WalkTokens extensions --== // + if (pack.walkTokens) { + const walkTokens = this.defaults.walkTokens; + const packWalktokens = pack.walkTokens; + opts.walkTokens = function (token) { + let values = []; + values.push(packWalktokens.call(this, token)); + if (walkTokens) { + values = values.concat(walkTokens.call(this, token)); + } + return values; + }; + } + this.defaults = { ...this.defaults, ...opts }; + }); + return this; + } + // TODO: Remove this in next major release + #convertRendererFunction(func, prop, renderer) { + switch (prop) { + case 'heading': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + return func.call(this, renderer.parser.parseInline(token.tokens), token.depth, unescape(renderer.parser.parseInline(token.tokens, renderer.parser.textRenderer))); + }; + case 'code': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + return func.call(this, token.text, token.lang, !!token.escaped); + }; + case 'table': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + let header = ''; + // header + let cell = ''; + for (let j = 0; j < token.header.length; j++) { + cell += this.tablecell({ + text: token.header[j].text, + tokens: token.header[j].tokens, + header: true, + align: token.align[j] + }); + } + header += this.tablerow({ text: cell }); + let body = ''; + for (let j = 0; j < token.rows.length; j++) { + const row = token.rows[j]; + cell = ''; + for (let k = 0; k < row.length; k++) { + cell += this.tablecell({ + text: row[k].text, + tokens: row[k].tokens, + header: false, + align: token.align[k] + }); + } + body += this.tablerow({ text: cell }); + } + return func.call(this, header, body); + }; + case 'blockquote': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + const body = this.parser.parse(token.tokens); + return func.call(this, body); + }; + case 'list': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + const ordered = token.ordered; + const start = token.start; + const loose = token.loose; + let body = ''; + for (let j = 0; j < token.items.length; j++) { + const item = token.items[j]; + const checked = item.checked; + const task = item.task; + let itemBody = ''; + if (item.task) { + const checkbox = this.checkbox({ checked: !!checked }); + if (loose) { + if (item.tokens.length > 0 && item.tokens[0].type === 'paragraph') { + item.tokens[0].text = checkbox + ' ' + item.tokens[0].text; + if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') { + item.tokens[0].tokens[0].text = checkbox + ' ' + item.tokens[0].tokens[0].text; + } + } + else { + item.tokens.unshift({ + type: 'text', + text: checkbox + ' ' + }); + } + } + else { + itemBody += checkbox + ' '; + } + } + itemBody += this.parser.parse(item.tokens, loose); + body += this.listitem({ + type: 'list_item', + raw: itemBody, + text: itemBody, + task, + checked: !!checked, + loose, + tokens: item.tokens + }); + } + return func.call(this, body, ordered, start); + }; + case 'html': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + return func.call(this, token.text, token.block); + }; + case 'paragraph': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + return func.call(this, this.parser.parseInline(token.tokens)); + }; + case 'escape': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + return func.call(this, token.text); + }; + case 'link': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + return func.call(this, token.href, token.title, this.parser.parseInline(token.tokens)); + }; + case 'image': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + return func.call(this, token.href, token.title, token.text); + }; + case 'strong': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + return func.call(this, this.parser.parseInline(token.tokens)); + }; + case 'em': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + return func.call(this, this.parser.parseInline(token.tokens)); + }; + case 'codespan': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + return func.call(this, token.text); + }; + case 'del': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + return func.call(this, this.parser.parseInline(token.tokens)); + }; + case 'text': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + return func.call(this, token.text); + }; + // do nothing + } + return func; + } + setOptions(opt) { + this.defaults = { ...this.defaults, ...opt }; + return this; + } + lexer(src, options) { + return _Lexer.lex(src, options ?? this.defaults); + } + parser(tokens, options) { + return _Parser.parse(tokens, options ?? this.defaults); + } + #parseMarkdown(lexer, parser) { + return (src, options) => { + const origOpt = { ...options }; + const opt = { ...this.defaults, ...origOpt }; + // Show warning if an extension set async to true but the parse was called with async: false + if (this.defaults.async === true && origOpt.async === false) { + if (!opt.silent) { + console.warn('marked(): The async option was set to true by an extension. The async: false option sent to parse will be ignored.'); + } + opt.async = true; + } + const throwError = this.#onError(!!opt.silent, !!opt.async); + // throw error in case of non string input + if (typeof src === 'undefined' || src === null) { + return throwError(new Error('marked(): input parameter is undefined or null')); + } + if (typeof src !== 'string') { + return throwError(new Error('marked(): input parameter is of type ' + + Object.prototype.toString.call(src) + ', string expected')); + } + if (opt.hooks) { + opt.hooks.options = opt; + } + if (opt.async) { + return Promise.resolve(opt.hooks ? opt.hooks.preprocess(src) : src) + .then(src => lexer(src, opt)) + .then(tokens => opt.hooks ? opt.hooks.processAllTokens(tokens) : tokens) + .then(tokens => opt.walkTokens ? Promise.all(this.walkTokens(tokens, opt.walkTokens)).then(() => tokens) : tokens) + .then(tokens => parser(tokens, opt)) + .then(html => opt.hooks ? opt.hooks.postprocess(html) : html) + .catch(throwError); + } + try { + if (opt.hooks) { + src = opt.hooks.preprocess(src); + } + let tokens = lexer(src, opt); + if (opt.hooks) { + tokens = opt.hooks.processAllTokens(tokens); + } + if (opt.walkTokens) { + this.walkTokens(tokens, opt.walkTokens); + } + let html = parser(tokens, opt); + if (opt.hooks) { + html = opt.hooks.postprocess(html); + } + return html; + } + catch (e) { + return throwError(e); + } + }; + } + #onError(silent, async) { + return (e) => { + e.message += '\nPlease report this to https://github.com/markedjs/marked.'; + if (silent) { + const msg = '

    An error occurred:

    '
    +                    + escape$1(e.message + '', true)
    +                    + '
    '; + if (async) { + return Promise.resolve(msg); + } + return msg; + } + if (async) { + return Promise.reject(e); + } + throw e; + }; + } +} + +const markedInstance = new Marked(); +function marked(src, opt) { + return markedInstance.parse(src, opt); +} +/** + * Sets the default options. + * + * @param options Hash of options + */ +marked.options = + marked.setOptions = function (options) { + markedInstance.setOptions(options); + marked.defaults = markedInstance.defaults; + changeDefaults(marked.defaults); + return marked; + }; +/** + * Gets the original marked default options. + */ +marked.getDefaults = _getDefaults; +marked.defaults = _defaults; +/** + * Use Extension + */ +marked.use = function (...args) { + markedInstance.use(...args); + marked.defaults = markedInstance.defaults; + changeDefaults(marked.defaults); + return marked; +}; +/** + * Run callback for every token + */ +marked.walkTokens = function (tokens, callback) { + return markedInstance.walkTokens(tokens, callback); +}; +/** + * Compiles markdown to HTML without enclosing `p` tag. + * + * @param src String of markdown source to be compiled + * @param options Hash of options + * @return String of compiled HTML + */ +marked.parseInline = markedInstance.parseInline; +/** + * Expose + */ +marked.Parser = _Parser; +marked.parser = _Parser.parse; +marked.Renderer = _Renderer; +marked.TextRenderer = _TextRenderer; +marked.Lexer = _Lexer; +marked.lexer = _Lexer.lex; +marked.Tokenizer = _Tokenizer; +marked.Hooks = _Hooks; +marked.parse = marked; +const options = marked.options; +const setOptions = marked.setOptions; +const use = marked.use; +const walkTokens = marked.walkTokens; +const parseInline = marked.parseInline; +const parse = marked; +const parser = _Parser.parse; +const lexer = _Lexer.lex; + +export { _Hooks as Hooks, _Lexer as Lexer, Marked, _Parser as Parser, _Renderer as Renderer, _TextRenderer as TextRenderer, _Tokenizer as Tokenizer, _defaults as defaults, _getDefaults as getDefaults, lexer, marked, options, parse, parseInline, parser, setOptions, use, walkTokens }; +//# sourceMappingURL=marked.esm.js.map diff --git a/scripts/node_modules/marked/lib/marked.esm.js.map b/scripts/node_modules/marked/lib/marked.esm.js.map new file mode 100644 index 000000000..29cb5cfb0 --- /dev/null +++ b/scripts/node_modules/marked/lib/marked.esm.js.map @@ -0,0 +1 @@ +{"version":3,"file":"marked.esm.js","sources":["../src/defaults.ts","../src/helpers.ts","../src/Tokenizer.ts","../src/rules.ts","../src/Lexer.ts","../src/Renderer.ts","../src/TextRenderer.ts","../src/Parser.ts","../src/Hooks.ts","../src/Instance.ts","../src/marked.ts"],"sourcesContent":["/**\n * Gets the original marked default options.\n */\nexport function _getDefaults() {\n return {\n async: false,\n breaks: false,\n extensions: null,\n gfm: true,\n hooks: null,\n pedantic: false,\n renderer: null,\n silent: false,\n tokenizer: null,\n walkTokens: null\n };\n}\nexport let _defaults = _getDefaults();\nexport function changeDefaults(newDefaults) {\n _defaults = newDefaults;\n}\n","/**\n * Helpers\n */\nconst escapeTest = /[&<>\"']/;\nconst escapeReplace = new RegExp(escapeTest.source, 'g');\nconst escapeTestNoEncode = /[<>\"']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/;\nconst escapeReplaceNoEncode = new RegExp(escapeTestNoEncode.source, 'g');\nconst escapeReplacements = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": '''\n};\nconst getEscapeReplacement = (ch) => escapeReplacements[ch];\nexport function escape(html, encode) {\n if (encode) {\n if (escapeTest.test(html)) {\n return html.replace(escapeReplace, getEscapeReplacement);\n }\n }\n else {\n if (escapeTestNoEncode.test(html)) {\n return html.replace(escapeReplaceNoEncode, getEscapeReplacement);\n }\n }\n return html;\n}\nconst unescapeTest = /&(#(?:\\d+)|(?:#x[0-9A-Fa-f]+)|(?:\\w+));?/ig;\nexport function unescape(html) {\n // explicitly match decimal, hex, and named HTML entities\n return html.replace(unescapeTest, (_, n) => {\n n = n.toLowerCase();\n if (n === 'colon')\n return ':';\n if (n.charAt(0) === '#') {\n return n.charAt(1) === 'x'\n ? String.fromCharCode(parseInt(n.substring(2), 16))\n : String.fromCharCode(+n.substring(1));\n }\n return '';\n });\n}\nconst caret = /(^|[^\\[])\\^/g;\nexport function edit(regex, opt) {\n let source = typeof regex === 'string' ? regex : regex.source;\n opt = opt || '';\n const obj = {\n replace: (name, val) => {\n let valSource = typeof val === 'string' ? val : val.source;\n valSource = valSource.replace(caret, '$1');\n source = source.replace(name, valSource);\n return obj;\n },\n getRegex: () => {\n return new RegExp(source, opt);\n }\n };\n return obj;\n}\nexport function cleanUrl(href) {\n try {\n href = encodeURI(href).replace(/%25/g, '%');\n }\n catch (e) {\n return null;\n }\n return href;\n}\nexport const noopTest = { exec: () => null };\nexport function splitCells(tableRow, count) {\n // ensure that every cell-delimiting pipe has a space\n // before it to distinguish it from an escaped pipe\n const row = tableRow.replace(/\\|/g, (match, offset, str) => {\n let escaped = false;\n let curr = offset;\n while (--curr >= 0 && str[curr] === '\\\\')\n escaped = !escaped;\n if (escaped) {\n // odd number of slashes means | is escaped\n // so we leave it alone\n return '|';\n }\n else {\n // add space before unescaped |\n return ' |';\n }\n }), cells = row.split(/ \\|/);\n let i = 0;\n // First/last cell in a row cannot be empty if it has no leading/trailing pipe\n if (!cells[0].trim()) {\n cells.shift();\n }\n if (cells.length > 0 && !cells[cells.length - 1].trim()) {\n cells.pop();\n }\n if (count) {\n if (cells.length > count) {\n cells.splice(count);\n }\n else {\n while (cells.length < count)\n cells.push('');\n }\n }\n for (; i < cells.length; i++) {\n // leading or trailing whitespace is ignored per the gfm spec\n cells[i] = cells[i].trim().replace(/\\\\\\|/g, '|');\n }\n return cells;\n}\n/**\n * Remove trailing 'c's. Equivalent to str.replace(/c*$/, '').\n * /c*$/ is vulnerable to REDOS.\n *\n * @param str\n * @param c\n * @param invert Remove suffix of non-c chars instead. Default falsey.\n */\nexport function rtrim(str, c, invert) {\n const l = str.length;\n if (l === 0) {\n return '';\n }\n // Length of suffix matching the invert condition.\n let suffLen = 0;\n // Step left until we fail to match the invert condition.\n while (suffLen < l) {\n const currChar = str.charAt(l - suffLen - 1);\n if (currChar === c && !invert) {\n suffLen++;\n }\n else if (currChar !== c && invert) {\n suffLen++;\n }\n else {\n break;\n }\n }\n return str.slice(0, l - suffLen);\n}\nexport function findClosingBracket(str, b) {\n if (str.indexOf(b[1]) === -1) {\n return -1;\n }\n let level = 0;\n for (let i = 0; i < str.length; i++) {\n if (str[i] === '\\\\') {\n i++;\n }\n else if (str[i] === b[0]) {\n level++;\n }\n else if (str[i] === b[1]) {\n level--;\n if (level < 0) {\n return i;\n }\n }\n }\n return -1;\n}\n","import { _defaults } from './defaults.ts';\nimport { rtrim, splitCells, escape, findClosingBracket } from './helpers.ts';\nfunction outputLink(cap, link, raw, lexer) {\n const href = link.href;\n const title = link.title ? escape(link.title) : null;\n const text = cap[1].replace(/\\\\([\\[\\]])/g, '$1');\n if (cap[0].charAt(0) !== '!') {\n lexer.state.inLink = true;\n const token = {\n type: 'link',\n raw,\n href,\n title,\n text,\n tokens: lexer.inlineTokens(text)\n };\n lexer.state.inLink = false;\n return token;\n }\n return {\n type: 'image',\n raw,\n href,\n title,\n text: escape(text)\n };\n}\nfunction indentCodeCompensation(raw, text) {\n const matchIndentToCode = raw.match(/^(\\s+)(?:```)/);\n if (matchIndentToCode === null) {\n return text;\n }\n const indentToCode = matchIndentToCode[1];\n return text\n .split('\\n')\n .map(node => {\n const matchIndentInNode = node.match(/^\\s+/);\n if (matchIndentInNode === null) {\n return node;\n }\n const [indentInNode] = matchIndentInNode;\n if (indentInNode.length >= indentToCode.length) {\n return node.slice(indentToCode.length);\n }\n return node;\n })\n .join('\\n');\n}\n/**\n * Tokenizer\n */\nexport class _Tokenizer {\n options;\n rules; // set by the lexer\n lexer; // set by the lexer\n constructor(options) {\n this.options = options || _defaults;\n }\n space(src) {\n const cap = this.rules.block.newline.exec(src);\n if (cap && cap[0].length > 0) {\n return {\n type: 'space',\n raw: cap[0]\n };\n }\n }\n code(src) {\n const cap = this.rules.block.code.exec(src);\n if (cap) {\n const text = cap[0].replace(/^ {1,4}/gm, '');\n return {\n type: 'code',\n raw: cap[0],\n codeBlockStyle: 'indented',\n text: !this.options.pedantic\n ? rtrim(text, '\\n')\n : text\n };\n }\n }\n fences(src) {\n const cap = this.rules.block.fences.exec(src);\n if (cap) {\n const raw = cap[0];\n const text = indentCodeCompensation(raw, cap[3] || '');\n return {\n type: 'code',\n raw,\n lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, '$1') : cap[2],\n text\n };\n }\n }\n heading(src) {\n const cap = this.rules.block.heading.exec(src);\n if (cap) {\n let text = cap[2].trim();\n // remove trailing #s\n if (/#$/.test(text)) {\n const trimmed = rtrim(text, '#');\n if (this.options.pedantic) {\n text = trimmed.trim();\n }\n else if (!trimmed || / $/.test(trimmed)) {\n // CommonMark requires space before trailing #s\n text = trimmed.trim();\n }\n }\n return {\n type: 'heading',\n raw: cap[0],\n depth: cap[1].length,\n text,\n tokens: this.lexer.inline(text)\n };\n }\n }\n hr(src) {\n const cap = this.rules.block.hr.exec(src);\n if (cap) {\n return {\n type: 'hr',\n raw: rtrim(cap[0], '\\n')\n };\n }\n }\n blockquote(src) {\n const cap = this.rules.block.blockquote.exec(src);\n if (cap) {\n let lines = rtrim(cap[0], '\\n').split('\\n');\n let raw = '';\n let text = '';\n const tokens = [];\n while (lines.length > 0) {\n let inBlockquote = false;\n const currentLines = [];\n let i;\n for (i = 0; i < lines.length; i++) {\n // get lines up to a continuation\n if (/^ {0,3}>/.test(lines[i])) {\n currentLines.push(lines[i]);\n inBlockquote = true;\n }\n else if (!inBlockquote) {\n currentLines.push(lines[i]);\n }\n else {\n break;\n }\n }\n lines = lines.slice(i);\n const currentRaw = currentLines.join('\\n');\n const currentText = currentRaw\n // precede setext continuation with 4 spaces so it isn't a setext\n .replace(/\\n {0,3}((?:=+|-+) *)(?=\\n|$)/g, '\\n $1')\n .replace(/^ {0,3}>[ \\t]?/gm, '');\n raw = raw ? `${raw}\\n${currentRaw}` : currentRaw;\n text = text ? `${text}\\n${currentText}` : currentText;\n // parse blockquote lines as top level tokens\n // merge paragraphs if this is a continuation\n const top = this.lexer.state.top;\n this.lexer.state.top = true;\n this.lexer.blockTokens(currentText, tokens, true);\n this.lexer.state.top = top;\n // if there is no continuation then we are done\n if (lines.length === 0) {\n break;\n }\n const lastToken = tokens[tokens.length - 1];\n if (lastToken?.type === 'code') {\n // blockquote continuation cannot be preceded by a code block\n break;\n }\n else if (lastToken?.type === 'blockquote') {\n // include continuation in nested blockquote\n const oldToken = lastToken;\n const newText = oldToken.raw + '\\n' + lines.join('\\n');\n const newToken = this.blockquote(newText);\n tokens[tokens.length - 1] = newToken;\n raw = raw.substring(0, raw.length - oldToken.raw.length) + newToken.raw;\n text = text.substring(0, text.length - oldToken.text.length) + newToken.text;\n break;\n }\n else if (lastToken?.type === 'list') {\n // include continuation in nested list\n const oldToken = lastToken;\n const newText = oldToken.raw + '\\n' + lines.join('\\n');\n const newToken = this.list(newText);\n tokens[tokens.length - 1] = newToken;\n raw = raw.substring(0, raw.length - lastToken.raw.length) + newToken.raw;\n text = text.substring(0, text.length - oldToken.raw.length) + newToken.raw;\n lines = newText.substring(tokens[tokens.length - 1].raw.length).split('\\n');\n continue;\n }\n }\n return {\n type: 'blockquote',\n raw,\n tokens,\n text\n };\n }\n }\n list(src) {\n let cap = this.rules.block.list.exec(src);\n if (cap) {\n let bull = cap[1].trim();\n const isordered = bull.length > 1;\n const list = {\n type: 'list',\n raw: '',\n ordered: isordered,\n start: isordered ? +bull.slice(0, -1) : '',\n loose: false,\n items: []\n };\n bull = isordered ? `\\\\d{1,9}\\\\${bull.slice(-1)}` : `\\\\${bull}`;\n if (this.options.pedantic) {\n bull = isordered ? bull : '[*+-]';\n }\n // Get next list item\n const itemRegex = new RegExp(`^( {0,3}${bull})((?:[\\t ][^\\\\n]*)?(?:\\\\n|$))`);\n let raw = '';\n let itemContents = '';\n let endsWithBlankLine = false;\n // Check if current bullet point can start a new List Item\n while (src) {\n let endEarly = false;\n if (!(cap = itemRegex.exec(src))) {\n break;\n }\n if (this.rules.block.hr.test(src)) { // End list if bullet was actually HR (possibly move into itemRegex?)\n break;\n }\n raw = cap[0];\n src = src.substring(raw.length);\n let line = cap[2].split('\\n', 1)[0].replace(/^\\t+/, (t) => ' '.repeat(3 * t.length));\n let nextLine = src.split('\\n', 1)[0];\n let indent = 0;\n if (this.options.pedantic) {\n indent = 2;\n itemContents = line.trimStart();\n }\n else {\n indent = cap[2].search(/[^ ]/); // Find first non-space char\n indent = indent > 4 ? 1 : indent; // Treat indented code blocks (> 4 spaces) as having only 1 indent\n itemContents = line.slice(indent);\n indent += cap[1].length;\n }\n let blankLine = false;\n if (!line && /^ *$/.test(nextLine)) { // Items begin with at most one blank line\n raw += nextLine + '\\n';\n src = src.substring(nextLine.length + 1);\n endEarly = true;\n }\n if (!endEarly) {\n const nextBulletRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\\\d{1,9}[.)])((?:[ \\t][^\\\\n]*)?(?:\\\\n|$))`);\n const hrRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\\\* *){3,})(?:\\\\n+|$)`);\n const fencesBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\\`\\`\\`|~~~)`);\n const headingBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`);\n // Check if following lines should be included in List Item\n while (src) {\n const rawLine = src.split('\\n', 1)[0];\n nextLine = rawLine;\n // Re-align to follow commonmark nesting rules\n if (this.options.pedantic) {\n nextLine = nextLine.replace(/^ {1,4}(?=( {4})*[^ ])/g, ' ');\n }\n // End list item if found code fences\n if (fencesBeginRegex.test(nextLine)) {\n break;\n }\n // End list item if found start of new heading\n if (headingBeginRegex.test(nextLine)) {\n break;\n }\n // End list item if found start of new bullet\n if (nextBulletRegex.test(nextLine)) {\n break;\n }\n // Horizontal rule found\n if (hrRegex.test(src)) {\n break;\n }\n if (nextLine.search(/[^ ]/) >= indent || !nextLine.trim()) { // Dedent if possible\n itemContents += '\\n' + nextLine.slice(indent);\n }\n else {\n // not enough indentation\n if (blankLine) {\n break;\n }\n // paragraph continuation unless last line was a different block level element\n if (line.search(/[^ ]/) >= 4) { // indented code block\n break;\n }\n if (fencesBeginRegex.test(line)) {\n break;\n }\n if (headingBeginRegex.test(line)) {\n break;\n }\n if (hrRegex.test(line)) {\n break;\n }\n itemContents += '\\n' + nextLine;\n }\n if (!blankLine && !nextLine.trim()) { // Check if current line is blank\n blankLine = true;\n }\n raw += rawLine + '\\n';\n src = src.substring(rawLine.length + 1);\n line = nextLine.slice(indent);\n }\n }\n if (!list.loose) {\n // If the previous item ended with a blank line, the list is loose\n if (endsWithBlankLine) {\n list.loose = true;\n }\n else if (/\\n *\\n *$/.test(raw)) {\n endsWithBlankLine = true;\n }\n }\n let istask = null;\n let ischecked;\n // Check for task list items\n if (this.options.gfm) {\n istask = /^\\[[ xX]\\] /.exec(itemContents);\n if (istask) {\n ischecked = istask[0] !== '[ ] ';\n itemContents = itemContents.replace(/^\\[[ xX]\\] +/, '');\n }\n }\n list.items.push({\n type: 'list_item',\n raw,\n task: !!istask,\n checked: ischecked,\n loose: false,\n text: itemContents,\n tokens: []\n });\n list.raw += raw;\n }\n // Do not consume newlines at end of final item. Alternatively, make itemRegex *start* with any newlines to simplify/speed up endsWithBlankLine logic\n list.items[list.items.length - 1].raw = raw.trimEnd();\n (list.items[list.items.length - 1]).text = itemContents.trimEnd();\n list.raw = list.raw.trimEnd();\n // Item child tokens handled here at end because we needed to have the final item to trim it first\n for (let i = 0; i < list.items.length; i++) {\n this.lexer.state.top = false;\n list.items[i].tokens = this.lexer.blockTokens(list.items[i].text, []);\n if (!list.loose) {\n // Check if list should be loose\n const spacers = list.items[i].tokens.filter(t => t.type === 'space');\n const hasMultipleLineBreaks = spacers.length > 0 && spacers.some(t => /\\n.*\\n/.test(t.raw));\n list.loose = hasMultipleLineBreaks;\n }\n }\n // Set all items to loose if list is loose\n if (list.loose) {\n for (let i = 0; i < list.items.length; i++) {\n list.items[i].loose = true;\n }\n }\n return list;\n }\n }\n html(src) {\n const cap = this.rules.block.html.exec(src);\n if (cap) {\n const token = {\n type: 'html',\n block: true,\n raw: cap[0],\n pre: cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style',\n text: cap[0]\n };\n return token;\n }\n }\n def(src) {\n const cap = this.rules.block.def.exec(src);\n if (cap) {\n const tag = cap[1].toLowerCase().replace(/\\s+/g, ' ');\n const href = cap[2] ? cap[2].replace(/^<(.*)>$/, '$1').replace(this.rules.inline.anyPunctuation, '$1') : '';\n const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, '$1') : cap[3];\n return {\n type: 'def',\n tag,\n raw: cap[0],\n href,\n title\n };\n }\n }\n table(src) {\n const cap = this.rules.block.table.exec(src);\n if (!cap) {\n return;\n }\n if (!/[:|]/.test(cap[2])) {\n // delimiter row must have a pipe (|) or colon (:) otherwise it is a setext heading\n return;\n }\n const headers = splitCells(cap[1]);\n const aligns = cap[2].replace(/^\\||\\| *$/g, '').split('|');\n const rows = cap[3] && cap[3].trim() ? cap[3].replace(/\\n[ \\t]*$/, '').split('\\n') : [];\n const item = {\n type: 'table',\n raw: cap[0],\n header: [],\n align: [],\n rows: []\n };\n if (headers.length !== aligns.length) {\n // header and align columns must be equal, rows can be different.\n return;\n }\n for (const align of aligns) {\n if (/^ *-+: *$/.test(align)) {\n item.align.push('right');\n }\n else if (/^ *:-+: *$/.test(align)) {\n item.align.push('center');\n }\n else if (/^ *:-+ *$/.test(align)) {\n item.align.push('left');\n }\n else {\n item.align.push(null);\n }\n }\n for (let i = 0; i < headers.length; i++) {\n item.header.push({\n text: headers[i],\n tokens: this.lexer.inline(headers[i]),\n header: true,\n align: item.align[i]\n });\n }\n for (const row of rows) {\n item.rows.push(splitCells(row, item.header.length).map((cell, i) => {\n return {\n text: cell,\n tokens: this.lexer.inline(cell),\n header: false,\n align: item.align[i]\n };\n }));\n }\n return item;\n }\n lheading(src) {\n const cap = this.rules.block.lheading.exec(src);\n if (cap) {\n return {\n type: 'heading',\n raw: cap[0],\n depth: cap[2].charAt(0) === '=' ? 1 : 2,\n text: cap[1],\n tokens: this.lexer.inline(cap[1])\n };\n }\n }\n paragraph(src) {\n const cap = this.rules.block.paragraph.exec(src);\n if (cap) {\n const text = cap[1].charAt(cap[1].length - 1) === '\\n'\n ? cap[1].slice(0, -1)\n : cap[1];\n return {\n type: 'paragraph',\n raw: cap[0],\n text,\n tokens: this.lexer.inline(text)\n };\n }\n }\n text(src) {\n const cap = this.rules.block.text.exec(src);\n if (cap) {\n return {\n type: 'text',\n raw: cap[0],\n text: cap[0],\n tokens: this.lexer.inline(cap[0])\n };\n }\n }\n escape(src) {\n const cap = this.rules.inline.escape.exec(src);\n if (cap) {\n return {\n type: 'escape',\n raw: cap[0],\n text: escape(cap[1])\n };\n }\n }\n tag(src) {\n const cap = this.rules.inline.tag.exec(src);\n if (cap) {\n if (!this.lexer.state.inLink && /^
    /i.test(cap[0])) {\n this.lexer.state.inLink = false;\n }\n if (!this.lexer.state.inRawBlock && /^<(pre|code|kbd|script)(\\s|>)/i.test(cap[0])) {\n this.lexer.state.inRawBlock = true;\n }\n else if (this.lexer.state.inRawBlock && /^<\\/(pre|code|kbd|script)(\\s|>)/i.test(cap[0])) {\n this.lexer.state.inRawBlock = false;\n }\n return {\n type: 'html',\n raw: cap[0],\n inLink: this.lexer.state.inLink,\n inRawBlock: this.lexer.state.inRawBlock,\n block: false,\n text: cap[0]\n };\n }\n }\n link(src) {\n const cap = this.rules.inline.link.exec(src);\n if (cap) {\n const trimmedUrl = cap[2].trim();\n if (!this.options.pedantic && /^$/.test(trimmedUrl))) {\n return;\n }\n // ending angle bracket cannot be escaped\n const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), '\\\\');\n if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) {\n return;\n }\n }\n else {\n // find closing parenthesis\n const lastParenIndex = findClosingBracket(cap[2], '()');\n if (lastParenIndex > -1) {\n const start = cap[0].indexOf('!') === 0 ? 5 : 4;\n const linkLen = start + cap[1].length + lastParenIndex;\n cap[2] = cap[2].substring(0, lastParenIndex);\n cap[0] = cap[0].substring(0, linkLen).trim();\n cap[3] = '';\n }\n }\n let href = cap[2];\n let title = '';\n if (this.options.pedantic) {\n // split pedantic href and title\n const link = /^([^'\"]*[^\\s])\\s+(['\"])(.*)\\2/.exec(href);\n if (link) {\n href = link[1];\n title = link[3];\n }\n }\n else {\n title = cap[3] ? cap[3].slice(1, -1) : '';\n }\n href = href.trim();\n if (/^$/.test(trimmedUrl))) {\n // pedantic allows starting angle bracket without ending angle bracket\n href = href.slice(1);\n }\n else {\n href = href.slice(1, -1);\n }\n }\n return outputLink(cap, {\n href: href ? href.replace(this.rules.inline.anyPunctuation, '$1') : href,\n title: title ? title.replace(this.rules.inline.anyPunctuation, '$1') : title\n }, cap[0], this.lexer);\n }\n }\n reflink(src, links) {\n let cap;\n if ((cap = this.rules.inline.reflink.exec(src))\n || (cap = this.rules.inline.nolink.exec(src))) {\n const linkString = (cap[2] || cap[1]).replace(/\\s+/g, ' ');\n const link = links[linkString.toLowerCase()];\n if (!link) {\n const text = cap[0].charAt(0);\n return {\n type: 'text',\n raw: text,\n text\n };\n }\n return outputLink(cap, link, cap[0], this.lexer);\n }\n }\n emStrong(src, maskedSrc, prevChar = '') {\n let match = this.rules.inline.emStrongLDelim.exec(src);\n if (!match)\n return;\n // _ can't be between two alphanumerics. \\p{L}\\p{N} includes non-english alphabet/numbers as well\n if (match[3] && prevChar.match(/[\\p{L}\\p{N}]/u))\n return;\n const nextChar = match[1] || match[2] || '';\n if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) {\n // unicode Regex counts emoji as 1 char; spread into array for proper count (used multiple times below)\n const lLength = [...match[0]].length - 1;\n let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0;\n const endReg = match[0][0] === '*' ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;\n endReg.lastIndex = 0;\n // Clip maskedSrc to same section of string as src (move to lexer?)\n maskedSrc = maskedSrc.slice(-1 * src.length + lLength);\n while ((match = endReg.exec(maskedSrc)) != null) {\n rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6];\n if (!rDelim)\n continue; // skip single * in __abc*abc__\n rLength = [...rDelim].length;\n if (match[3] || match[4]) { // found another Left Delim\n delimTotal += rLength;\n continue;\n }\n else if (match[5] || match[6]) { // either Left or Right Delim\n if (lLength % 3 && !((lLength + rLength) % 3)) {\n midDelimTotal += rLength;\n continue; // CommonMark Emphasis Rules 9-10\n }\n }\n delimTotal -= rLength;\n if (delimTotal > 0)\n continue; // Haven't found enough closing delimiters\n // Remove extra characters. *a*** -> *a*\n rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal);\n // char length can be >1 for unicode characters;\n const lastCharLength = [...match[0]][0].length;\n const raw = src.slice(0, lLength + match.index + lastCharLength + rLength);\n // Create `em` if smallest delimiter has odd char count. *a***\n if (Math.min(lLength, rLength) % 2) {\n const text = raw.slice(1, -1);\n return {\n type: 'em',\n raw,\n text,\n tokens: this.lexer.inlineTokens(text)\n };\n }\n // Create 'strong' if smallest delimiter has even char count. **a***\n const text = raw.slice(2, -2);\n return {\n type: 'strong',\n raw,\n text,\n tokens: this.lexer.inlineTokens(text)\n };\n }\n }\n }\n codespan(src) {\n const cap = this.rules.inline.code.exec(src);\n if (cap) {\n let text = cap[2].replace(/\\n/g, ' ');\n const hasNonSpaceChars = /[^ ]/.test(text);\n const hasSpaceCharsOnBothEnds = /^ /.test(text) && / $/.test(text);\n if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {\n text = text.substring(1, text.length - 1);\n }\n text = escape(text, true);\n return {\n type: 'codespan',\n raw: cap[0],\n text\n };\n }\n }\n br(src) {\n const cap = this.rules.inline.br.exec(src);\n if (cap) {\n return {\n type: 'br',\n raw: cap[0]\n };\n }\n }\n del(src) {\n const cap = this.rules.inline.del.exec(src);\n if (cap) {\n return {\n type: 'del',\n raw: cap[0],\n text: cap[2],\n tokens: this.lexer.inlineTokens(cap[2])\n };\n }\n }\n autolink(src) {\n const cap = this.rules.inline.autolink.exec(src);\n if (cap) {\n let text, href;\n if (cap[2] === '@') {\n text = escape(cap[1]);\n href = 'mailto:' + text;\n }\n else {\n text = escape(cap[1]);\n href = text;\n }\n return {\n type: 'link',\n raw: cap[0],\n text,\n href,\n tokens: [\n {\n type: 'text',\n raw: text,\n text\n }\n ]\n };\n }\n }\n url(src) {\n let cap;\n if (cap = this.rules.inline.url.exec(src)) {\n let text, href;\n if (cap[2] === '@') {\n text = escape(cap[0]);\n href = 'mailto:' + text;\n }\n else {\n // do extended autolink path validation\n let prevCapZero;\n do {\n prevCapZero = cap[0];\n cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? '';\n } while (prevCapZero !== cap[0]);\n text = escape(cap[0]);\n if (cap[1] === 'www.') {\n href = 'http://' + cap[0];\n }\n else {\n href = cap[0];\n }\n }\n return {\n type: 'link',\n raw: cap[0],\n text,\n href,\n tokens: [\n {\n type: 'text',\n raw: text,\n text\n }\n ]\n };\n }\n }\n inlineText(src) {\n const cap = this.rules.inline.text.exec(src);\n if (cap) {\n let text;\n if (this.lexer.state.inRawBlock) {\n text = cap[0];\n }\n else {\n text = escape(cap[0]);\n }\n return {\n type: 'text',\n raw: cap[0],\n text\n };\n }\n }\n}\n","import { edit, noopTest } from './helpers.ts';\n/**\n * Block-Level Grammar\n */\nconst newline = /^(?: *(?:\\n|$))+/;\nconst blockCode = /^( {4}[^\\n]+(?:\\n(?: *(?:\\n|$))*)?)+/;\nconst fences = /^ {0,3}(`{3,}(?=[^`\\n]*(?:\\n|$))|~{3,})([^\\n]*)(?:\\n|$)(?:|([\\s\\S]*?)(?:\\n|$))(?: {0,3}\\1[~`]* *(?=\\n|$)|$)/;\nconst hr = /^ {0,3}((?:-[\\t ]*){3,}|(?:_[ \\t]*){3,}|(?:\\*[ \\t]*){3,})(?:\\n+|$)/;\nconst heading = /^ {0,3}(#{1,6})(?=\\s|$)(.*)(?:\\n+|$)/;\nconst bullet = /(?:[*+-]|\\d{1,9}[.)])/;\nconst lheading = edit(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\\n(?!\\s*?\\n|bull |blockCode|fences|blockquote|heading|html))+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/)\n .replace(/bull/g, bullet) // lists can interrupt\n .replace(/blockCode/g, / {4}/) // indented code blocks can interrupt\n .replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/) // fenced code blocks can interrupt\n .replace(/blockquote/g, / {0,3}>/) // blockquote can interrupt\n .replace(/heading/g, / {0,3}#{1,6}/) // ATX heading can interrupt\n .replace(/html/g, / {0,3}<[^\\n>]+>\\n/) // block html can interrupt\n .getRegex();\nconst _paragraph = /^([^\\n]+(?:\\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\\n)[^\\n]+)*)/;\nconst blockText = /^[^\\n]+/;\nconst _blockLabel = /(?!\\s*\\])(?:\\\\.|[^\\[\\]\\\\])+/;\nconst def = edit(/^ {0,3}\\[(label)\\]: *(?:\\n *)?([^<\\s][^\\s]*|<.*?>)(?:(?: +(?:\\n *)?| *\\n *)(title))? *(?:\\n+|$)/)\n .replace('label', _blockLabel)\n .replace('title', /(?:\"(?:\\\\\"?|[^\"\\\\])*\"|'[^'\\n]*(?:\\n[^'\\n]+)*\\n?'|\\([^()]*\\))/)\n .getRegex();\nconst list = edit(/^( {0,3}bull)([ \\t][^\\n]+?)?(?:\\n|$)/)\n .replace(/bull/g, bullet)\n .getRegex();\nconst _tag = 'address|article|aside|base|basefont|blockquote|body|caption'\n + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption'\n + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe'\n + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option'\n + '|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title'\n + '|tr|track|ul';\nconst _comment = /|$))/;\nconst html = edit('^ {0,3}(?:' // optional indentation\n + '<(script|pre|style|textarea)[\\\\s>][\\\\s\\\\S]*?(?:[^\\\\n]*\\\\n+|$)' // (1)\n + '|comment[^\\\\n]*(\\\\n+|$)' // (2)\n + '|<\\\\?[\\\\s\\\\S]*?(?:\\\\?>\\\\n*|$)' // (3)\n + '|\\\\n*|$)' // (4)\n + '|\\\\n*|$)' // (5)\n + '|)[\\\\s\\\\S]*?(?:(?:\\\\n *)+\\\\n|$)' // (6)\n + '|<(?!script|pre|style|textarea)([a-z][\\\\w-]*)(?:attribute)*? */?>(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n *)+\\\\n|$)' // (7) open tag\n + '|(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n *)+\\\\n|$)' // (7) closing tag\n + ')', 'i')\n .replace('comment', _comment)\n .replace('tag', _tag)\n .replace('attribute', / +[a-zA-Z:_][\\w.:-]*(?: *= *\"[^\"\\n]*\"| *= *'[^'\\n]*'| *= *[^\\s\"'=<>`]+)?/)\n .getRegex();\nconst paragraph = edit(_paragraph)\n .replace('hr', hr)\n .replace('heading', ' {0,3}#{1,6}(?:\\\\s|$)')\n .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs\n .replace('|table', '')\n .replace('blockquote', ' {0,3}>')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n')\n .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt\n .replace('html', ')|<(?:script|pre|style|textarea|!--)')\n .replace('tag', _tag) // pars can be interrupted by type (6) html blocks\n .getRegex();\nconst blockquote = edit(/^( {0,3}> ?(paragraph|[^\\n]*)(?:\\n|$))+/)\n .replace('paragraph', paragraph)\n .getRegex();\n/**\n * Normal Block Grammar\n */\nconst blockNormal = {\n blockquote,\n code: blockCode,\n def,\n fences,\n heading,\n hr,\n html,\n lheading,\n list,\n newline,\n paragraph,\n table: noopTest,\n text: blockText\n};\n/**\n * GFM Block Grammar\n */\nconst gfmTable = edit('^ *([^\\\\n ].*)\\\\n' // Header\n + ' {0,3}((?:\\\\| *)?:?-+:? *(?:\\\\| *:?-+:? *)*(?:\\\\| *)?)' // Align\n + '(?:\\\\n((?:(?! *\\\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\\\n|$))*)\\\\n*|$)') // Cells\n .replace('hr', hr)\n .replace('heading', ' {0,3}#{1,6}(?:\\\\s|$)')\n .replace('blockquote', ' {0,3}>')\n .replace('code', ' {4}[^\\\\n]')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n')\n .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt\n .replace('html', ')|<(?:script|pre|style|textarea|!--)')\n .replace('tag', _tag) // tables can be interrupted by type (6) html blocks\n .getRegex();\nconst blockGfm = {\n ...blockNormal,\n table: gfmTable,\n paragraph: edit(_paragraph)\n .replace('hr', hr)\n .replace('heading', ' {0,3}#{1,6}(?:\\\\s|$)')\n .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs\n .replace('table', gfmTable) // interrupt paragraphs with table\n .replace('blockquote', ' {0,3}>')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n')\n .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt\n .replace('html', ')|<(?:script|pre|style|textarea|!--)')\n .replace('tag', _tag) // pars can be interrupted by type (6) html blocks\n .getRegex()\n};\n/**\n * Pedantic grammar (original John Gruber's loose markdown specification)\n */\nconst blockPedantic = {\n ...blockNormal,\n html: edit('^ *(?:comment *(?:\\\\n|\\\\s*$)'\n + '|<(tag)[\\\\s\\\\S]+? *(?:\\\\n{2,}|\\\\s*$)' // closed tag\n + '|\\\\s]*)*?/?> *(?:\\\\n{2,}|\\\\s*$))')\n .replace('comment', _comment)\n .replace(/tag/g, '(?!(?:'\n + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub'\n + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)'\n + '\\\\b)\\\\w+(?!:|[^\\\\w\\\\s@]*@)\\\\b')\n .getRegex(),\n def: /^ *\\[([^\\]]+)\\]: *]+)>?(?: +([\"(][^\\n]+[\")]))? *(?:\\n+|$)/,\n heading: /^(#{1,6})(.*)(?:\\n+|$)/,\n fences: noopTest, // fences not supported\n lheading: /^(.+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/,\n paragraph: edit(_paragraph)\n .replace('hr', hr)\n .replace('heading', ' *#{1,6} *[^\\n]')\n .replace('lheading', lheading)\n .replace('|table', '')\n .replace('blockquote', ' {0,3}>')\n .replace('|fences', '')\n .replace('|list', '')\n .replace('|html', '')\n .replace('|tag', '')\n .getRegex()\n};\n/**\n * Inline-Level Grammar\n */\nconst escape = /^\\\\([!\"#$%&'()*+,\\-./:;<=>?@\\[\\]\\\\^_`{|}~])/;\nconst inlineCode = /^(`+)([^`]|[^`][\\s\\S]*?[^`])\\1(?!`)/;\nconst br = /^( {2,}|\\\\)\\n(?!\\s*$)/;\nconst inlineText = /^(`+|[^`])(?:(?= {2,}\\n)|[\\s\\S]*?(?:(?=[\\\\\nconst blockSkip = /\\[[^[\\]]*?\\]\\([^\\(\\)]*?\\)|`[^`]*?`|<[^<>]*?>/g;\nconst emStrongLDelim = edit(/^(?:\\*+(?:((?!\\*)[punct])|[^\\s*]))|^_+(?:((?!_)[punct])|([^\\s_]))/, 'u')\n .replace(/punct/g, _punctuation)\n .getRegex();\nconst emStrongRDelimAst = edit('^[^_*]*?__[^_*]*?\\\\*[^_*]*?(?=__)' // Skip orphan inside strong\n + '|[^*]+(?=[^*])' // Consume to delim\n + '|(?!\\\\*)[punct](\\\\*+)(?=[\\\\s]|$)' // (1) #*** can only be a Right Delimiter\n + '|[^punct\\\\s](\\\\*+)(?!\\\\*)(?=[punct\\\\s]|$)' // (2) a***#, a*** can only be a Right Delimiter\n + '|(?!\\\\*)[punct\\\\s](\\\\*+)(?=[^punct\\\\s])' // (3) #***a, ***a can only be Left Delimiter\n + '|[\\\\s](\\\\*+)(?!\\\\*)(?=[punct])' // (4) ***# can only be Left Delimiter\n + '|(?!\\\\*)[punct](\\\\*+)(?!\\\\*)(?=[punct])' // (5) #***# can be either Left or Right Delimiter\n + '|[^punct\\\\s](\\\\*+)(?=[^punct\\\\s])', 'gu') // (6) a***a can be either Left or Right Delimiter\n .replace(/punct/g, _punctuation)\n .getRegex();\n// (6) Not allowed for _\nconst emStrongRDelimUnd = edit('^[^_*]*?\\\\*\\\\*[^_*]*?_[^_*]*?(?=\\\\*\\\\*)' // Skip orphan inside strong\n + '|[^_]+(?=[^_])' // Consume to delim\n + '|(?!_)[punct](_+)(?=[\\\\s]|$)' // (1) #___ can only be a Right Delimiter\n + '|[^punct\\\\s](_+)(?!_)(?=[punct\\\\s]|$)' // (2) a___#, a___ can only be a Right Delimiter\n + '|(?!_)[punct\\\\s](_+)(?=[^punct\\\\s])' // (3) #___a, ___a can only be Left Delimiter\n + '|[\\\\s](_+)(?!_)(?=[punct])' // (4) ___# can only be Left Delimiter\n + '|(?!_)[punct](_+)(?!_)(?=[punct])', 'gu') // (5) #___# can be either Left or Right Delimiter\n .replace(/punct/g, _punctuation)\n .getRegex();\nconst anyPunctuation = edit(/\\\\([punct])/, 'gu')\n .replace(/punct/g, _punctuation)\n .getRegex();\nconst autolink = edit(/^<(scheme:[^\\s\\x00-\\x1f<>]*|email)>/)\n .replace('scheme', /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/)\n .replace('email', /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/)\n .getRegex();\nconst _inlineComment = edit(_comment).replace('(?:-->|$)', '-->').getRegex();\nconst tag = edit('^comment'\n + '|^' // self-closing tag\n + '|^<[a-zA-Z][\\\\w-]*(?:attribute)*?\\\\s*/?>' // open tag\n + '|^<\\\\?[\\\\s\\\\S]*?\\\\?>' // processing instruction, e.g. \n + '|^' // declaration, e.g. \n + '|^') // CDATA section\n .replace('comment', _inlineComment)\n .replace('attribute', /\\s+[a-zA-Z:_][\\w.:-]*(?:\\s*=\\s*\"[^\"]*\"|\\s*=\\s*'[^']*'|\\s*=\\s*[^\\s\"'=<>`]+)?/)\n .getRegex();\nconst _inlineLabel = /(?:\\[(?:\\\\.|[^\\[\\]\\\\])*\\]|\\\\.|`[^`]*`|[^\\[\\]\\\\`])*?/;\nconst link = edit(/^!?\\[(label)\\]\\(\\s*(href)(?:\\s+(title))?\\s*\\)/)\n .replace('label', _inlineLabel)\n .replace('href', /<(?:\\\\.|[^\\n<>\\\\])+>|[^\\s\\x00-\\x1f]*/)\n .replace('title', /\"(?:\\\\\"?|[^\"\\\\])*\"|'(?:\\\\'?|[^'\\\\])*'|\\((?:\\\\\\)?|[^)\\\\])*\\)/)\n .getRegex();\nconst reflink = edit(/^!?\\[(label)\\]\\[(ref)\\]/)\n .replace('label', _inlineLabel)\n .replace('ref', _blockLabel)\n .getRegex();\nconst nolink = edit(/^!?\\[(ref)\\](?:\\[\\])?/)\n .replace('ref', _blockLabel)\n .getRegex();\nconst reflinkSearch = edit('reflink|nolink(?!\\\\()', 'g')\n .replace('reflink', reflink)\n .replace('nolink', nolink)\n .getRegex();\n/**\n * Normal Inline Grammar\n */\nconst inlineNormal = {\n _backpedal: noopTest, // only used for GFM url\n anyPunctuation,\n autolink,\n blockSkip,\n br,\n code: inlineCode,\n del: noopTest,\n emStrongLDelim,\n emStrongRDelimAst,\n emStrongRDelimUnd,\n escape,\n link,\n nolink,\n punctuation,\n reflink,\n reflinkSearch,\n tag,\n text: inlineText,\n url: noopTest\n};\n/**\n * Pedantic Inline Grammar\n */\nconst inlinePedantic = {\n ...inlineNormal,\n link: edit(/^!?\\[(label)\\]\\((.*?)\\)/)\n .replace('label', _inlineLabel)\n .getRegex(),\n reflink: edit(/^!?\\[(label)\\]\\s*\\[([^\\]]*)\\]/)\n .replace('label', _inlineLabel)\n .getRegex()\n};\n/**\n * GFM Inline Grammar\n */\nconst inlineGfm = {\n ...inlineNormal,\n escape: edit(escape).replace('])', '~|])').getRegex(),\n url: edit(/^((?:ftp|https?):\\/\\/|www\\.)(?:[a-zA-Z0-9\\-]+\\.?)+[^\\s<]*|^email/, 'i')\n .replace('email', /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/)\n .getRegex(),\n _backpedal: /(?:[^?!.,:;*_'\"~()&]+|\\([^)]*\\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'\"~)]+(?!$))+/,\n del: /^(~~?)(?=[^\\s~])([\\s\\S]*?[^\\s~])\\1(?=[^~]|$)/,\n text: /^([`~]+|[^`~])(?:(?= {2,}\\n)|(?=[a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-]+@)|[\\s\\S]*?(?:(?=[\\\\ {\n return leading + ' '.repeat(tabs.length);\n });\n }\n let token;\n let lastToken;\n let cutSrc;\n while (src) {\n if (this.options.extensions\n && this.options.extensions.block\n && this.options.extensions.block.some((extTokenizer) => {\n if (token = extTokenizer.call({ lexer: this }, src, tokens)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n return true;\n }\n return false;\n })) {\n continue;\n }\n // newline\n if (token = this.tokenizer.space(src)) {\n src = src.substring(token.raw.length);\n if (token.raw.length === 1 && tokens.length > 0) {\n // if there's a single \\n as a spacer, it's terminating the last line,\n // so move it there so that we don't get unnecessary paragraph tags\n tokens[tokens.length - 1].raw += '\\n';\n }\n else {\n tokens.push(token);\n }\n continue;\n }\n // code\n if (token = this.tokenizer.code(src)) {\n src = src.substring(token.raw.length);\n lastToken = tokens[tokens.length - 1];\n // An indented code block cannot interrupt a paragraph.\n if (lastToken && (lastToken.type === 'paragraph' || lastToken.type === 'text')) {\n lastToken.raw += '\\n' + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;\n }\n else {\n tokens.push(token);\n }\n continue;\n }\n // fences\n if (token = this.tokenizer.fences(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // heading\n if (token = this.tokenizer.heading(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // hr\n if (token = this.tokenizer.hr(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // blockquote\n if (token = this.tokenizer.blockquote(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // list\n if (token = this.tokenizer.list(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // html\n if (token = this.tokenizer.html(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // def\n if (token = this.tokenizer.def(src)) {\n src = src.substring(token.raw.length);\n lastToken = tokens[tokens.length - 1];\n if (lastToken && (lastToken.type === 'paragraph' || lastToken.type === 'text')) {\n lastToken.raw += '\\n' + token.raw;\n lastToken.text += '\\n' + token.raw;\n this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;\n }\n else if (!this.tokens.links[token.tag]) {\n this.tokens.links[token.tag] = {\n href: token.href,\n title: token.title\n };\n }\n continue;\n }\n // table (gfm)\n if (token = this.tokenizer.table(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // lheading\n if (token = this.tokenizer.lheading(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // top-level paragraph\n // prevent paragraph consuming extensions by clipping 'src' to extension start\n cutSrc = src;\n if (this.options.extensions && this.options.extensions.startBlock) {\n let startIndex = Infinity;\n const tempSrc = src.slice(1);\n let tempStart;\n this.options.extensions.startBlock.forEach((getStartIndex) => {\n tempStart = getStartIndex.call({ lexer: this }, tempSrc);\n if (typeof tempStart === 'number' && tempStart >= 0) {\n startIndex = Math.min(startIndex, tempStart);\n }\n });\n if (startIndex < Infinity && startIndex >= 0) {\n cutSrc = src.substring(0, startIndex + 1);\n }\n }\n if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) {\n lastToken = tokens[tokens.length - 1];\n if (lastParagraphClipped && lastToken?.type === 'paragraph') {\n lastToken.raw += '\\n' + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.pop();\n this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;\n }\n else {\n tokens.push(token);\n }\n lastParagraphClipped = (cutSrc.length !== src.length);\n src = src.substring(token.raw.length);\n continue;\n }\n // text\n if (token = this.tokenizer.text(src)) {\n src = src.substring(token.raw.length);\n lastToken = tokens[tokens.length - 1];\n if (lastToken && lastToken.type === 'text') {\n lastToken.raw += '\\n' + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.pop();\n this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;\n }\n else {\n tokens.push(token);\n }\n continue;\n }\n if (src) {\n const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);\n if (this.options.silent) {\n console.error(errMsg);\n break;\n }\n else {\n throw new Error(errMsg);\n }\n }\n }\n this.state.top = true;\n return tokens;\n }\n inline(src, tokens = []) {\n this.inlineQueue.push({ src, tokens });\n return tokens;\n }\n /**\n * Lexing/Compiling\n */\n inlineTokens(src, tokens = []) {\n let token, lastToken, cutSrc;\n // String with links masked to avoid interference with em and strong\n let maskedSrc = src;\n let match;\n let keepPrevChar, prevChar;\n // Mask out reflinks\n if (this.tokens.links) {\n const links = Object.keys(this.tokens.links);\n if (links.length > 0) {\n while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) {\n if (links.includes(match[0].slice(match[0].lastIndexOf('[') + 1, -1))) {\n maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex);\n }\n }\n }\n }\n // Mask out other blocks\n while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) {\n maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);\n }\n // Mask out escaped characters\n while ((match = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) != null) {\n maskedSrc = maskedSrc.slice(0, match.index) + '++' + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);\n }\n while (src) {\n if (!keepPrevChar) {\n prevChar = '';\n }\n keepPrevChar = false;\n // extensions\n if (this.options.extensions\n && this.options.extensions.inline\n && this.options.extensions.inline.some((extTokenizer) => {\n if (token = extTokenizer.call({ lexer: this }, src, tokens)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n return true;\n }\n return false;\n })) {\n continue;\n }\n // escape\n if (token = this.tokenizer.escape(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // tag\n if (token = this.tokenizer.tag(src)) {\n src = src.substring(token.raw.length);\n lastToken = tokens[tokens.length - 1];\n if (lastToken && token.type === 'text' && lastToken.type === 'text') {\n lastToken.raw += token.raw;\n lastToken.text += token.text;\n }\n else {\n tokens.push(token);\n }\n continue;\n }\n // link\n if (token = this.tokenizer.link(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // reflink, nolink\n if (token = this.tokenizer.reflink(src, this.tokens.links)) {\n src = src.substring(token.raw.length);\n lastToken = tokens[tokens.length - 1];\n if (lastToken && token.type === 'text' && lastToken.type === 'text') {\n lastToken.raw += token.raw;\n lastToken.text += token.text;\n }\n else {\n tokens.push(token);\n }\n continue;\n }\n // em & strong\n if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // code\n if (token = this.tokenizer.codespan(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // br\n if (token = this.tokenizer.br(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // del (gfm)\n if (token = this.tokenizer.del(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // autolink\n if (token = this.tokenizer.autolink(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // url (gfm)\n if (!this.state.inLink && (token = this.tokenizer.url(src))) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // text\n // prevent inlineText consuming extensions by clipping 'src' to extension start\n cutSrc = src;\n if (this.options.extensions && this.options.extensions.startInline) {\n let startIndex = Infinity;\n const tempSrc = src.slice(1);\n let tempStart;\n this.options.extensions.startInline.forEach((getStartIndex) => {\n tempStart = getStartIndex.call({ lexer: this }, tempSrc);\n if (typeof tempStart === 'number' && tempStart >= 0) {\n startIndex = Math.min(startIndex, tempStart);\n }\n });\n if (startIndex < Infinity && startIndex >= 0) {\n cutSrc = src.substring(0, startIndex + 1);\n }\n }\n if (token = this.tokenizer.inlineText(cutSrc)) {\n src = src.substring(token.raw.length);\n if (token.raw.slice(-1) !== '_') { // Track prevChar before string of ____ started\n prevChar = token.raw.slice(-1);\n }\n keepPrevChar = true;\n lastToken = tokens[tokens.length - 1];\n if (lastToken && lastToken.type === 'text') {\n lastToken.raw += token.raw;\n lastToken.text += token.text;\n }\n else {\n tokens.push(token);\n }\n continue;\n }\n if (src) {\n const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);\n if (this.options.silent) {\n console.error(errMsg);\n break;\n }\n else {\n throw new Error(errMsg);\n }\n }\n }\n return tokens;\n }\n}\n","import { _defaults } from './defaults.ts';\nimport { cleanUrl, escape } from './helpers.ts';\n/**\n * Renderer\n */\nexport class _Renderer {\n options;\n parser; // set by the parser\n constructor(options) {\n this.options = options || _defaults;\n }\n space(token) {\n return '';\n }\n code({ text, lang, escaped }) {\n const langString = (lang || '').match(/^\\S*/)?.[0];\n const code = text.replace(/\\n$/, '') + '\\n';\n if (!langString) {\n return '
    '\n                + (escaped ? code : escape(code, true))\n                + '
    \\n';\n }\n return '
    '\n            + (escaped ? code : escape(code, true))\n            + '
    \\n';\n }\n blockquote({ tokens }) {\n const body = this.parser.parse(tokens);\n return `
    \\n${body}
    \\n`;\n }\n html({ text }) {\n return text;\n }\n heading({ tokens, depth }) {\n return `${this.parser.parseInline(tokens)}\\n`;\n }\n hr(token) {\n return '
    \\n';\n }\n list(token) {\n const ordered = token.ordered;\n const start = token.start;\n let body = '';\n for (let j = 0; j < token.items.length; j++) {\n const item = token.items[j];\n body += this.listitem(item);\n }\n const type = ordered ? 'ol' : 'ul';\n const startAttr = (ordered && start !== 1) ? (' start=\"' + start + '\"') : '';\n return '<' + type + startAttr + '>\\n' + body + '\\n';\n }\n listitem(item) {\n let itemBody = '';\n if (item.task) {\n const checkbox = this.checkbox({ checked: !!item.checked });\n if (item.loose) {\n if (item.tokens.length > 0 && item.tokens[0].type === 'paragraph') {\n item.tokens[0].text = checkbox + ' ' + item.tokens[0].text;\n if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') {\n item.tokens[0].tokens[0].text = checkbox + ' ' + item.tokens[0].tokens[0].text;\n }\n }\n else {\n item.tokens.unshift({\n type: 'text',\n raw: checkbox + ' ',\n text: checkbox + ' '\n });\n }\n }\n else {\n itemBody += checkbox + ' ';\n }\n }\n itemBody += this.parser.parse(item.tokens, !!item.loose);\n return `
  • ${itemBody}
  • \\n`;\n }\n checkbox({ checked }) {\n return '';\n }\n paragraph({ tokens }) {\n return `

    ${this.parser.parseInline(tokens)}

    \\n`;\n }\n table(token) {\n let header = '';\n // header\n let cell = '';\n for (let j = 0; j < token.header.length; j++) {\n cell += this.tablecell(token.header[j]);\n }\n header += this.tablerow({ text: cell });\n let body = '';\n for (let j = 0; j < token.rows.length; j++) {\n const row = token.rows[j];\n cell = '';\n for (let k = 0; k < row.length; k++) {\n cell += this.tablecell(row[k]);\n }\n body += this.tablerow({ text: cell });\n }\n if (body)\n body = `${body}`;\n return '\\n'\n + '\\n'\n + header\n + '\\n'\n + body\n + '
    \\n';\n }\n tablerow({ text }) {\n return `\\n${text}\\n`;\n }\n tablecell(token) {\n const content = this.parser.parseInline(token.tokens);\n const type = token.header ? 'th' : 'td';\n const tag = token.align\n ? `<${type} align=\"${token.align}\">`\n : `<${type}>`;\n return tag + content + `\\n`;\n }\n /**\n * span level renderer\n */\n strong({ tokens }) {\n return `${this.parser.parseInline(tokens)}`;\n }\n em({ tokens }) {\n return `${this.parser.parseInline(tokens)}`;\n }\n codespan({ text }) {\n return `${text}`;\n }\n br(token) {\n return '
    ';\n }\n del({ tokens }) {\n return `${this.parser.parseInline(tokens)}`;\n }\n link({ href, title, tokens }) {\n const text = this.parser.parseInline(tokens);\n const cleanHref = cleanUrl(href);\n if (cleanHref === null) {\n return text;\n }\n href = cleanHref;\n let out = '
    ';\n return out;\n }\n image({ href, title, text }) {\n const cleanHref = cleanUrl(href);\n if (cleanHref === null) {\n return text;\n }\n href = cleanHref;\n let out = `\"${text}\"`;\n {\n const tokens = genericToken[childTokens].flat(Infinity);\n values = values.concat(this.walkTokens(tokens, callback));\n });\n }\n else if (genericToken.tokens) {\n values = values.concat(this.walkTokens(genericToken.tokens, callback));\n }\n }\n }\n }\n return values;\n }\n use(...args) {\n const extensions = this.defaults.extensions || { renderers: {}, childTokens: {} };\n args.forEach((pack) => {\n // copy options to new object\n const opts = { ...pack };\n // set async to true if it was set to true before\n opts.async = this.defaults.async || opts.async || false;\n // ==-- Parse \"addon\" extensions --== //\n if (pack.extensions) {\n pack.extensions.forEach((ext) => {\n if (!ext.name) {\n throw new Error('extension name required');\n }\n if ('renderer' in ext) { // Renderer extensions\n const prevRenderer = extensions.renderers[ext.name];\n if (prevRenderer) {\n // Replace extension with func to run new extension but fall back if false\n extensions.renderers[ext.name] = function (...args) {\n let ret = ext.renderer.apply(this, args);\n if (ret === false) {\n ret = prevRenderer.apply(this, args);\n }\n return ret;\n };\n }\n else {\n extensions.renderers[ext.name] = ext.renderer;\n }\n }\n if ('tokenizer' in ext) { // Tokenizer Extensions\n if (!ext.level || (ext.level !== 'block' && ext.level !== 'inline')) {\n throw new Error(\"extension level must be 'block' or 'inline'\");\n }\n const extLevel = extensions[ext.level];\n if (extLevel) {\n extLevel.unshift(ext.tokenizer);\n }\n else {\n extensions[ext.level] = [ext.tokenizer];\n }\n if (ext.start) { // Function to check for start of token\n if (ext.level === 'block') {\n if (extensions.startBlock) {\n extensions.startBlock.push(ext.start);\n }\n else {\n extensions.startBlock = [ext.start];\n }\n }\n else if (ext.level === 'inline') {\n if (extensions.startInline) {\n extensions.startInline.push(ext.start);\n }\n else {\n extensions.startInline = [ext.start];\n }\n }\n }\n }\n if ('childTokens' in ext && ext.childTokens) { // Child tokens to be visited by walkTokens\n extensions.childTokens[ext.name] = ext.childTokens;\n }\n });\n opts.extensions = extensions;\n }\n // ==-- Parse \"overwrite\" extensions --== //\n if (pack.renderer) {\n const renderer = this.defaults.renderer || new _Renderer(this.defaults);\n for (const prop in pack.renderer) {\n if (!(prop in renderer)) {\n throw new Error(`renderer '${prop}' does not exist`);\n }\n if (['options', 'parser'].includes(prop)) {\n // ignore options property\n continue;\n }\n const rendererProp = prop;\n let rendererFunc = pack.renderer[rendererProp];\n const prevRenderer = renderer[rendererProp];\n // Replace renderer with func to run extension, but fall back if false\n renderer[rendererProp] = (...args) => {\n if (!pack.useNewRenderer) {\n // TODO: Remove this in next major version\n rendererFunc = this.#convertRendererFunction(rendererFunc, rendererProp, renderer);\n }\n let ret = rendererFunc.apply(renderer, args);\n if (ret === false) {\n ret = prevRenderer.apply(renderer, args);\n }\n return ret || '';\n };\n }\n opts.renderer = renderer;\n }\n if (pack.tokenizer) {\n const tokenizer = this.defaults.tokenizer || new _Tokenizer(this.defaults);\n for (const prop in pack.tokenizer) {\n if (!(prop in tokenizer)) {\n throw new Error(`tokenizer '${prop}' does not exist`);\n }\n if (['options', 'rules', 'lexer'].includes(prop)) {\n // ignore options, rules, and lexer properties\n continue;\n }\n const tokenizerProp = prop;\n const tokenizerFunc = pack.tokenizer[tokenizerProp];\n const prevTokenizer = tokenizer[tokenizerProp];\n // Replace tokenizer with func to run extension, but fall back if false\n // @ts-expect-error cannot type tokenizer function dynamically\n tokenizer[tokenizerProp] = (...args) => {\n let ret = tokenizerFunc.apply(tokenizer, args);\n if (ret === false) {\n ret = prevTokenizer.apply(tokenizer, args);\n }\n return ret;\n };\n }\n opts.tokenizer = tokenizer;\n }\n // ==-- Parse Hooks extensions --== //\n if (pack.hooks) {\n const hooks = this.defaults.hooks || new _Hooks();\n for (const prop in pack.hooks) {\n if (!(prop in hooks)) {\n throw new Error(`hook '${prop}' does not exist`);\n }\n if (prop === 'options') {\n // ignore options property\n continue;\n }\n const hooksProp = prop;\n const hooksFunc = pack.hooks[hooksProp];\n const prevHook = hooks[hooksProp];\n if (_Hooks.passThroughHooks.has(prop)) {\n // @ts-expect-error cannot type hook function dynamically\n hooks[hooksProp] = (arg) => {\n if (this.defaults.async) {\n return Promise.resolve(hooksFunc.call(hooks, arg)).then(ret => {\n return prevHook.call(hooks, ret);\n });\n }\n const ret = hooksFunc.call(hooks, arg);\n return prevHook.call(hooks, ret);\n };\n }\n else {\n // @ts-expect-error cannot type hook function dynamically\n hooks[hooksProp] = (...args) => {\n let ret = hooksFunc.apply(hooks, args);\n if (ret === false) {\n ret = prevHook.apply(hooks, args);\n }\n return ret;\n };\n }\n }\n opts.hooks = hooks;\n }\n // ==-- Parse WalkTokens extensions --== //\n if (pack.walkTokens) {\n const walkTokens = this.defaults.walkTokens;\n const packWalktokens = pack.walkTokens;\n opts.walkTokens = function (token) {\n let values = [];\n values.push(packWalktokens.call(this, token));\n if (walkTokens) {\n values = values.concat(walkTokens.call(this, token));\n }\n return values;\n };\n }\n this.defaults = { ...this.defaults, ...opts };\n });\n return this;\n }\n // TODO: Remove this in next major release\n #convertRendererFunction(func, prop, renderer) {\n switch (prop) {\n case 'heading':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n return func.call(this, renderer.parser.parseInline(token.tokens), token.depth, unescape(renderer.parser.parseInline(token.tokens, renderer.parser.textRenderer)));\n };\n case 'code':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n return func.call(this, token.text, token.lang, !!token.escaped);\n };\n case 'table':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n let header = '';\n // header\n let cell = '';\n for (let j = 0; j < token.header.length; j++) {\n cell += this.tablecell({\n text: token.header[j].text,\n tokens: token.header[j].tokens,\n header: true,\n align: token.align[j]\n });\n }\n header += this.tablerow({ text: cell });\n let body = '';\n for (let j = 0; j < token.rows.length; j++) {\n const row = token.rows[j];\n cell = '';\n for (let k = 0; k < row.length; k++) {\n cell += this.tablecell({\n text: row[k].text,\n tokens: row[k].tokens,\n header: false,\n align: token.align[k]\n });\n }\n body += this.tablerow({ text: cell });\n }\n return func.call(this, header, body);\n };\n case 'blockquote':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n const body = this.parser.parse(token.tokens);\n return func.call(this, body);\n };\n case 'list':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n const ordered = token.ordered;\n const start = token.start;\n const loose = token.loose;\n let body = '';\n for (let j = 0; j < token.items.length; j++) {\n const item = token.items[j];\n const checked = item.checked;\n const task = item.task;\n let itemBody = '';\n if (item.task) {\n const checkbox = this.checkbox({ checked: !!checked });\n if (loose) {\n if (item.tokens.length > 0 && item.tokens[0].type === 'paragraph') {\n item.tokens[0].text = checkbox + ' ' + item.tokens[0].text;\n if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') {\n item.tokens[0].tokens[0].text = checkbox + ' ' + item.tokens[0].tokens[0].text;\n }\n }\n else {\n item.tokens.unshift({\n type: 'text',\n text: checkbox + ' '\n });\n }\n }\n else {\n itemBody += checkbox + ' ';\n }\n }\n itemBody += this.parser.parse(item.tokens, loose);\n body += this.listitem({\n type: 'list_item',\n raw: itemBody,\n text: itemBody,\n task,\n checked: !!checked,\n loose,\n tokens: item.tokens\n });\n }\n return func.call(this, body, ordered, start);\n };\n case 'html':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n return func.call(this, token.text, token.block);\n };\n case 'paragraph':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n return func.call(this, this.parser.parseInline(token.tokens));\n };\n case 'escape':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n return func.call(this, token.text);\n };\n case 'link':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n return func.call(this, token.href, token.title, this.parser.parseInline(token.tokens));\n };\n case 'image':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n return func.call(this, token.href, token.title, token.text);\n };\n case 'strong':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n return func.call(this, this.parser.parseInline(token.tokens));\n };\n case 'em':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n return func.call(this, this.parser.parseInline(token.tokens));\n };\n case 'codespan':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n return func.call(this, token.text);\n };\n case 'del':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n return func.call(this, this.parser.parseInline(token.tokens));\n };\n case 'text':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n return func.call(this, token.text);\n };\n default:\n // do nothing\n }\n return func;\n }\n setOptions(opt) {\n this.defaults = { ...this.defaults, ...opt };\n return this;\n }\n lexer(src, options) {\n return _Lexer.lex(src, options ?? this.defaults);\n }\n parser(tokens, options) {\n return _Parser.parse(tokens, options ?? this.defaults);\n }\n #parseMarkdown(lexer, parser) {\n return (src, options) => {\n const origOpt = { ...options };\n const opt = { ...this.defaults, ...origOpt };\n // Show warning if an extension set async to true but the parse was called with async: false\n if (this.defaults.async === true && origOpt.async === false) {\n if (!opt.silent) {\n console.warn('marked(): The async option was set to true by an extension. The async: false option sent to parse will be ignored.');\n }\n opt.async = true;\n }\n const throwError = this.#onError(!!opt.silent, !!opt.async);\n // throw error in case of non string input\n if (typeof src === 'undefined' || src === null) {\n return throwError(new Error('marked(): input parameter is undefined or null'));\n }\n if (typeof src !== 'string') {\n return throwError(new Error('marked(): input parameter is of type '\n + Object.prototype.toString.call(src) + ', string expected'));\n }\n if (opt.hooks) {\n opt.hooks.options = opt;\n }\n if (opt.async) {\n return Promise.resolve(opt.hooks ? opt.hooks.preprocess(src) : src)\n .then(src => lexer(src, opt))\n .then(tokens => opt.hooks ? opt.hooks.processAllTokens(tokens) : tokens)\n .then(tokens => opt.walkTokens ? Promise.all(this.walkTokens(tokens, opt.walkTokens)).then(() => tokens) : tokens)\n .then(tokens => parser(tokens, opt))\n .then(html => opt.hooks ? opt.hooks.postprocess(html) : html)\n .catch(throwError);\n }\n try {\n if (opt.hooks) {\n src = opt.hooks.preprocess(src);\n }\n let tokens = lexer(src, opt);\n if (opt.hooks) {\n tokens = opt.hooks.processAllTokens(tokens);\n }\n if (opt.walkTokens) {\n this.walkTokens(tokens, opt.walkTokens);\n }\n let html = parser(tokens, opt);\n if (opt.hooks) {\n html = opt.hooks.postprocess(html);\n }\n return html;\n }\n catch (e) {\n return throwError(e);\n }\n };\n }\n #onError(silent, async) {\n return (e) => {\n e.message += '\\nPlease report this to https://github.com/markedjs/marked.';\n if (silent) {\n const msg = '

    An error occurred:

    '\n                    + escape(e.message + '', true)\n                    + '
    ';\n if (async) {\n return Promise.resolve(msg);\n }\n return msg;\n }\n if (async) {\n return Promise.reject(e);\n }\n throw e;\n };\n }\n}\n","import { _Lexer } from './Lexer.ts';\nimport { _Parser } from './Parser.ts';\nimport { _Tokenizer } from './Tokenizer.ts';\nimport { _Renderer } from './Renderer.ts';\nimport { _TextRenderer } from './TextRenderer.ts';\nimport { _Hooks } from './Hooks.ts';\nimport { Marked } from './Instance.ts';\nimport { _getDefaults, changeDefaults, _defaults } from './defaults.ts';\nconst markedInstance = new Marked();\nexport function marked(src, opt) {\n return markedInstance.parse(src, opt);\n}\n/**\n * Sets the default options.\n *\n * @param options Hash of options\n */\nmarked.options =\n marked.setOptions = function (options) {\n markedInstance.setOptions(options);\n marked.defaults = markedInstance.defaults;\n changeDefaults(marked.defaults);\n return marked;\n };\n/**\n * Gets the original marked default options.\n */\nmarked.getDefaults = _getDefaults;\nmarked.defaults = _defaults;\n/**\n * Use Extension\n */\nmarked.use = function (...args) {\n markedInstance.use(...args);\n marked.defaults = markedInstance.defaults;\n changeDefaults(marked.defaults);\n return marked;\n};\n/**\n * Run callback for every token\n */\nmarked.walkTokens = function (tokens, callback) {\n return markedInstance.walkTokens(tokens, callback);\n};\n/**\n * Compiles markdown to HTML without enclosing `p` tag.\n *\n * @param src String of markdown source to be compiled\n * @param options Hash of options\n * @return String of compiled HTML\n */\nmarked.parseInline = markedInstance.parseInline;\n/**\n * Expose\n */\nmarked.Parser = _Parser;\nmarked.parser = _Parser.parse;\nmarked.Renderer = _Renderer;\nmarked.TextRenderer = _TextRenderer;\nmarked.Lexer = _Lexer;\nmarked.lexer = _Lexer.lex;\nmarked.Tokenizer = _Tokenizer;\nmarked.Hooks = _Hooks;\nmarked.parse = marked;\nexport const options = marked.options;\nexport const setOptions = marked.setOptions;\nexport const use = marked.use;\nexport const walkTokens = marked.walkTokens;\nexport const parseInline = marked.parseInline;\nexport const parse = marked;\nexport const parser = _Parser.parse;\nexport const lexer = _Lexer.lex;\nexport { _defaults as defaults, _getDefaults as getDefaults } from './defaults.ts';\nexport { _Lexer as Lexer } from './Lexer.ts';\nexport { _Parser as Parser } from './Parser.ts';\nexport { _Tokenizer as Tokenizer } from './Tokenizer.ts';\nexport { _Renderer as Renderer } from './Renderer.ts';\nexport { _TextRenderer as TextRenderer } from './TextRenderer.ts';\nexport { _Hooks as Hooks } from './Hooks.ts';\nexport { Marked } from './Instance.ts';\n"],"names":["escape"],"mappings":";;;;;;;;;;;AAAA;AACA;AACA;AACO,SAAS,YAAY,GAAG;AAC/B,IAAI,OAAO;AACX,QAAQ,KAAK,EAAE,KAAK;AACpB,QAAQ,MAAM,EAAE,KAAK;AACrB,QAAQ,UAAU,EAAE,IAAI;AACxB,QAAQ,GAAG,EAAE,IAAI;AACjB,QAAQ,KAAK,EAAE,IAAI;AACnB,QAAQ,QAAQ,EAAE,KAAK;AACvB,QAAQ,QAAQ,EAAE,IAAI;AACtB,QAAQ,MAAM,EAAE,KAAK;AACrB,QAAQ,SAAS,EAAE,IAAI;AACvB,QAAQ,UAAU,EAAE,IAAI;AACxB,KAAK,CAAC;AACN,CAAC;AACS,IAAC,SAAS,GAAG,YAAY,GAAG;AAC/B,SAAS,cAAc,CAAC,WAAW,EAAE;AAC5C,IAAI,SAAS,GAAG,WAAW,CAAC;AAC5B;;ACpBA;AACA;AACA;AACA,MAAM,UAAU,GAAG,SAAS,CAAC;AAC7B,MAAM,aAAa,GAAG,IAAI,MAAM,CAAC,UAAU,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;AACzD,MAAM,kBAAkB,GAAG,mDAAmD,CAAC;AAC/E,MAAM,qBAAqB,GAAG,IAAI,MAAM,CAAC,kBAAkB,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;AACzE,MAAM,kBAAkB,GAAG;AAC3B,IAAI,GAAG,EAAE,OAAO;AAChB,IAAI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AACA;AACA;AACA,MAAM,CAAC,UAAU,GAAG,UAAU,MAAM,EAAE,QAAQ,EAAE;AAChD,IAAI,OAAO,cAAc,CAAC,UAAU,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;AACvD,CAAC,CAAC;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,CAAC,WAAW,GAAG,cAAc,CAAC,WAAW,CAAC;AAChD;AACA;AACA;AACA,MAAM,CAAC,MAAM,GAAG,OAAO,CAAC;AACxB,MAAM,CAAC,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC;AAC9B,MAAM,CAAC,QAAQ,GAAG,SAAS,CAAC;AAC5B,MAAM,CAAC,YAAY,GAAG,aAAa,CAAC;AACpC,MAAM,CAAC,KAAK,GAAG,MAAM,CAAC;AACtB,MAAM,CAAC,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC;AAC1B,MAAM,CAAC,SAAS,GAAG,UAAU,CAAC;AAC9B,MAAM,CAAC,KAAK,GAAG,MAAM,CAAC;AACtB,MAAM,CAAC,KAAK,GAAG,MAAM,CAAC;AACV,MAAC,OAAO,GAAG,MAAM,CAAC,QAAQ;AAC1B,MAAC,UAAU,GAAG,MAAM,CAAC,WAAW;AAChC,MAAC,GAAG,GAAG,MAAM,CAAC,IAAI;AAClB,MAAC,UAAU,GAAG,MAAM,CAAC,WAAW;AAChC,MAAC,WAAW,GAAG,MAAM,CAAC,YAAY;AAClC,MAAC,KAAK,GAAG,OAAO;AAChB,MAAC,MAAM,GAAG,OAAO,CAAC,MAAM;AACxB,MAAC,KAAK,GAAG,MAAM,CAAC;;;;"} \ No newline at end of file diff --git a/scripts/node_modules/marked/lib/marked.umd.js b/scripts/node_modules/marked/lib/marked.umd.js new file mode 100644 index 000000000..63321e52b --- /dev/null +++ b/scripts/node_modules/marked/lib/marked.umd.js @@ -0,0 +1,2732 @@ +/** + * marked v13.0.1 - a markdown parser + * Copyright (c) 2011-2024, Christopher Jeffrey. (MIT Licensed) + * https://github.com/markedjs/marked + */ + +/** + * DO NOT EDIT THIS FILE + * The code in this file is generated from files in ./src/ + */ + +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.marked = {})); +})(this, (function (exports) { 'use strict'; + + /** + * Gets the original marked default options. + */ + function _getDefaults() { + return { + async: false, + breaks: false, + extensions: null, + gfm: true, + hooks: null, + pedantic: false, + renderer: null, + silent: false, + tokenizer: null, + walkTokens: null + }; + } + exports.defaults = _getDefaults(); + function changeDefaults(newDefaults) { + exports.defaults = newDefaults; + } + + /** + * Helpers + */ + const escapeTest = /[&<>"']/; + const escapeReplace = new RegExp(escapeTest.source, 'g'); + const escapeTestNoEncode = /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/; + const escapeReplaceNoEncode = new RegExp(escapeTestNoEncode.source, 'g'); + const escapeReplacements = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' + }; + const getEscapeReplacement = (ch) => escapeReplacements[ch]; + function escape$1(html, encode) { + if (encode) { + if (escapeTest.test(html)) { + return html.replace(escapeReplace, getEscapeReplacement); + } + } + else { + if (escapeTestNoEncode.test(html)) { + return html.replace(escapeReplaceNoEncode, getEscapeReplacement); + } + } + return html; + } + const unescapeTest = /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig; + function unescape(html) { + // explicitly match decimal, hex, and named HTML entities + return html.replace(unescapeTest, (_, n) => { + n = n.toLowerCase(); + if (n === 'colon') + return ':'; + if (n.charAt(0) === '#') { + return n.charAt(1) === 'x' + ? String.fromCharCode(parseInt(n.substring(2), 16)) + : String.fromCharCode(+n.substring(1)); + } + return ''; + }); + } + const caret = /(^|[^\[])\^/g; + function edit(regex, opt) { + let source = typeof regex === 'string' ? regex : regex.source; + opt = opt || ''; + const obj = { + replace: (name, val) => { + let valSource = typeof val === 'string' ? val : val.source; + valSource = valSource.replace(caret, '$1'); + source = source.replace(name, valSource); + return obj; + }, + getRegex: () => { + return new RegExp(source, opt); + } + }; + return obj; + } + function cleanUrl(href) { + try { + href = encodeURI(href).replace(/%25/g, '%'); + } + catch (e) { + return null; + } + return href; + } + const noopTest = { exec: () => null }; + function splitCells(tableRow, count) { + // ensure that every cell-delimiting pipe has a space + // before it to distinguish it from an escaped pipe + const row = tableRow.replace(/\|/g, (match, offset, str) => { + let escaped = false; + let curr = offset; + while (--curr >= 0 && str[curr] === '\\') + escaped = !escaped; + if (escaped) { + // odd number of slashes means | is escaped + // so we leave it alone + return '|'; + } + else { + // add space before unescaped | + return ' |'; + } + }), cells = row.split(/ \|/); + let i = 0; + // First/last cell in a row cannot be empty if it has no leading/trailing pipe + if (!cells[0].trim()) { + cells.shift(); + } + if (cells.length > 0 && !cells[cells.length - 1].trim()) { + cells.pop(); + } + if (count) { + if (cells.length > count) { + cells.splice(count); + } + else { + while (cells.length < count) + cells.push(''); + } + } + for (; i < cells.length; i++) { + // leading or trailing whitespace is ignored per the gfm spec + cells[i] = cells[i].trim().replace(/\\\|/g, '|'); + } + return cells; + } + /** + * Remove trailing 'c's. Equivalent to str.replace(/c*$/, ''). + * /c*$/ is vulnerable to REDOS. + * + * @param str + * @param c + * @param invert Remove suffix of non-c chars instead. Default falsey. + */ + function rtrim(str, c, invert) { + const l = str.length; + if (l === 0) { + return ''; + } + // Length of suffix matching the invert condition. + let suffLen = 0; + // Step left until we fail to match the invert condition. + while (suffLen < l) { + const currChar = str.charAt(l - suffLen - 1); + if (currChar === c && !invert) { + suffLen++; + } + else if (currChar !== c && invert) { + suffLen++; + } + else { + break; + } + } + return str.slice(0, l - suffLen); + } + function findClosingBracket(str, b) { + if (str.indexOf(b[1]) === -1) { + return -1; + } + let level = 0; + for (let i = 0; i < str.length; i++) { + if (str[i] === '\\') { + i++; + } + else if (str[i] === b[0]) { + level++; + } + else if (str[i] === b[1]) { + level--; + if (level < 0) { + return i; + } + } + } + return -1; + } + + function outputLink(cap, link, raw, lexer) { + const href = link.href; + const title = link.title ? escape$1(link.title) : null; + const text = cap[1].replace(/\\([\[\]])/g, '$1'); + if (cap[0].charAt(0) !== '!') { + lexer.state.inLink = true; + const token = { + type: 'link', + raw, + href, + title, + text, + tokens: lexer.inlineTokens(text) + }; + lexer.state.inLink = false; + return token; + } + return { + type: 'image', + raw, + href, + title, + text: escape$1(text) + }; + } + function indentCodeCompensation(raw, text) { + const matchIndentToCode = raw.match(/^(\s+)(?:```)/); + if (matchIndentToCode === null) { + return text; + } + const indentToCode = matchIndentToCode[1]; + return text + .split('\n') + .map(node => { + const matchIndentInNode = node.match(/^\s+/); + if (matchIndentInNode === null) { + return node; + } + const [indentInNode] = matchIndentInNode; + if (indentInNode.length >= indentToCode.length) { + return node.slice(indentToCode.length); + } + return node; + }) + .join('\n'); + } + /** + * Tokenizer + */ + class _Tokenizer { + options; + rules; // set by the lexer + lexer; // set by the lexer + constructor(options) { + this.options = options || exports.defaults; + } + space(src) { + const cap = this.rules.block.newline.exec(src); + if (cap && cap[0].length > 0) { + return { + type: 'space', + raw: cap[0] + }; + } + } + code(src) { + const cap = this.rules.block.code.exec(src); + if (cap) { + const text = cap[0].replace(/^ {1,4}/gm, ''); + return { + type: 'code', + raw: cap[0], + codeBlockStyle: 'indented', + text: !this.options.pedantic + ? rtrim(text, '\n') + : text + }; + } + } + fences(src) { + const cap = this.rules.block.fences.exec(src); + if (cap) { + const raw = cap[0]; + const text = indentCodeCompensation(raw, cap[3] || ''); + return { + type: 'code', + raw, + lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, '$1') : cap[2], + text + }; + } + } + heading(src) { + const cap = this.rules.block.heading.exec(src); + if (cap) { + let text = cap[2].trim(); + // remove trailing #s + if (/#$/.test(text)) { + const trimmed = rtrim(text, '#'); + if (this.options.pedantic) { + text = trimmed.trim(); + } + else if (!trimmed || / $/.test(trimmed)) { + // CommonMark requires space before trailing #s + text = trimmed.trim(); + } + } + return { + type: 'heading', + raw: cap[0], + depth: cap[1].length, + text, + tokens: this.lexer.inline(text) + }; + } + } + hr(src) { + const cap = this.rules.block.hr.exec(src); + if (cap) { + return { + type: 'hr', + raw: rtrim(cap[0], '\n') + }; + } + } + blockquote(src) { + const cap = this.rules.block.blockquote.exec(src); + if (cap) { + let lines = rtrim(cap[0], '\n').split('\n'); + let raw = ''; + let text = ''; + const tokens = []; + while (lines.length > 0) { + let inBlockquote = false; + const currentLines = []; + let i; + for (i = 0; i < lines.length; i++) { + // get lines up to a continuation + if (/^ {0,3}>/.test(lines[i])) { + currentLines.push(lines[i]); + inBlockquote = true; + } + else if (!inBlockquote) { + currentLines.push(lines[i]); + } + else { + break; + } + } + lines = lines.slice(i); + const currentRaw = currentLines.join('\n'); + const currentText = currentRaw + // precede setext continuation with 4 spaces so it isn't a setext + .replace(/\n {0,3}((?:=+|-+) *)(?=\n|$)/g, '\n $1') + .replace(/^ {0,3}>[ \t]?/gm, ''); + raw = raw ? `${raw}\n${currentRaw}` : currentRaw; + text = text ? `${text}\n${currentText}` : currentText; + // parse blockquote lines as top level tokens + // merge paragraphs if this is a continuation + const top = this.lexer.state.top; + this.lexer.state.top = true; + this.lexer.blockTokens(currentText, tokens, true); + this.lexer.state.top = top; + // if there is no continuation then we are done + if (lines.length === 0) { + break; + } + const lastToken = tokens[tokens.length - 1]; + if (lastToken?.type === 'code') { + // blockquote continuation cannot be preceded by a code block + break; + } + else if (lastToken?.type === 'blockquote') { + // include continuation in nested blockquote + const oldToken = lastToken; + const newText = oldToken.raw + '\n' + lines.join('\n'); + const newToken = this.blockquote(newText); + tokens[tokens.length - 1] = newToken; + raw = raw.substring(0, raw.length - oldToken.raw.length) + newToken.raw; + text = text.substring(0, text.length - oldToken.text.length) + newToken.text; + break; + } + else if (lastToken?.type === 'list') { + // include continuation in nested list + const oldToken = lastToken; + const newText = oldToken.raw + '\n' + lines.join('\n'); + const newToken = this.list(newText); + tokens[tokens.length - 1] = newToken; + raw = raw.substring(0, raw.length - lastToken.raw.length) + newToken.raw; + text = text.substring(0, text.length - oldToken.raw.length) + newToken.raw; + lines = newText.substring(tokens[tokens.length - 1].raw.length).split('\n'); + continue; + } + } + return { + type: 'blockquote', + raw, + tokens, + text + }; + } + } + list(src) { + let cap = this.rules.block.list.exec(src); + if (cap) { + let bull = cap[1].trim(); + const isordered = bull.length > 1; + const list = { + type: 'list', + raw: '', + ordered: isordered, + start: isordered ? +bull.slice(0, -1) : '', + loose: false, + items: [] + }; + bull = isordered ? `\\d{1,9}\\${bull.slice(-1)}` : `\\${bull}`; + if (this.options.pedantic) { + bull = isordered ? bull : '[*+-]'; + } + // Get next list item + const itemRegex = new RegExp(`^( {0,3}${bull})((?:[\t ][^\\n]*)?(?:\\n|$))`); + let raw = ''; + let itemContents = ''; + let endsWithBlankLine = false; + // Check if current bullet point can start a new List Item + while (src) { + let endEarly = false; + if (!(cap = itemRegex.exec(src))) { + break; + } + if (this.rules.block.hr.test(src)) { // End list if bullet was actually HR (possibly move into itemRegex?) + break; + } + raw = cap[0]; + src = src.substring(raw.length); + let line = cap[2].split('\n', 1)[0].replace(/^\t+/, (t) => ' '.repeat(3 * t.length)); + let nextLine = src.split('\n', 1)[0]; + let indent = 0; + if (this.options.pedantic) { + indent = 2; + itemContents = line.trimStart(); + } + else { + indent = cap[2].search(/[^ ]/); // Find first non-space char + indent = indent > 4 ? 1 : indent; // Treat indented code blocks (> 4 spaces) as having only 1 indent + itemContents = line.slice(indent); + indent += cap[1].length; + } + let blankLine = false; + if (!line && /^ *$/.test(nextLine)) { // Items begin with at most one blank line + raw += nextLine + '\n'; + src = src.substring(nextLine.length + 1); + endEarly = true; + } + if (!endEarly) { + const nextBulletRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ \t][^\\n]*)?(?:\\n|$))`); + const hrRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`); + const fencesBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\`\`\`|~~~)`); + const headingBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`); + // Check if following lines should be included in List Item + while (src) { + const rawLine = src.split('\n', 1)[0]; + nextLine = rawLine; + // Re-align to follow commonmark nesting rules + if (this.options.pedantic) { + nextLine = nextLine.replace(/^ {1,4}(?=( {4})*[^ ])/g, ' '); + } + // End list item if found code fences + if (fencesBeginRegex.test(nextLine)) { + break; + } + // End list item if found start of new heading + if (headingBeginRegex.test(nextLine)) { + break; + } + // End list item if found start of new bullet + if (nextBulletRegex.test(nextLine)) { + break; + } + // Horizontal rule found + if (hrRegex.test(src)) { + break; + } + if (nextLine.search(/[^ ]/) >= indent || !nextLine.trim()) { // Dedent if possible + itemContents += '\n' + nextLine.slice(indent); + } + else { + // not enough indentation + if (blankLine) { + break; + } + // paragraph continuation unless last line was a different block level element + if (line.search(/[^ ]/) >= 4) { // indented code block + break; + } + if (fencesBeginRegex.test(line)) { + break; + } + if (headingBeginRegex.test(line)) { + break; + } + if (hrRegex.test(line)) { + break; + } + itemContents += '\n' + nextLine; + } + if (!blankLine && !nextLine.trim()) { // Check if current line is blank + blankLine = true; + } + raw += rawLine + '\n'; + src = src.substring(rawLine.length + 1); + line = nextLine.slice(indent); + } + } + if (!list.loose) { + // If the previous item ended with a blank line, the list is loose + if (endsWithBlankLine) { + list.loose = true; + } + else if (/\n *\n *$/.test(raw)) { + endsWithBlankLine = true; + } + } + let istask = null; + let ischecked; + // Check for task list items + if (this.options.gfm) { + istask = /^\[[ xX]\] /.exec(itemContents); + if (istask) { + ischecked = istask[0] !== '[ ] '; + itemContents = itemContents.replace(/^\[[ xX]\] +/, ''); + } + } + list.items.push({ + type: 'list_item', + raw, + task: !!istask, + checked: ischecked, + loose: false, + text: itemContents, + tokens: [] + }); + list.raw += raw; + } + // Do not consume newlines at end of final item. Alternatively, make itemRegex *start* with any newlines to simplify/speed up endsWithBlankLine logic + list.items[list.items.length - 1].raw = raw.trimEnd(); + (list.items[list.items.length - 1]).text = itemContents.trimEnd(); + list.raw = list.raw.trimEnd(); + // Item child tokens handled here at end because we needed to have the final item to trim it first + for (let i = 0; i < list.items.length; i++) { + this.lexer.state.top = false; + list.items[i].tokens = this.lexer.blockTokens(list.items[i].text, []); + if (!list.loose) { + // Check if list should be loose + const spacers = list.items[i].tokens.filter(t => t.type === 'space'); + const hasMultipleLineBreaks = spacers.length > 0 && spacers.some(t => /\n.*\n/.test(t.raw)); + list.loose = hasMultipleLineBreaks; + } + } + // Set all items to loose if list is loose + if (list.loose) { + for (let i = 0; i < list.items.length; i++) { + list.items[i].loose = true; + } + } + return list; + } + } + html(src) { + const cap = this.rules.block.html.exec(src); + if (cap) { + const token = { + type: 'html', + block: true, + raw: cap[0], + pre: cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style', + text: cap[0] + }; + return token; + } + } + def(src) { + const cap = this.rules.block.def.exec(src); + if (cap) { + const tag = cap[1].toLowerCase().replace(/\s+/g, ' '); + const href = cap[2] ? cap[2].replace(/^<(.*)>$/, '$1').replace(this.rules.inline.anyPunctuation, '$1') : ''; + const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, '$1') : cap[3]; + return { + type: 'def', + tag, + raw: cap[0], + href, + title + }; + } + } + table(src) { + const cap = this.rules.block.table.exec(src); + if (!cap) { + return; + } + if (!/[:|]/.test(cap[2])) { + // delimiter row must have a pipe (|) or colon (:) otherwise it is a setext heading + return; + } + const headers = splitCells(cap[1]); + const aligns = cap[2].replace(/^\||\| *$/g, '').split('|'); + const rows = cap[3] && cap[3].trim() ? cap[3].replace(/\n[ \t]*$/, '').split('\n') : []; + const item = { + type: 'table', + raw: cap[0], + header: [], + align: [], + rows: [] + }; + if (headers.length !== aligns.length) { + // header and align columns must be equal, rows can be different. + return; + } + for (const align of aligns) { + if (/^ *-+: *$/.test(align)) { + item.align.push('right'); + } + else if (/^ *:-+: *$/.test(align)) { + item.align.push('center'); + } + else if (/^ *:-+ *$/.test(align)) { + item.align.push('left'); + } + else { + item.align.push(null); + } + } + for (let i = 0; i < headers.length; i++) { + item.header.push({ + text: headers[i], + tokens: this.lexer.inline(headers[i]), + header: true, + align: item.align[i] + }); + } + for (const row of rows) { + item.rows.push(splitCells(row, item.header.length).map((cell, i) => { + return { + text: cell, + tokens: this.lexer.inline(cell), + header: false, + align: item.align[i] + }; + })); + } + return item; + } + lheading(src) { + const cap = this.rules.block.lheading.exec(src); + if (cap) { + return { + type: 'heading', + raw: cap[0], + depth: cap[2].charAt(0) === '=' ? 1 : 2, + text: cap[1], + tokens: this.lexer.inline(cap[1]) + }; + } + } + paragraph(src) { + const cap = this.rules.block.paragraph.exec(src); + if (cap) { + const text = cap[1].charAt(cap[1].length - 1) === '\n' + ? cap[1].slice(0, -1) + : cap[1]; + return { + type: 'paragraph', + raw: cap[0], + text, + tokens: this.lexer.inline(text) + }; + } + } + text(src) { + const cap = this.rules.block.text.exec(src); + if (cap) { + return { + type: 'text', + raw: cap[0], + text: cap[0], + tokens: this.lexer.inline(cap[0]) + }; + } + } + escape(src) { + const cap = this.rules.inline.escape.exec(src); + if (cap) { + return { + type: 'escape', + raw: cap[0], + text: escape$1(cap[1]) + }; + } + } + tag(src) { + const cap = this.rules.inline.tag.exec(src); + if (cap) { + if (!this.lexer.state.inLink && /^
    /i.test(cap[0])) { + this.lexer.state.inLink = false; + } + if (!this.lexer.state.inRawBlock && /^<(pre|code|kbd|script)(\s|>)/i.test(cap[0])) { + this.lexer.state.inRawBlock = true; + } + else if (this.lexer.state.inRawBlock && /^<\/(pre|code|kbd|script)(\s|>)/i.test(cap[0])) { + this.lexer.state.inRawBlock = false; + } + return { + type: 'html', + raw: cap[0], + inLink: this.lexer.state.inLink, + inRawBlock: this.lexer.state.inRawBlock, + block: false, + text: cap[0] + }; + } + } + link(src) { + const cap = this.rules.inline.link.exec(src); + if (cap) { + const trimmedUrl = cap[2].trim(); + if (!this.options.pedantic && /^$/.test(trimmedUrl))) { + return; + } + // ending angle bracket cannot be escaped + const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), '\\'); + if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) { + return; + } + } + else { + // find closing parenthesis + const lastParenIndex = findClosingBracket(cap[2], '()'); + if (lastParenIndex > -1) { + const start = cap[0].indexOf('!') === 0 ? 5 : 4; + const linkLen = start + cap[1].length + lastParenIndex; + cap[2] = cap[2].substring(0, lastParenIndex); + cap[0] = cap[0].substring(0, linkLen).trim(); + cap[3] = ''; + } + } + let href = cap[2]; + let title = ''; + if (this.options.pedantic) { + // split pedantic href and title + const link = /^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(href); + if (link) { + href = link[1]; + title = link[3]; + } + } + else { + title = cap[3] ? cap[3].slice(1, -1) : ''; + } + href = href.trim(); + if (/^$/.test(trimmedUrl))) { + // pedantic allows starting angle bracket without ending angle bracket + href = href.slice(1); + } + else { + href = href.slice(1, -1); + } + } + return outputLink(cap, { + href: href ? href.replace(this.rules.inline.anyPunctuation, '$1') : href, + title: title ? title.replace(this.rules.inline.anyPunctuation, '$1') : title + }, cap[0], this.lexer); + } + } + reflink(src, links) { + let cap; + if ((cap = this.rules.inline.reflink.exec(src)) + || (cap = this.rules.inline.nolink.exec(src))) { + const linkString = (cap[2] || cap[1]).replace(/\s+/g, ' '); + const link = links[linkString.toLowerCase()]; + if (!link) { + const text = cap[0].charAt(0); + return { + type: 'text', + raw: text, + text + }; + } + return outputLink(cap, link, cap[0], this.lexer); + } + } + emStrong(src, maskedSrc, prevChar = '') { + let match = this.rules.inline.emStrongLDelim.exec(src); + if (!match) + return; + // _ can't be between two alphanumerics. \p{L}\p{N} includes non-english alphabet/numbers as well + if (match[3] && prevChar.match(/[\p{L}\p{N}]/u)) + return; + const nextChar = match[1] || match[2] || ''; + if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) { + // unicode Regex counts emoji as 1 char; spread into array for proper count (used multiple times below) + const lLength = [...match[0]].length - 1; + let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0; + const endReg = match[0][0] === '*' ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd; + endReg.lastIndex = 0; + // Clip maskedSrc to same section of string as src (move to lexer?) + maskedSrc = maskedSrc.slice(-1 * src.length + lLength); + while ((match = endReg.exec(maskedSrc)) != null) { + rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6]; + if (!rDelim) + continue; // skip single * in __abc*abc__ + rLength = [...rDelim].length; + if (match[3] || match[4]) { // found another Left Delim + delimTotal += rLength; + continue; + } + else if (match[5] || match[6]) { // either Left or Right Delim + if (lLength % 3 && !((lLength + rLength) % 3)) { + midDelimTotal += rLength; + continue; // CommonMark Emphasis Rules 9-10 + } + } + delimTotal -= rLength; + if (delimTotal > 0) + continue; // Haven't found enough closing delimiters + // Remove extra characters. *a*** -> *a* + rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal); + // char length can be >1 for unicode characters; + const lastCharLength = [...match[0]][0].length; + const raw = src.slice(0, lLength + match.index + lastCharLength + rLength); + // Create `em` if smallest delimiter has odd char count. *a*** + if (Math.min(lLength, rLength) % 2) { + const text = raw.slice(1, -1); + return { + type: 'em', + raw, + text, + tokens: this.lexer.inlineTokens(text) + }; + } + // Create 'strong' if smallest delimiter has even char count. **a*** + const text = raw.slice(2, -2); + return { + type: 'strong', + raw, + text, + tokens: this.lexer.inlineTokens(text) + }; + } + } + } + codespan(src) { + const cap = this.rules.inline.code.exec(src); + if (cap) { + let text = cap[2].replace(/\n/g, ' '); + const hasNonSpaceChars = /[^ ]/.test(text); + const hasSpaceCharsOnBothEnds = /^ /.test(text) && / $/.test(text); + if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) { + text = text.substring(1, text.length - 1); + } + text = escape$1(text, true); + return { + type: 'codespan', + raw: cap[0], + text + }; + } + } + br(src) { + const cap = this.rules.inline.br.exec(src); + if (cap) { + return { + type: 'br', + raw: cap[0] + }; + } + } + del(src) { + const cap = this.rules.inline.del.exec(src); + if (cap) { + return { + type: 'del', + raw: cap[0], + text: cap[2], + tokens: this.lexer.inlineTokens(cap[2]) + }; + } + } + autolink(src) { + const cap = this.rules.inline.autolink.exec(src); + if (cap) { + let text, href; + if (cap[2] === '@') { + text = escape$1(cap[1]); + href = 'mailto:' + text; + } + else { + text = escape$1(cap[1]); + href = text; + } + return { + type: 'link', + raw: cap[0], + text, + href, + tokens: [ + { + type: 'text', + raw: text, + text + } + ] + }; + } + } + url(src) { + let cap; + if (cap = this.rules.inline.url.exec(src)) { + let text, href; + if (cap[2] === '@') { + text = escape$1(cap[0]); + href = 'mailto:' + text; + } + else { + // do extended autolink path validation + let prevCapZero; + do { + prevCapZero = cap[0]; + cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? ''; + } while (prevCapZero !== cap[0]); + text = escape$1(cap[0]); + if (cap[1] === 'www.') { + href = 'http://' + cap[0]; + } + else { + href = cap[0]; + } + } + return { + type: 'link', + raw: cap[0], + text, + href, + tokens: [ + { + type: 'text', + raw: text, + text + } + ] + }; + } + } + inlineText(src) { + const cap = this.rules.inline.text.exec(src); + if (cap) { + let text; + if (this.lexer.state.inRawBlock) { + text = cap[0]; + } + else { + text = escape$1(cap[0]); + } + return { + type: 'text', + raw: cap[0], + text + }; + } + } + } + + /** + * Block-Level Grammar + */ + const newline = /^(?: *(?:\n|$))+/; + const blockCode = /^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/; + const fences = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/; + const hr = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/; + const heading = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/; + const bullet = /(?:[*+-]|\d{1,9}[.)])/; + const lheading = edit(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/) + .replace(/bull/g, bullet) // lists can interrupt + .replace(/blockCode/g, / {4}/) // indented code blocks can interrupt + .replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/) // fenced code blocks can interrupt + .replace(/blockquote/g, / {0,3}>/) // blockquote can interrupt + .replace(/heading/g, / {0,3}#{1,6}/) // ATX heading can interrupt + .replace(/html/g, / {0,3}<[^\n>]+>\n/) // block html can interrupt + .getRegex(); + const _paragraph = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/; + const blockText = /^[^\n]+/; + const _blockLabel = /(?!\s*\])(?:\\.|[^\[\]\\])+/; + const def = edit(/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/) + .replace('label', _blockLabel) + .replace('title', /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/) + .getRegex(); + const list = edit(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/) + .replace(/bull/g, bullet) + .getRegex(); + const _tag = 'address|article|aside|base|basefont|blockquote|body|caption' + + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption' + + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe' + + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option' + + '|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title' + + '|tr|track|ul'; + const _comment = /|$))/; + const html = edit('^ {0,3}(?:' // optional indentation + + '<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)' // (1) + + '|comment[^\\n]*(\\n+|$)' // (2) + + '|<\\?[\\s\\S]*?(?:\\?>\\n*|$)' // (3) + + '|\\n*|$)' // (4) + + '|\\n*|$)' // (5) + + '|)[\\s\\S]*?(?:(?:\\n *)+\\n|$)' // (6) + + '|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)' // (7) open tag + + '|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)' // (7) closing tag + + ')', 'i') + .replace('comment', _comment) + .replace('tag', _tag) + .replace('attribute', / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/) + .getRegex(); + const paragraph = edit(_paragraph) + .replace('hr', hr) + .replace('heading', ' {0,3}#{1,6}(?:\\s|$)') + .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs + .replace('|table', '') + .replace('blockquote', ' {0,3}>') + .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n') + .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt + .replace('html', ')|<(?:script|pre|style|textarea|!--)') + .replace('tag', _tag) // pars can be interrupted by type (6) html blocks + .getRegex(); + const blockquote = edit(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/) + .replace('paragraph', paragraph) + .getRegex(); + /** + * Normal Block Grammar + */ + const blockNormal = { + blockquote, + code: blockCode, + def, + fences, + heading, + hr, + html, + lheading, + list, + newline, + paragraph, + table: noopTest, + text: blockText + }; + /** + * GFM Block Grammar + */ + const gfmTable = edit('^ *([^\\n ].*)\\n' // Header + + ' {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)' // Align + + '(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)') // Cells + .replace('hr', hr) + .replace('heading', ' {0,3}#{1,6}(?:\\s|$)') + .replace('blockquote', ' {0,3}>') + .replace('code', ' {4}[^\\n]') + .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n') + .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt + .replace('html', ')|<(?:script|pre|style|textarea|!--)') + .replace('tag', _tag) // tables can be interrupted by type (6) html blocks + .getRegex(); + const blockGfm = { + ...blockNormal, + table: gfmTable, + paragraph: edit(_paragraph) + .replace('hr', hr) + .replace('heading', ' {0,3}#{1,6}(?:\\s|$)') + .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs + .replace('table', gfmTable) // interrupt paragraphs with table + .replace('blockquote', ' {0,3}>') + .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n') + .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt + .replace('html', ')|<(?:script|pre|style|textarea|!--)') + .replace('tag', _tag) // pars can be interrupted by type (6) html blocks + .getRegex() + }; + /** + * Pedantic grammar (original John Gruber's loose markdown specification) + */ + const blockPedantic = { + ...blockNormal, + html: edit('^ *(?:comment *(?:\\n|\\s*$)' + + '|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)' // closed tag + + '|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))') + .replace('comment', _comment) + .replace(/tag/g, '(?!(?:' + + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub' + + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)' + + '\\b)\\w+(?!:|[^\\w\\s@]*@)\\b') + .getRegex(), + def: /^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/, + heading: /^(#{1,6})(.*)(?:\n+|$)/, + fences: noopTest, // fences not supported + lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/, + paragraph: edit(_paragraph) + .replace('hr', hr) + .replace('heading', ' *#{1,6} *[^\n]') + .replace('lheading', lheading) + .replace('|table', '') + .replace('blockquote', ' {0,3}>') + .replace('|fences', '') + .replace('|list', '') + .replace('|html', '') + .replace('|tag', '') + .getRegex() + }; + /** + * Inline-Level Grammar + */ + const escape = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/; + const inlineCode = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/; + const br = /^( {2,}|\\)\n(?!\s*$)/; + const inlineText = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\ + const blockSkip = /\[[^[\]]*?\]\([^\(\)]*?\)|`[^`]*?`|<[^<>]*?>/g; + const emStrongLDelim = edit(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/, 'u') + .replace(/punct/g, _punctuation) + .getRegex(); + const emStrongRDelimAst = edit('^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)' // Skip orphan inside strong + + '|[^*]+(?=[^*])' // Consume to delim + + '|(?!\\*)[punct](\\*+)(?=[\\s]|$)' // (1) #*** can only be a Right Delimiter + + '|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)' // (2) a***#, a*** can only be a Right Delimiter + + '|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])' // (3) #***a, ***a can only be Left Delimiter + + '|[\\s](\\*+)(?!\\*)(?=[punct])' // (4) ***# can only be Left Delimiter + + '|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])' // (5) #***# can be either Left or Right Delimiter + + '|[^punct\\s](\\*+)(?=[^punct\\s])', 'gu') // (6) a***a can be either Left or Right Delimiter + .replace(/punct/g, _punctuation) + .getRegex(); + // (6) Not allowed for _ + const emStrongRDelimUnd = edit('^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)' // Skip orphan inside strong + + '|[^_]+(?=[^_])' // Consume to delim + + '|(?!_)[punct](_+)(?=[\\s]|$)' // (1) #___ can only be a Right Delimiter + + '|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)' // (2) a___#, a___ can only be a Right Delimiter + + '|(?!_)[punct\\s](_+)(?=[^punct\\s])' // (3) #___a, ___a can only be Left Delimiter + + '|[\\s](_+)(?!_)(?=[punct])' // (4) ___# can only be Left Delimiter + + '|(?!_)[punct](_+)(?!_)(?=[punct])', 'gu') // (5) #___# can be either Left or Right Delimiter + .replace(/punct/g, _punctuation) + .getRegex(); + const anyPunctuation = edit(/\\([punct])/, 'gu') + .replace(/punct/g, _punctuation) + .getRegex(); + const autolink = edit(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/) + .replace('scheme', /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/) + .replace('email', /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/) + .getRegex(); + const _inlineComment = edit(_comment).replace('(?:-->|$)', '-->').getRegex(); + const tag = edit('^comment' + + '|^' // self-closing tag + + '|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>' // open tag + + '|^<\\?[\\s\\S]*?\\?>' // processing instruction, e.g. + + '|^' // declaration, e.g. + + '|^') // CDATA section + .replace('comment', _inlineComment) + .replace('attribute', /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/) + .getRegex(); + const _inlineLabel = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/; + const link = edit(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/) + .replace('label', _inlineLabel) + .replace('href', /<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/) + .replace('title', /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/) + .getRegex(); + const reflink = edit(/^!?\[(label)\]\[(ref)\]/) + .replace('label', _inlineLabel) + .replace('ref', _blockLabel) + .getRegex(); + const nolink = edit(/^!?\[(ref)\](?:\[\])?/) + .replace('ref', _blockLabel) + .getRegex(); + const reflinkSearch = edit('reflink|nolink(?!\\()', 'g') + .replace('reflink', reflink) + .replace('nolink', nolink) + .getRegex(); + /** + * Normal Inline Grammar + */ + const inlineNormal = { + _backpedal: noopTest, // only used for GFM url + anyPunctuation, + autolink, + blockSkip, + br, + code: inlineCode, + del: noopTest, + emStrongLDelim, + emStrongRDelimAst, + emStrongRDelimUnd, + escape, + link, + nolink, + punctuation, + reflink, + reflinkSearch, + tag, + text: inlineText, + url: noopTest + }; + /** + * Pedantic Inline Grammar + */ + const inlinePedantic = { + ...inlineNormal, + link: edit(/^!?\[(label)\]\((.*?)\)/) + .replace('label', _inlineLabel) + .getRegex(), + reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/) + .replace('label', _inlineLabel) + .getRegex() + }; + /** + * GFM Inline Grammar + */ + const inlineGfm = { + ...inlineNormal, + escape: edit(escape).replace('])', '~|])').getRegex(), + url: edit(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/, 'i') + .replace('email', /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/) + .getRegex(), + _backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/, + del: /^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/, + text: /^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\ { + return leading + ' '.repeat(tabs.length); + }); + } + let token; + let lastToken; + let cutSrc; + while (src) { + if (this.options.extensions + && this.options.extensions.block + && this.options.extensions.block.some((extTokenizer) => { + if (token = extTokenizer.call({ lexer: this }, src, tokens)) { + src = src.substring(token.raw.length); + tokens.push(token); + return true; + } + return false; + })) { + continue; + } + // newline + if (token = this.tokenizer.space(src)) { + src = src.substring(token.raw.length); + if (token.raw.length === 1 && tokens.length > 0) { + // if there's a single \n as a spacer, it's terminating the last line, + // so move it there so that we don't get unnecessary paragraph tags + tokens[tokens.length - 1].raw += '\n'; + } + else { + tokens.push(token); + } + continue; + } + // code + if (token = this.tokenizer.code(src)) { + src = src.substring(token.raw.length); + lastToken = tokens[tokens.length - 1]; + // An indented code block cannot interrupt a paragraph. + if (lastToken && (lastToken.type === 'paragraph' || lastToken.type === 'text')) { + lastToken.raw += '\n' + token.raw; + lastToken.text += '\n' + token.text; + this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text; + } + else { + tokens.push(token); + } + continue; + } + // fences + if (token = this.tokenizer.fences(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // heading + if (token = this.tokenizer.heading(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // hr + if (token = this.tokenizer.hr(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // blockquote + if (token = this.tokenizer.blockquote(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // list + if (token = this.tokenizer.list(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // html + if (token = this.tokenizer.html(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // def + if (token = this.tokenizer.def(src)) { + src = src.substring(token.raw.length); + lastToken = tokens[tokens.length - 1]; + if (lastToken && (lastToken.type === 'paragraph' || lastToken.type === 'text')) { + lastToken.raw += '\n' + token.raw; + lastToken.text += '\n' + token.raw; + this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text; + } + else if (!this.tokens.links[token.tag]) { + this.tokens.links[token.tag] = { + href: token.href, + title: token.title + }; + } + continue; + } + // table (gfm) + if (token = this.tokenizer.table(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // lheading + if (token = this.tokenizer.lheading(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // top-level paragraph + // prevent paragraph consuming extensions by clipping 'src' to extension start + cutSrc = src; + if (this.options.extensions && this.options.extensions.startBlock) { + let startIndex = Infinity; + const tempSrc = src.slice(1); + let tempStart; + this.options.extensions.startBlock.forEach((getStartIndex) => { + tempStart = getStartIndex.call({ lexer: this }, tempSrc); + if (typeof tempStart === 'number' && tempStart >= 0) { + startIndex = Math.min(startIndex, tempStart); + } + }); + if (startIndex < Infinity && startIndex >= 0) { + cutSrc = src.substring(0, startIndex + 1); + } + } + if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) { + lastToken = tokens[tokens.length - 1]; + if (lastParagraphClipped && lastToken?.type === 'paragraph') { + lastToken.raw += '\n' + token.raw; + lastToken.text += '\n' + token.text; + this.inlineQueue.pop(); + this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text; + } + else { + tokens.push(token); + } + lastParagraphClipped = (cutSrc.length !== src.length); + src = src.substring(token.raw.length); + continue; + } + // text + if (token = this.tokenizer.text(src)) { + src = src.substring(token.raw.length); + lastToken = tokens[tokens.length - 1]; + if (lastToken && lastToken.type === 'text') { + lastToken.raw += '\n' + token.raw; + lastToken.text += '\n' + token.text; + this.inlineQueue.pop(); + this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text; + } + else { + tokens.push(token); + } + continue; + } + if (src) { + const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0); + if (this.options.silent) { + console.error(errMsg); + break; + } + else { + throw new Error(errMsg); + } + } + } + this.state.top = true; + return tokens; + } + inline(src, tokens = []) { + this.inlineQueue.push({ src, tokens }); + return tokens; + } + /** + * Lexing/Compiling + */ + inlineTokens(src, tokens = []) { + let token, lastToken, cutSrc; + // String with links masked to avoid interference with em and strong + let maskedSrc = src; + let match; + let keepPrevChar, prevChar; + // Mask out reflinks + if (this.tokens.links) { + const links = Object.keys(this.tokens.links); + if (links.length > 0) { + while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) { + if (links.includes(match[0].slice(match[0].lastIndexOf('[') + 1, -1))) { + maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex); + } + } + } + } + // Mask out other blocks + while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) { + maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex); + } + // Mask out escaped characters + while ((match = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) != null) { + maskedSrc = maskedSrc.slice(0, match.index) + '++' + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex); + } + while (src) { + if (!keepPrevChar) { + prevChar = ''; + } + keepPrevChar = false; + // extensions + if (this.options.extensions + && this.options.extensions.inline + && this.options.extensions.inline.some((extTokenizer) => { + if (token = extTokenizer.call({ lexer: this }, src, tokens)) { + src = src.substring(token.raw.length); + tokens.push(token); + return true; + } + return false; + })) { + continue; + } + // escape + if (token = this.tokenizer.escape(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // tag + if (token = this.tokenizer.tag(src)) { + src = src.substring(token.raw.length); + lastToken = tokens[tokens.length - 1]; + if (lastToken && token.type === 'text' && lastToken.type === 'text') { + lastToken.raw += token.raw; + lastToken.text += token.text; + } + else { + tokens.push(token); + } + continue; + } + // link + if (token = this.tokenizer.link(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // reflink, nolink + if (token = this.tokenizer.reflink(src, this.tokens.links)) { + src = src.substring(token.raw.length); + lastToken = tokens[tokens.length - 1]; + if (lastToken && token.type === 'text' && lastToken.type === 'text') { + lastToken.raw += token.raw; + lastToken.text += token.text; + } + else { + tokens.push(token); + } + continue; + } + // em & strong + if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // code + if (token = this.tokenizer.codespan(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // br + if (token = this.tokenizer.br(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // del (gfm) + if (token = this.tokenizer.del(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // autolink + if (token = this.tokenizer.autolink(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // url (gfm) + if (!this.state.inLink && (token = this.tokenizer.url(src))) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + // text + // prevent inlineText consuming extensions by clipping 'src' to extension start + cutSrc = src; + if (this.options.extensions && this.options.extensions.startInline) { + let startIndex = Infinity; + const tempSrc = src.slice(1); + let tempStart; + this.options.extensions.startInline.forEach((getStartIndex) => { + tempStart = getStartIndex.call({ lexer: this }, tempSrc); + if (typeof tempStart === 'number' && tempStart >= 0) { + startIndex = Math.min(startIndex, tempStart); + } + }); + if (startIndex < Infinity && startIndex >= 0) { + cutSrc = src.substring(0, startIndex + 1); + } + } + if (token = this.tokenizer.inlineText(cutSrc)) { + src = src.substring(token.raw.length); + if (token.raw.slice(-1) !== '_') { // Track prevChar before string of ____ started + prevChar = token.raw.slice(-1); + } + keepPrevChar = true; + lastToken = tokens[tokens.length - 1]; + if (lastToken && lastToken.type === 'text') { + lastToken.raw += token.raw; + lastToken.text += token.text; + } + else { + tokens.push(token); + } + continue; + } + if (src) { + const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0); + if (this.options.silent) { + console.error(errMsg); + break; + } + else { + throw new Error(errMsg); + } + } + } + return tokens; + } + } + + /** + * Renderer + */ + class _Renderer { + options; + parser; // set by the parser + constructor(options) { + this.options = options || exports.defaults; + } + space(token) { + return ''; + } + code({ text, lang, escaped }) { + const langString = (lang || '').match(/^\S*/)?.[0]; + const code = text.replace(/\n$/, '') + '\n'; + if (!langString) { + return '
    '
    +                    + (escaped ? code : escape$1(code, true))
    +                    + '
    \n'; + } + return '
    '
    +                + (escaped ? code : escape$1(code, true))
    +                + '
    \n'; + } + blockquote({ tokens }) { + const body = this.parser.parse(tokens); + return `
    \n${body}
    \n`; + } + html({ text }) { + return text; + } + heading({ tokens, depth }) { + return `${this.parser.parseInline(tokens)}\n`; + } + hr(token) { + return '
    \n'; + } + list(token) { + const ordered = token.ordered; + const start = token.start; + let body = ''; + for (let j = 0; j < token.items.length; j++) { + const item = token.items[j]; + body += this.listitem(item); + } + const type = ordered ? 'ol' : 'ul'; + const startAttr = (ordered && start !== 1) ? (' start="' + start + '"') : ''; + return '<' + type + startAttr + '>\n' + body + '\n'; + } + listitem(item) { + let itemBody = ''; + if (item.task) { + const checkbox = this.checkbox({ checked: !!item.checked }); + if (item.loose) { + if (item.tokens.length > 0 && item.tokens[0].type === 'paragraph') { + item.tokens[0].text = checkbox + ' ' + item.tokens[0].text; + if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') { + item.tokens[0].tokens[0].text = checkbox + ' ' + item.tokens[0].tokens[0].text; + } + } + else { + item.tokens.unshift({ + type: 'text', + raw: checkbox + ' ', + text: checkbox + ' ' + }); + } + } + else { + itemBody += checkbox + ' '; + } + } + itemBody += this.parser.parse(item.tokens, !!item.loose); + return `
  • ${itemBody}
  • \n`; + } + checkbox({ checked }) { + return ''; + } + paragraph({ tokens }) { + return `

    ${this.parser.parseInline(tokens)}

    \n`; + } + table(token) { + let header = ''; + // header + let cell = ''; + for (let j = 0; j < token.header.length; j++) { + cell += this.tablecell(token.header[j]); + } + header += this.tablerow({ text: cell }); + let body = ''; + for (let j = 0; j < token.rows.length; j++) { + const row = token.rows[j]; + cell = ''; + for (let k = 0; k < row.length; k++) { + cell += this.tablecell(row[k]); + } + body += this.tablerow({ text: cell }); + } + if (body) + body = `${body}`; + return '\n' + + '\n' + + header + + '\n' + + body + + '
    \n'; + } + tablerow({ text }) { + return `\n${text}\n`; + } + tablecell(token) { + const content = this.parser.parseInline(token.tokens); + const type = token.header ? 'th' : 'td'; + const tag = token.align + ? `<${type} align="${token.align}">` + : `<${type}>`; + return tag + content + `\n`; + } + /** + * span level renderer + */ + strong({ tokens }) { + return `${this.parser.parseInline(tokens)}`; + } + em({ tokens }) { + return `${this.parser.parseInline(tokens)}`; + } + codespan({ text }) { + return `${text}`; + } + br(token) { + return '
    '; + } + del({ tokens }) { + return `${this.parser.parseInline(tokens)}`; + } + link({ href, title, tokens }) { + const text = this.parser.parseInline(tokens); + const cleanHref = cleanUrl(href); + if (cleanHref === null) { + return text; + } + href = cleanHref; + let out = '
    '; + return out; + } + image({ href, title, text }) { + const cleanHref = cleanUrl(href); + if (cleanHref === null) { + return text; + } + href = cleanHref; + let out = `${text} { + const tokens = genericToken[childTokens].flat(Infinity); + values = values.concat(this.walkTokens(tokens, callback)); + }); + } + else if (genericToken.tokens) { + values = values.concat(this.walkTokens(genericToken.tokens, callback)); + } + } + } + } + return values; + } + use(...args) { + const extensions = this.defaults.extensions || { renderers: {}, childTokens: {} }; + args.forEach((pack) => { + // copy options to new object + const opts = { ...pack }; + // set async to true if it was set to true before + opts.async = this.defaults.async || opts.async || false; + // ==-- Parse "addon" extensions --== // + if (pack.extensions) { + pack.extensions.forEach((ext) => { + if (!ext.name) { + throw new Error('extension name required'); + } + if ('renderer' in ext) { // Renderer extensions + const prevRenderer = extensions.renderers[ext.name]; + if (prevRenderer) { + // Replace extension with func to run new extension but fall back if false + extensions.renderers[ext.name] = function (...args) { + let ret = ext.renderer.apply(this, args); + if (ret === false) { + ret = prevRenderer.apply(this, args); + } + return ret; + }; + } + else { + extensions.renderers[ext.name] = ext.renderer; + } + } + if ('tokenizer' in ext) { // Tokenizer Extensions + if (!ext.level || (ext.level !== 'block' && ext.level !== 'inline')) { + throw new Error("extension level must be 'block' or 'inline'"); + } + const extLevel = extensions[ext.level]; + if (extLevel) { + extLevel.unshift(ext.tokenizer); + } + else { + extensions[ext.level] = [ext.tokenizer]; + } + if (ext.start) { // Function to check for start of token + if (ext.level === 'block') { + if (extensions.startBlock) { + extensions.startBlock.push(ext.start); + } + else { + extensions.startBlock = [ext.start]; + } + } + else if (ext.level === 'inline') { + if (extensions.startInline) { + extensions.startInline.push(ext.start); + } + else { + extensions.startInline = [ext.start]; + } + } + } + } + if ('childTokens' in ext && ext.childTokens) { // Child tokens to be visited by walkTokens + extensions.childTokens[ext.name] = ext.childTokens; + } + }); + opts.extensions = extensions; + } + // ==-- Parse "overwrite" extensions --== // + if (pack.renderer) { + const renderer = this.defaults.renderer || new _Renderer(this.defaults); + for (const prop in pack.renderer) { + if (!(prop in renderer)) { + throw new Error(`renderer '${prop}' does not exist`); + } + if (['options', 'parser'].includes(prop)) { + // ignore options property + continue; + } + const rendererProp = prop; + let rendererFunc = pack.renderer[rendererProp]; + const prevRenderer = renderer[rendererProp]; + // Replace renderer with func to run extension, but fall back if false + renderer[rendererProp] = (...args) => { + if (!pack.useNewRenderer) { + // TODO: Remove this in next major version + rendererFunc = this.#convertRendererFunction(rendererFunc, rendererProp, renderer); + } + let ret = rendererFunc.apply(renderer, args); + if (ret === false) { + ret = prevRenderer.apply(renderer, args); + } + return ret || ''; + }; + } + opts.renderer = renderer; + } + if (pack.tokenizer) { + const tokenizer = this.defaults.tokenizer || new _Tokenizer(this.defaults); + for (const prop in pack.tokenizer) { + if (!(prop in tokenizer)) { + throw new Error(`tokenizer '${prop}' does not exist`); + } + if (['options', 'rules', 'lexer'].includes(prop)) { + // ignore options, rules, and lexer properties + continue; + } + const tokenizerProp = prop; + const tokenizerFunc = pack.tokenizer[tokenizerProp]; + const prevTokenizer = tokenizer[tokenizerProp]; + // Replace tokenizer with func to run extension, but fall back if false + // @ts-expect-error cannot type tokenizer function dynamically + tokenizer[tokenizerProp] = (...args) => { + let ret = tokenizerFunc.apply(tokenizer, args); + if (ret === false) { + ret = prevTokenizer.apply(tokenizer, args); + } + return ret; + }; + } + opts.tokenizer = tokenizer; + } + // ==-- Parse Hooks extensions --== // + if (pack.hooks) { + const hooks = this.defaults.hooks || new _Hooks(); + for (const prop in pack.hooks) { + if (!(prop in hooks)) { + throw new Error(`hook '${prop}' does not exist`); + } + if (prop === 'options') { + // ignore options property + continue; + } + const hooksProp = prop; + const hooksFunc = pack.hooks[hooksProp]; + const prevHook = hooks[hooksProp]; + if (_Hooks.passThroughHooks.has(prop)) { + // @ts-expect-error cannot type hook function dynamically + hooks[hooksProp] = (arg) => { + if (this.defaults.async) { + return Promise.resolve(hooksFunc.call(hooks, arg)).then(ret => { + return prevHook.call(hooks, ret); + }); + } + const ret = hooksFunc.call(hooks, arg); + return prevHook.call(hooks, ret); + }; + } + else { + // @ts-expect-error cannot type hook function dynamically + hooks[hooksProp] = (...args) => { + let ret = hooksFunc.apply(hooks, args); + if (ret === false) { + ret = prevHook.apply(hooks, args); + } + return ret; + }; + } + } + opts.hooks = hooks; + } + // ==-- Parse WalkTokens extensions --== // + if (pack.walkTokens) { + const walkTokens = this.defaults.walkTokens; + const packWalktokens = pack.walkTokens; + opts.walkTokens = function (token) { + let values = []; + values.push(packWalktokens.call(this, token)); + if (walkTokens) { + values = values.concat(walkTokens.call(this, token)); + } + return values; + }; + } + this.defaults = { ...this.defaults, ...opts }; + }); + return this; + } + // TODO: Remove this in next major release + #convertRendererFunction(func, prop, renderer) { + switch (prop) { + case 'heading': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + return func.call(this, renderer.parser.parseInline(token.tokens), token.depth, unescape(renderer.parser.parseInline(token.tokens, renderer.parser.textRenderer))); + }; + case 'code': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + return func.call(this, token.text, token.lang, !!token.escaped); + }; + case 'table': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + let header = ''; + // header + let cell = ''; + for (let j = 0; j < token.header.length; j++) { + cell += this.tablecell({ + text: token.header[j].text, + tokens: token.header[j].tokens, + header: true, + align: token.align[j] + }); + } + header += this.tablerow({ text: cell }); + let body = ''; + for (let j = 0; j < token.rows.length; j++) { + const row = token.rows[j]; + cell = ''; + for (let k = 0; k < row.length; k++) { + cell += this.tablecell({ + text: row[k].text, + tokens: row[k].tokens, + header: false, + align: token.align[k] + }); + } + body += this.tablerow({ text: cell }); + } + return func.call(this, header, body); + }; + case 'blockquote': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + const body = this.parser.parse(token.tokens); + return func.call(this, body); + }; + case 'list': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + const ordered = token.ordered; + const start = token.start; + const loose = token.loose; + let body = ''; + for (let j = 0; j < token.items.length; j++) { + const item = token.items[j]; + const checked = item.checked; + const task = item.task; + let itemBody = ''; + if (item.task) { + const checkbox = this.checkbox({ checked: !!checked }); + if (loose) { + if (item.tokens.length > 0 && item.tokens[0].type === 'paragraph') { + item.tokens[0].text = checkbox + ' ' + item.tokens[0].text; + if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') { + item.tokens[0].tokens[0].text = checkbox + ' ' + item.tokens[0].tokens[0].text; + } + } + else { + item.tokens.unshift({ + type: 'text', + text: checkbox + ' ' + }); + } + } + else { + itemBody += checkbox + ' '; + } + } + itemBody += this.parser.parse(item.tokens, loose); + body += this.listitem({ + type: 'list_item', + raw: itemBody, + text: itemBody, + task, + checked: !!checked, + loose, + tokens: item.tokens + }); + } + return func.call(this, body, ordered, start); + }; + case 'html': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + return func.call(this, token.text, token.block); + }; + case 'paragraph': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + return func.call(this, this.parser.parseInline(token.tokens)); + }; + case 'escape': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + return func.call(this, token.text); + }; + case 'link': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + return func.call(this, token.href, token.title, this.parser.parseInline(token.tokens)); + }; + case 'image': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + return func.call(this, token.href, token.title, token.text); + }; + case 'strong': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + return func.call(this, this.parser.parseInline(token.tokens)); + }; + case 'em': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + return func.call(this, this.parser.parseInline(token.tokens)); + }; + case 'codespan': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + return func.call(this, token.text); + }; + case 'del': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + return func.call(this, this.parser.parseInline(token.tokens)); + }; + case 'text': + return function (token) { + if (!token.type || token.type !== prop) { + // @ts-ignore + // eslint-disable-next-line prefer-rest-params + return func.apply(this, arguments); + } + return func.call(this, token.text); + }; + // do nothing + } + return func; + } + setOptions(opt) { + this.defaults = { ...this.defaults, ...opt }; + return this; + } + lexer(src, options) { + return _Lexer.lex(src, options ?? this.defaults); + } + parser(tokens, options) { + return _Parser.parse(tokens, options ?? this.defaults); + } + #parseMarkdown(lexer, parser) { + return (src, options) => { + const origOpt = { ...options }; + const opt = { ...this.defaults, ...origOpt }; + // Show warning if an extension set async to true but the parse was called with async: false + if (this.defaults.async === true && origOpt.async === false) { + if (!opt.silent) { + console.warn('marked(): The async option was set to true by an extension. The async: false option sent to parse will be ignored.'); + } + opt.async = true; + } + const throwError = this.#onError(!!opt.silent, !!opt.async); + // throw error in case of non string input + if (typeof src === 'undefined' || src === null) { + return throwError(new Error('marked(): input parameter is undefined or null')); + } + if (typeof src !== 'string') { + return throwError(new Error('marked(): input parameter is of type ' + + Object.prototype.toString.call(src) + ', string expected')); + } + if (opt.hooks) { + opt.hooks.options = opt; + } + if (opt.async) { + return Promise.resolve(opt.hooks ? opt.hooks.preprocess(src) : src) + .then(src => lexer(src, opt)) + .then(tokens => opt.hooks ? opt.hooks.processAllTokens(tokens) : tokens) + .then(tokens => opt.walkTokens ? Promise.all(this.walkTokens(tokens, opt.walkTokens)).then(() => tokens) : tokens) + .then(tokens => parser(tokens, opt)) + .then(html => opt.hooks ? opt.hooks.postprocess(html) : html) + .catch(throwError); + } + try { + if (opt.hooks) { + src = opt.hooks.preprocess(src); + } + let tokens = lexer(src, opt); + if (opt.hooks) { + tokens = opt.hooks.processAllTokens(tokens); + } + if (opt.walkTokens) { + this.walkTokens(tokens, opt.walkTokens); + } + let html = parser(tokens, opt); + if (opt.hooks) { + html = opt.hooks.postprocess(html); + } + return html; + } + catch (e) { + return throwError(e); + } + }; + } + #onError(silent, async) { + return (e) => { + e.message += '\nPlease report this to https://github.com/markedjs/marked.'; + if (silent) { + const msg = '

    An error occurred:

    '
    +                        + escape$1(e.message + '', true)
    +                        + '
    '; + if (async) { + return Promise.resolve(msg); + } + return msg; + } + if (async) { + return Promise.reject(e); + } + throw e; + }; + } + } + + const markedInstance = new Marked(); + function marked(src, opt) { + return markedInstance.parse(src, opt); + } + /** + * Sets the default options. + * + * @param options Hash of options + */ + marked.options = + marked.setOptions = function (options) { + markedInstance.setOptions(options); + marked.defaults = markedInstance.defaults; + changeDefaults(marked.defaults); + return marked; + }; + /** + * Gets the original marked default options. + */ + marked.getDefaults = _getDefaults; + marked.defaults = exports.defaults; + /** + * Use Extension + */ + marked.use = function (...args) { + markedInstance.use(...args); + marked.defaults = markedInstance.defaults; + changeDefaults(marked.defaults); + return marked; + }; + /** + * Run callback for every token + */ + marked.walkTokens = function (tokens, callback) { + return markedInstance.walkTokens(tokens, callback); + }; + /** + * Compiles markdown to HTML without enclosing `p` tag. + * + * @param src String of markdown source to be compiled + * @param options Hash of options + * @return String of compiled HTML + */ + marked.parseInline = markedInstance.parseInline; + /** + * Expose + */ + marked.Parser = _Parser; + marked.parser = _Parser.parse; + marked.Renderer = _Renderer; + marked.TextRenderer = _TextRenderer; + marked.Lexer = _Lexer; + marked.lexer = _Lexer.lex; + marked.Tokenizer = _Tokenizer; + marked.Hooks = _Hooks; + marked.parse = marked; + const options = marked.options; + const setOptions = marked.setOptions; + const use = marked.use; + const walkTokens = marked.walkTokens; + const parseInline = marked.parseInline; + const parse = marked; + const parser = _Parser.parse; + const lexer = _Lexer.lex; + + exports.Hooks = _Hooks; + exports.Lexer = _Lexer; + exports.Marked = Marked; + exports.Parser = _Parser; + exports.Renderer = _Renderer; + exports.TextRenderer = _TextRenderer; + exports.Tokenizer = _Tokenizer; + exports.getDefaults = _getDefaults; + exports.lexer = lexer; + exports.marked = marked; + exports.options = options; + exports.parse = parse; + exports.parseInline = parseInline; + exports.parser = parser; + exports.setOptions = setOptions; + exports.use = use; + exports.walkTokens = walkTokens; + +})); +//# sourceMappingURL=marked.umd.js.map diff --git a/scripts/node_modules/marked/lib/marked.umd.js.map b/scripts/node_modules/marked/lib/marked.umd.js.map new file mode 100644 index 000000000..18dd3e956 --- /dev/null +++ b/scripts/node_modules/marked/lib/marked.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"marked.umd.js","sources":["../src/defaults.ts","../src/helpers.ts","../src/Tokenizer.ts","../src/rules.ts","../src/Lexer.ts","../src/Renderer.ts","../src/TextRenderer.ts","../src/Parser.ts","../src/Hooks.ts","../src/Instance.ts","../src/marked.ts"],"sourcesContent":["/**\n * Gets the original marked default options.\n */\nexport function _getDefaults() {\n return {\n async: false,\n breaks: false,\n extensions: null,\n gfm: true,\n hooks: null,\n pedantic: false,\n renderer: null,\n silent: false,\n tokenizer: null,\n walkTokens: null\n };\n}\nexport let _defaults = _getDefaults();\nexport function changeDefaults(newDefaults) {\n _defaults = newDefaults;\n}\n","/**\n * Helpers\n */\nconst escapeTest = /[&<>\"']/;\nconst escapeReplace = new RegExp(escapeTest.source, 'g');\nconst escapeTestNoEncode = /[<>\"']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/;\nconst escapeReplaceNoEncode = new RegExp(escapeTestNoEncode.source, 'g');\nconst escapeReplacements = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": '''\n};\nconst getEscapeReplacement = (ch) => escapeReplacements[ch];\nexport function escape(html, encode) {\n if (encode) {\n if (escapeTest.test(html)) {\n return html.replace(escapeReplace, getEscapeReplacement);\n }\n }\n else {\n if (escapeTestNoEncode.test(html)) {\n return html.replace(escapeReplaceNoEncode, getEscapeReplacement);\n }\n }\n return html;\n}\nconst unescapeTest = /&(#(?:\\d+)|(?:#x[0-9A-Fa-f]+)|(?:\\w+));?/ig;\nexport function unescape(html) {\n // explicitly match decimal, hex, and named HTML entities\n return html.replace(unescapeTest, (_, n) => {\n n = n.toLowerCase();\n if (n === 'colon')\n return ':';\n if (n.charAt(0) === '#') {\n return n.charAt(1) === 'x'\n ? String.fromCharCode(parseInt(n.substring(2), 16))\n : String.fromCharCode(+n.substring(1));\n }\n return '';\n });\n}\nconst caret = /(^|[^\\[])\\^/g;\nexport function edit(regex, opt) {\n let source = typeof regex === 'string' ? regex : regex.source;\n opt = opt || '';\n const obj = {\n replace: (name, val) => {\n let valSource = typeof val === 'string' ? val : val.source;\n valSource = valSource.replace(caret, '$1');\n source = source.replace(name, valSource);\n return obj;\n },\n getRegex: () => {\n return new RegExp(source, opt);\n }\n };\n return obj;\n}\nexport function cleanUrl(href) {\n try {\n href = encodeURI(href).replace(/%25/g, '%');\n }\n catch (e) {\n return null;\n }\n return href;\n}\nexport const noopTest = { exec: () => null };\nexport function splitCells(tableRow, count) {\n // ensure that every cell-delimiting pipe has a space\n // before it to distinguish it from an escaped pipe\n const row = tableRow.replace(/\\|/g, (match, offset, str) => {\n let escaped = false;\n let curr = offset;\n while (--curr >= 0 && str[curr] === '\\\\')\n escaped = !escaped;\n if (escaped) {\n // odd number of slashes means | is escaped\n // so we leave it alone\n return '|';\n }\n else {\n // add space before unescaped |\n return ' |';\n }\n }), cells = row.split(/ \\|/);\n let i = 0;\n // First/last cell in a row cannot be empty if it has no leading/trailing pipe\n if (!cells[0].trim()) {\n cells.shift();\n }\n if (cells.length > 0 && !cells[cells.length - 1].trim()) {\n cells.pop();\n }\n if (count) {\n if (cells.length > count) {\n cells.splice(count);\n }\n else {\n while (cells.length < count)\n cells.push('');\n }\n }\n for (; i < cells.length; i++) {\n // leading or trailing whitespace is ignored per the gfm spec\n cells[i] = cells[i].trim().replace(/\\\\\\|/g, '|');\n }\n return cells;\n}\n/**\n * Remove trailing 'c's. Equivalent to str.replace(/c*$/, '').\n * /c*$/ is vulnerable to REDOS.\n *\n * @param str\n * @param c\n * @param invert Remove suffix of non-c chars instead. Default falsey.\n */\nexport function rtrim(str, c, invert) {\n const l = str.length;\n if (l === 0) {\n return '';\n }\n // Length of suffix matching the invert condition.\n let suffLen = 0;\n // Step left until we fail to match the invert condition.\n while (suffLen < l) {\n const currChar = str.charAt(l - suffLen - 1);\n if (currChar === c && !invert) {\n suffLen++;\n }\n else if (currChar !== c && invert) {\n suffLen++;\n }\n else {\n break;\n }\n }\n return str.slice(0, l - suffLen);\n}\nexport function findClosingBracket(str, b) {\n if (str.indexOf(b[1]) === -1) {\n return -1;\n }\n let level = 0;\n for (let i = 0; i < str.length; i++) {\n if (str[i] === '\\\\') {\n i++;\n }\n else if (str[i] === b[0]) {\n level++;\n }\n else if (str[i] === b[1]) {\n level--;\n if (level < 0) {\n return i;\n }\n }\n }\n return -1;\n}\n","import { _defaults } from './defaults.ts';\nimport { rtrim, splitCells, escape, findClosingBracket } from './helpers.ts';\nfunction outputLink(cap, link, raw, lexer) {\n const href = link.href;\n const title = link.title ? escape(link.title) : null;\n const text = cap[1].replace(/\\\\([\\[\\]])/g, '$1');\n if (cap[0].charAt(0) !== '!') {\n lexer.state.inLink = true;\n const token = {\n type: 'link',\n raw,\n href,\n title,\n text,\n tokens: lexer.inlineTokens(text)\n };\n lexer.state.inLink = false;\n return token;\n }\n return {\n type: 'image',\n raw,\n href,\n title,\n text: escape(text)\n };\n}\nfunction indentCodeCompensation(raw, text) {\n const matchIndentToCode = raw.match(/^(\\s+)(?:```)/);\n if (matchIndentToCode === null) {\n return text;\n }\n const indentToCode = matchIndentToCode[1];\n return text\n .split('\\n')\n .map(node => {\n const matchIndentInNode = node.match(/^\\s+/);\n if (matchIndentInNode === null) {\n return node;\n }\n const [indentInNode] = matchIndentInNode;\n if (indentInNode.length >= indentToCode.length) {\n return node.slice(indentToCode.length);\n }\n return node;\n })\n .join('\\n');\n}\n/**\n * Tokenizer\n */\nexport class _Tokenizer {\n options;\n rules; // set by the lexer\n lexer; // set by the lexer\n constructor(options) {\n this.options = options || _defaults;\n }\n space(src) {\n const cap = this.rules.block.newline.exec(src);\n if (cap && cap[0].length > 0) {\n return {\n type: 'space',\n raw: cap[0]\n };\n }\n }\n code(src) {\n const cap = this.rules.block.code.exec(src);\n if (cap) {\n const text = cap[0].replace(/^ {1,4}/gm, '');\n return {\n type: 'code',\n raw: cap[0],\n codeBlockStyle: 'indented',\n text: !this.options.pedantic\n ? rtrim(text, '\\n')\n : text\n };\n }\n }\n fences(src) {\n const cap = this.rules.block.fences.exec(src);\n if (cap) {\n const raw = cap[0];\n const text = indentCodeCompensation(raw, cap[3] || '');\n return {\n type: 'code',\n raw,\n lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, '$1') : cap[2],\n text\n };\n }\n }\n heading(src) {\n const cap = this.rules.block.heading.exec(src);\n if (cap) {\n let text = cap[2].trim();\n // remove trailing #s\n if (/#$/.test(text)) {\n const trimmed = rtrim(text, '#');\n if (this.options.pedantic) {\n text = trimmed.trim();\n }\n else if (!trimmed || / $/.test(trimmed)) {\n // CommonMark requires space before trailing #s\n text = trimmed.trim();\n }\n }\n return {\n type: 'heading',\n raw: cap[0],\n depth: cap[1].length,\n text,\n tokens: this.lexer.inline(text)\n };\n }\n }\n hr(src) {\n const cap = this.rules.block.hr.exec(src);\n if (cap) {\n return {\n type: 'hr',\n raw: rtrim(cap[0], '\\n')\n };\n }\n }\n blockquote(src) {\n const cap = this.rules.block.blockquote.exec(src);\n if (cap) {\n let lines = rtrim(cap[0], '\\n').split('\\n');\n let raw = '';\n let text = '';\n const tokens = [];\n while (lines.length > 0) {\n let inBlockquote = false;\n const currentLines = [];\n let i;\n for (i = 0; i < lines.length; i++) {\n // get lines up to a continuation\n if (/^ {0,3}>/.test(lines[i])) {\n currentLines.push(lines[i]);\n inBlockquote = true;\n }\n else if (!inBlockquote) {\n currentLines.push(lines[i]);\n }\n else {\n break;\n }\n }\n lines = lines.slice(i);\n const currentRaw = currentLines.join('\\n');\n const currentText = currentRaw\n // precede setext continuation with 4 spaces so it isn't a setext\n .replace(/\\n {0,3}((?:=+|-+) *)(?=\\n|$)/g, '\\n $1')\n .replace(/^ {0,3}>[ \\t]?/gm, '');\n raw = raw ? `${raw}\\n${currentRaw}` : currentRaw;\n text = text ? `${text}\\n${currentText}` : currentText;\n // parse blockquote lines as top level tokens\n // merge paragraphs if this is a continuation\n const top = this.lexer.state.top;\n this.lexer.state.top = true;\n this.lexer.blockTokens(currentText, tokens, true);\n this.lexer.state.top = top;\n // if there is no continuation then we are done\n if (lines.length === 0) {\n break;\n }\n const lastToken = tokens[tokens.length - 1];\n if (lastToken?.type === 'code') {\n // blockquote continuation cannot be preceded by a code block\n break;\n }\n else if (lastToken?.type === 'blockquote') {\n // include continuation in nested blockquote\n const oldToken = lastToken;\n const newText = oldToken.raw + '\\n' + lines.join('\\n');\n const newToken = this.blockquote(newText);\n tokens[tokens.length - 1] = newToken;\n raw = raw.substring(0, raw.length - oldToken.raw.length) + newToken.raw;\n text = text.substring(0, text.length - oldToken.text.length) + newToken.text;\n break;\n }\n else if (lastToken?.type === 'list') {\n // include continuation in nested list\n const oldToken = lastToken;\n const newText = oldToken.raw + '\\n' + lines.join('\\n');\n const newToken = this.list(newText);\n tokens[tokens.length - 1] = newToken;\n raw = raw.substring(0, raw.length - lastToken.raw.length) + newToken.raw;\n text = text.substring(0, text.length - oldToken.raw.length) + newToken.raw;\n lines = newText.substring(tokens[tokens.length - 1].raw.length).split('\\n');\n continue;\n }\n }\n return {\n type: 'blockquote',\n raw,\n tokens,\n text\n };\n }\n }\n list(src) {\n let cap = this.rules.block.list.exec(src);\n if (cap) {\n let bull = cap[1].trim();\n const isordered = bull.length > 1;\n const list = {\n type: 'list',\n raw: '',\n ordered: isordered,\n start: isordered ? +bull.slice(0, -1) : '',\n loose: false,\n items: []\n };\n bull = isordered ? `\\\\d{1,9}\\\\${bull.slice(-1)}` : `\\\\${bull}`;\n if (this.options.pedantic) {\n bull = isordered ? bull : '[*+-]';\n }\n // Get next list item\n const itemRegex = new RegExp(`^( {0,3}${bull})((?:[\\t ][^\\\\n]*)?(?:\\\\n|$))`);\n let raw = '';\n let itemContents = '';\n let endsWithBlankLine = false;\n // Check if current bullet point can start a new List Item\n while (src) {\n let endEarly = false;\n if (!(cap = itemRegex.exec(src))) {\n break;\n }\n if (this.rules.block.hr.test(src)) { // End list if bullet was actually HR (possibly move into itemRegex?)\n break;\n }\n raw = cap[0];\n src = src.substring(raw.length);\n let line = cap[2].split('\\n', 1)[0].replace(/^\\t+/, (t) => ' '.repeat(3 * t.length));\n let nextLine = src.split('\\n', 1)[0];\n let indent = 0;\n if (this.options.pedantic) {\n indent = 2;\n itemContents = line.trimStart();\n }\n else {\n indent = cap[2].search(/[^ ]/); // Find first non-space char\n indent = indent > 4 ? 1 : indent; // Treat indented code blocks (> 4 spaces) as having only 1 indent\n itemContents = line.slice(indent);\n indent += cap[1].length;\n }\n let blankLine = false;\n if (!line && /^ *$/.test(nextLine)) { // Items begin with at most one blank line\n raw += nextLine + '\\n';\n src = src.substring(nextLine.length + 1);\n endEarly = true;\n }\n if (!endEarly) {\n const nextBulletRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\\\d{1,9}[.)])((?:[ \\t][^\\\\n]*)?(?:\\\\n|$))`);\n const hrRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\\\* *){3,})(?:\\\\n+|$)`);\n const fencesBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\\`\\`\\`|~~~)`);\n const headingBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`);\n // Check if following lines should be included in List Item\n while (src) {\n const rawLine = src.split('\\n', 1)[0];\n nextLine = rawLine;\n // Re-align to follow commonmark nesting rules\n if (this.options.pedantic) {\n nextLine = nextLine.replace(/^ {1,4}(?=( {4})*[^ ])/g, ' ');\n }\n // End list item if found code fences\n if (fencesBeginRegex.test(nextLine)) {\n break;\n }\n // End list item if found start of new heading\n if (headingBeginRegex.test(nextLine)) {\n break;\n }\n // End list item if found start of new bullet\n if (nextBulletRegex.test(nextLine)) {\n break;\n }\n // Horizontal rule found\n if (hrRegex.test(src)) {\n break;\n }\n if (nextLine.search(/[^ ]/) >= indent || !nextLine.trim()) { // Dedent if possible\n itemContents += '\\n' + nextLine.slice(indent);\n }\n else {\n // not enough indentation\n if (blankLine) {\n break;\n }\n // paragraph continuation unless last line was a different block level element\n if (line.search(/[^ ]/) >= 4) { // indented code block\n break;\n }\n if (fencesBeginRegex.test(line)) {\n break;\n }\n if (headingBeginRegex.test(line)) {\n break;\n }\n if (hrRegex.test(line)) {\n break;\n }\n itemContents += '\\n' + nextLine;\n }\n if (!blankLine && !nextLine.trim()) { // Check if current line is blank\n blankLine = true;\n }\n raw += rawLine + '\\n';\n src = src.substring(rawLine.length + 1);\n line = nextLine.slice(indent);\n }\n }\n if (!list.loose) {\n // If the previous item ended with a blank line, the list is loose\n if (endsWithBlankLine) {\n list.loose = true;\n }\n else if (/\\n *\\n *$/.test(raw)) {\n endsWithBlankLine = true;\n }\n }\n let istask = null;\n let ischecked;\n // Check for task list items\n if (this.options.gfm) {\n istask = /^\\[[ xX]\\] /.exec(itemContents);\n if (istask) {\n ischecked = istask[0] !== '[ ] ';\n itemContents = itemContents.replace(/^\\[[ xX]\\] +/, '');\n }\n }\n list.items.push({\n type: 'list_item',\n raw,\n task: !!istask,\n checked: ischecked,\n loose: false,\n text: itemContents,\n tokens: []\n });\n list.raw += raw;\n }\n // Do not consume newlines at end of final item. Alternatively, make itemRegex *start* with any newlines to simplify/speed up endsWithBlankLine logic\n list.items[list.items.length - 1].raw = raw.trimEnd();\n (list.items[list.items.length - 1]).text = itemContents.trimEnd();\n list.raw = list.raw.trimEnd();\n // Item child tokens handled here at end because we needed to have the final item to trim it first\n for (let i = 0; i < list.items.length; i++) {\n this.lexer.state.top = false;\n list.items[i].tokens = this.lexer.blockTokens(list.items[i].text, []);\n if (!list.loose) {\n // Check if list should be loose\n const spacers = list.items[i].tokens.filter(t => t.type === 'space');\n const hasMultipleLineBreaks = spacers.length > 0 && spacers.some(t => /\\n.*\\n/.test(t.raw));\n list.loose = hasMultipleLineBreaks;\n }\n }\n // Set all items to loose if list is loose\n if (list.loose) {\n for (let i = 0; i < list.items.length; i++) {\n list.items[i].loose = true;\n }\n }\n return list;\n }\n }\n html(src) {\n const cap = this.rules.block.html.exec(src);\n if (cap) {\n const token = {\n type: 'html',\n block: true,\n raw: cap[0],\n pre: cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style',\n text: cap[0]\n };\n return token;\n }\n }\n def(src) {\n const cap = this.rules.block.def.exec(src);\n if (cap) {\n const tag = cap[1].toLowerCase().replace(/\\s+/g, ' ');\n const href = cap[2] ? cap[2].replace(/^<(.*)>$/, '$1').replace(this.rules.inline.anyPunctuation, '$1') : '';\n const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, '$1') : cap[3];\n return {\n type: 'def',\n tag,\n raw: cap[0],\n href,\n title\n };\n }\n }\n table(src) {\n const cap = this.rules.block.table.exec(src);\n if (!cap) {\n return;\n }\n if (!/[:|]/.test(cap[2])) {\n // delimiter row must have a pipe (|) or colon (:) otherwise it is a setext heading\n return;\n }\n const headers = splitCells(cap[1]);\n const aligns = cap[2].replace(/^\\||\\| *$/g, '').split('|');\n const rows = cap[3] && cap[3].trim() ? cap[3].replace(/\\n[ \\t]*$/, '').split('\\n') : [];\n const item = {\n type: 'table',\n raw: cap[0],\n header: [],\n align: [],\n rows: []\n };\n if (headers.length !== aligns.length) {\n // header and align columns must be equal, rows can be different.\n return;\n }\n for (const align of aligns) {\n if (/^ *-+: *$/.test(align)) {\n item.align.push('right');\n }\n else if (/^ *:-+: *$/.test(align)) {\n item.align.push('center');\n }\n else if (/^ *:-+ *$/.test(align)) {\n item.align.push('left');\n }\n else {\n item.align.push(null);\n }\n }\n for (let i = 0; i < headers.length; i++) {\n item.header.push({\n text: headers[i],\n tokens: this.lexer.inline(headers[i]),\n header: true,\n align: item.align[i]\n });\n }\n for (const row of rows) {\n item.rows.push(splitCells(row, item.header.length).map((cell, i) => {\n return {\n text: cell,\n tokens: this.lexer.inline(cell),\n header: false,\n align: item.align[i]\n };\n }));\n }\n return item;\n }\n lheading(src) {\n const cap = this.rules.block.lheading.exec(src);\n if (cap) {\n return {\n type: 'heading',\n raw: cap[0],\n depth: cap[2].charAt(0) === '=' ? 1 : 2,\n text: cap[1],\n tokens: this.lexer.inline(cap[1])\n };\n }\n }\n paragraph(src) {\n const cap = this.rules.block.paragraph.exec(src);\n if (cap) {\n const text = cap[1].charAt(cap[1].length - 1) === '\\n'\n ? cap[1].slice(0, -1)\n : cap[1];\n return {\n type: 'paragraph',\n raw: cap[0],\n text,\n tokens: this.lexer.inline(text)\n };\n }\n }\n text(src) {\n const cap = this.rules.block.text.exec(src);\n if (cap) {\n return {\n type: 'text',\n raw: cap[0],\n text: cap[0],\n tokens: this.lexer.inline(cap[0])\n };\n }\n }\n escape(src) {\n const cap = this.rules.inline.escape.exec(src);\n if (cap) {\n return {\n type: 'escape',\n raw: cap[0],\n text: escape(cap[1])\n };\n }\n }\n tag(src) {\n const cap = this.rules.inline.tag.exec(src);\n if (cap) {\n if (!this.lexer.state.inLink && /^
    /i.test(cap[0])) {\n this.lexer.state.inLink = false;\n }\n if (!this.lexer.state.inRawBlock && /^<(pre|code|kbd|script)(\\s|>)/i.test(cap[0])) {\n this.lexer.state.inRawBlock = true;\n }\n else if (this.lexer.state.inRawBlock && /^<\\/(pre|code|kbd|script)(\\s|>)/i.test(cap[0])) {\n this.lexer.state.inRawBlock = false;\n }\n return {\n type: 'html',\n raw: cap[0],\n inLink: this.lexer.state.inLink,\n inRawBlock: this.lexer.state.inRawBlock,\n block: false,\n text: cap[0]\n };\n }\n }\n link(src) {\n const cap = this.rules.inline.link.exec(src);\n if (cap) {\n const trimmedUrl = cap[2].trim();\n if (!this.options.pedantic && /^$/.test(trimmedUrl))) {\n return;\n }\n // ending angle bracket cannot be escaped\n const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), '\\\\');\n if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) {\n return;\n }\n }\n else {\n // find closing parenthesis\n const lastParenIndex = findClosingBracket(cap[2], '()');\n if (lastParenIndex > -1) {\n const start = cap[0].indexOf('!') === 0 ? 5 : 4;\n const linkLen = start + cap[1].length + lastParenIndex;\n cap[2] = cap[2].substring(0, lastParenIndex);\n cap[0] = cap[0].substring(0, linkLen).trim();\n cap[3] = '';\n }\n }\n let href = cap[2];\n let title = '';\n if (this.options.pedantic) {\n // split pedantic href and title\n const link = /^([^'\"]*[^\\s])\\s+(['\"])(.*)\\2/.exec(href);\n if (link) {\n href = link[1];\n title = link[3];\n }\n }\n else {\n title = cap[3] ? cap[3].slice(1, -1) : '';\n }\n href = href.trim();\n if (/^$/.test(trimmedUrl))) {\n // pedantic allows starting angle bracket without ending angle bracket\n href = href.slice(1);\n }\n else {\n href = href.slice(1, -1);\n }\n }\n return outputLink(cap, {\n href: href ? href.replace(this.rules.inline.anyPunctuation, '$1') : href,\n title: title ? title.replace(this.rules.inline.anyPunctuation, '$1') : title\n }, cap[0], this.lexer);\n }\n }\n reflink(src, links) {\n let cap;\n if ((cap = this.rules.inline.reflink.exec(src))\n || (cap = this.rules.inline.nolink.exec(src))) {\n const linkString = (cap[2] || cap[1]).replace(/\\s+/g, ' ');\n const link = links[linkString.toLowerCase()];\n if (!link) {\n const text = cap[0].charAt(0);\n return {\n type: 'text',\n raw: text,\n text\n };\n }\n return outputLink(cap, link, cap[0], this.lexer);\n }\n }\n emStrong(src, maskedSrc, prevChar = '') {\n let match = this.rules.inline.emStrongLDelim.exec(src);\n if (!match)\n return;\n // _ can't be between two alphanumerics. \\p{L}\\p{N} includes non-english alphabet/numbers as well\n if (match[3] && prevChar.match(/[\\p{L}\\p{N}]/u))\n return;\n const nextChar = match[1] || match[2] || '';\n if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) {\n // unicode Regex counts emoji as 1 char; spread into array for proper count (used multiple times below)\n const lLength = [...match[0]].length - 1;\n let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0;\n const endReg = match[0][0] === '*' ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;\n endReg.lastIndex = 0;\n // Clip maskedSrc to same section of string as src (move to lexer?)\n maskedSrc = maskedSrc.slice(-1 * src.length + lLength);\n while ((match = endReg.exec(maskedSrc)) != null) {\n rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6];\n if (!rDelim)\n continue; // skip single * in __abc*abc__\n rLength = [...rDelim].length;\n if (match[3] || match[4]) { // found another Left Delim\n delimTotal += rLength;\n continue;\n }\n else if (match[5] || match[6]) { // either Left or Right Delim\n if (lLength % 3 && !((lLength + rLength) % 3)) {\n midDelimTotal += rLength;\n continue; // CommonMark Emphasis Rules 9-10\n }\n }\n delimTotal -= rLength;\n if (delimTotal > 0)\n continue; // Haven't found enough closing delimiters\n // Remove extra characters. *a*** -> *a*\n rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal);\n // char length can be >1 for unicode characters;\n const lastCharLength = [...match[0]][0].length;\n const raw = src.slice(0, lLength + match.index + lastCharLength + rLength);\n // Create `em` if smallest delimiter has odd char count. *a***\n if (Math.min(lLength, rLength) % 2) {\n const text = raw.slice(1, -1);\n return {\n type: 'em',\n raw,\n text,\n tokens: this.lexer.inlineTokens(text)\n };\n }\n // Create 'strong' if smallest delimiter has even char count. **a***\n const text = raw.slice(2, -2);\n return {\n type: 'strong',\n raw,\n text,\n tokens: this.lexer.inlineTokens(text)\n };\n }\n }\n }\n codespan(src) {\n const cap = this.rules.inline.code.exec(src);\n if (cap) {\n let text = cap[2].replace(/\\n/g, ' ');\n const hasNonSpaceChars = /[^ ]/.test(text);\n const hasSpaceCharsOnBothEnds = /^ /.test(text) && / $/.test(text);\n if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {\n text = text.substring(1, text.length - 1);\n }\n text = escape(text, true);\n return {\n type: 'codespan',\n raw: cap[0],\n text\n };\n }\n }\n br(src) {\n const cap = this.rules.inline.br.exec(src);\n if (cap) {\n return {\n type: 'br',\n raw: cap[0]\n };\n }\n }\n del(src) {\n const cap = this.rules.inline.del.exec(src);\n if (cap) {\n return {\n type: 'del',\n raw: cap[0],\n text: cap[2],\n tokens: this.lexer.inlineTokens(cap[2])\n };\n }\n }\n autolink(src) {\n const cap = this.rules.inline.autolink.exec(src);\n if (cap) {\n let text, href;\n if (cap[2] === '@') {\n text = escape(cap[1]);\n href = 'mailto:' + text;\n }\n else {\n text = escape(cap[1]);\n href = text;\n }\n return {\n type: 'link',\n raw: cap[0],\n text,\n href,\n tokens: [\n {\n type: 'text',\n raw: text,\n text\n }\n ]\n };\n }\n }\n url(src) {\n let cap;\n if (cap = this.rules.inline.url.exec(src)) {\n let text, href;\n if (cap[2] === '@') {\n text = escape(cap[0]);\n href = 'mailto:' + text;\n }\n else {\n // do extended autolink path validation\n let prevCapZero;\n do {\n prevCapZero = cap[0];\n cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? '';\n } while (prevCapZero !== cap[0]);\n text = escape(cap[0]);\n if (cap[1] === 'www.') {\n href = 'http://' + cap[0];\n }\n else {\n href = cap[0];\n }\n }\n return {\n type: 'link',\n raw: cap[0],\n text,\n href,\n tokens: [\n {\n type: 'text',\n raw: text,\n text\n }\n ]\n };\n }\n }\n inlineText(src) {\n const cap = this.rules.inline.text.exec(src);\n if (cap) {\n let text;\n if (this.lexer.state.inRawBlock) {\n text = cap[0];\n }\n else {\n text = escape(cap[0]);\n }\n return {\n type: 'text',\n raw: cap[0],\n text\n };\n }\n }\n}\n","import { edit, noopTest } from './helpers.ts';\n/**\n * Block-Level Grammar\n */\nconst newline = /^(?: *(?:\\n|$))+/;\nconst blockCode = /^( {4}[^\\n]+(?:\\n(?: *(?:\\n|$))*)?)+/;\nconst fences = /^ {0,3}(`{3,}(?=[^`\\n]*(?:\\n|$))|~{3,})([^\\n]*)(?:\\n|$)(?:|([\\s\\S]*?)(?:\\n|$))(?: {0,3}\\1[~`]* *(?=\\n|$)|$)/;\nconst hr = /^ {0,3}((?:-[\\t ]*){3,}|(?:_[ \\t]*){3,}|(?:\\*[ \\t]*){3,})(?:\\n+|$)/;\nconst heading = /^ {0,3}(#{1,6})(?=\\s|$)(.*)(?:\\n+|$)/;\nconst bullet = /(?:[*+-]|\\d{1,9}[.)])/;\nconst lheading = edit(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\\n(?!\\s*?\\n|bull |blockCode|fences|blockquote|heading|html))+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/)\n .replace(/bull/g, bullet) // lists can interrupt\n .replace(/blockCode/g, / {4}/) // indented code blocks can interrupt\n .replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/) // fenced code blocks can interrupt\n .replace(/blockquote/g, / {0,3}>/) // blockquote can interrupt\n .replace(/heading/g, / {0,3}#{1,6}/) // ATX heading can interrupt\n .replace(/html/g, / {0,3}<[^\\n>]+>\\n/) // block html can interrupt\n .getRegex();\nconst _paragraph = /^([^\\n]+(?:\\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\\n)[^\\n]+)*)/;\nconst blockText = /^[^\\n]+/;\nconst _blockLabel = /(?!\\s*\\])(?:\\\\.|[^\\[\\]\\\\])+/;\nconst def = edit(/^ {0,3}\\[(label)\\]: *(?:\\n *)?([^<\\s][^\\s]*|<.*?>)(?:(?: +(?:\\n *)?| *\\n *)(title))? *(?:\\n+|$)/)\n .replace('label', _blockLabel)\n .replace('title', /(?:\"(?:\\\\\"?|[^\"\\\\])*\"|'[^'\\n]*(?:\\n[^'\\n]+)*\\n?'|\\([^()]*\\))/)\n .getRegex();\nconst list = edit(/^( {0,3}bull)([ \\t][^\\n]+?)?(?:\\n|$)/)\n .replace(/bull/g, bullet)\n .getRegex();\nconst _tag = 'address|article|aside|base|basefont|blockquote|body|caption'\n + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption'\n + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe'\n + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option'\n + '|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title'\n + '|tr|track|ul';\nconst _comment = /|$))/;\nconst html = edit('^ {0,3}(?:' // optional indentation\n + '<(script|pre|style|textarea)[\\\\s>][\\\\s\\\\S]*?(?:[^\\\\n]*\\\\n+|$)' // (1)\n + '|comment[^\\\\n]*(\\\\n+|$)' // (2)\n + '|<\\\\?[\\\\s\\\\S]*?(?:\\\\?>\\\\n*|$)' // (3)\n + '|\\\\n*|$)' // (4)\n + '|\\\\n*|$)' // (5)\n + '|)[\\\\s\\\\S]*?(?:(?:\\\\n *)+\\\\n|$)' // (6)\n + '|<(?!script|pre|style|textarea)([a-z][\\\\w-]*)(?:attribute)*? */?>(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n *)+\\\\n|$)' // (7) open tag\n + '|(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n *)+\\\\n|$)' // (7) closing tag\n + ')', 'i')\n .replace('comment', _comment)\n .replace('tag', _tag)\n .replace('attribute', / +[a-zA-Z:_][\\w.:-]*(?: *= *\"[^\"\\n]*\"| *= *'[^'\\n]*'| *= *[^\\s\"'=<>`]+)?/)\n .getRegex();\nconst paragraph = edit(_paragraph)\n .replace('hr', hr)\n .replace('heading', ' {0,3}#{1,6}(?:\\\\s|$)')\n .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs\n .replace('|table', '')\n .replace('blockquote', ' {0,3}>')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n')\n .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt\n .replace('html', ')|<(?:script|pre|style|textarea|!--)')\n .replace('tag', _tag) // pars can be interrupted by type (6) html blocks\n .getRegex();\nconst blockquote = edit(/^( {0,3}> ?(paragraph|[^\\n]*)(?:\\n|$))+/)\n .replace('paragraph', paragraph)\n .getRegex();\n/**\n * Normal Block Grammar\n */\nconst blockNormal = {\n blockquote,\n code: blockCode,\n def,\n fences,\n heading,\n hr,\n html,\n lheading,\n list,\n newline,\n paragraph,\n table: noopTest,\n text: blockText\n};\n/**\n * GFM Block Grammar\n */\nconst gfmTable = edit('^ *([^\\\\n ].*)\\\\n' // Header\n + ' {0,3}((?:\\\\| *)?:?-+:? *(?:\\\\| *:?-+:? *)*(?:\\\\| *)?)' // Align\n + '(?:\\\\n((?:(?! *\\\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\\\n|$))*)\\\\n*|$)') // Cells\n .replace('hr', hr)\n .replace('heading', ' {0,3}#{1,6}(?:\\\\s|$)')\n .replace('blockquote', ' {0,3}>')\n .replace('code', ' {4}[^\\\\n]')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n')\n .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt\n .replace('html', ')|<(?:script|pre|style|textarea|!--)')\n .replace('tag', _tag) // tables can be interrupted by type (6) html blocks\n .getRegex();\nconst blockGfm = {\n ...blockNormal,\n table: gfmTable,\n paragraph: edit(_paragraph)\n .replace('hr', hr)\n .replace('heading', ' {0,3}#{1,6}(?:\\\\s|$)')\n .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs\n .replace('table', gfmTable) // interrupt paragraphs with table\n .replace('blockquote', ' {0,3}>')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n')\n .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt\n .replace('html', ')|<(?:script|pre|style|textarea|!--)')\n .replace('tag', _tag) // pars can be interrupted by type (6) html blocks\n .getRegex()\n};\n/**\n * Pedantic grammar (original John Gruber's loose markdown specification)\n */\nconst blockPedantic = {\n ...blockNormal,\n html: edit('^ *(?:comment *(?:\\\\n|\\\\s*$)'\n + '|<(tag)[\\\\s\\\\S]+? *(?:\\\\n{2,}|\\\\s*$)' // closed tag\n + '|\\\\s]*)*?/?> *(?:\\\\n{2,}|\\\\s*$))')\n .replace('comment', _comment)\n .replace(/tag/g, '(?!(?:'\n + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub'\n + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)'\n + '\\\\b)\\\\w+(?!:|[^\\\\w\\\\s@]*@)\\\\b')\n .getRegex(),\n def: /^ *\\[([^\\]]+)\\]: *]+)>?(?: +([\"(][^\\n]+[\")]))? *(?:\\n+|$)/,\n heading: /^(#{1,6})(.*)(?:\\n+|$)/,\n fences: noopTest, // fences not supported\n lheading: /^(.+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/,\n paragraph: edit(_paragraph)\n .replace('hr', hr)\n .replace('heading', ' *#{1,6} *[^\\n]')\n .replace('lheading', lheading)\n .replace('|table', '')\n .replace('blockquote', ' {0,3}>')\n .replace('|fences', '')\n .replace('|list', '')\n .replace('|html', '')\n .replace('|tag', '')\n .getRegex()\n};\n/**\n * Inline-Level Grammar\n */\nconst escape = /^\\\\([!\"#$%&'()*+,\\-./:;<=>?@\\[\\]\\\\^_`{|}~])/;\nconst inlineCode = /^(`+)([^`]|[^`][\\s\\S]*?[^`])\\1(?!`)/;\nconst br = /^( {2,}|\\\\)\\n(?!\\s*$)/;\nconst inlineText = /^(`+|[^`])(?:(?= {2,}\\n)|[\\s\\S]*?(?:(?=[\\\\\nconst blockSkip = /\\[[^[\\]]*?\\]\\([^\\(\\)]*?\\)|`[^`]*?`|<[^<>]*?>/g;\nconst emStrongLDelim = edit(/^(?:\\*+(?:((?!\\*)[punct])|[^\\s*]))|^_+(?:((?!_)[punct])|([^\\s_]))/, 'u')\n .replace(/punct/g, _punctuation)\n .getRegex();\nconst emStrongRDelimAst = edit('^[^_*]*?__[^_*]*?\\\\*[^_*]*?(?=__)' // Skip orphan inside strong\n + '|[^*]+(?=[^*])' // Consume to delim\n + '|(?!\\\\*)[punct](\\\\*+)(?=[\\\\s]|$)' // (1) #*** can only be a Right Delimiter\n + '|[^punct\\\\s](\\\\*+)(?!\\\\*)(?=[punct\\\\s]|$)' // (2) a***#, a*** can only be a Right Delimiter\n + '|(?!\\\\*)[punct\\\\s](\\\\*+)(?=[^punct\\\\s])' // (3) #***a, ***a can only be Left Delimiter\n + '|[\\\\s](\\\\*+)(?!\\\\*)(?=[punct])' // (4) ***# can only be Left Delimiter\n + '|(?!\\\\*)[punct](\\\\*+)(?!\\\\*)(?=[punct])' // (5) #***# can be either Left or Right Delimiter\n + '|[^punct\\\\s](\\\\*+)(?=[^punct\\\\s])', 'gu') // (6) a***a can be either Left or Right Delimiter\n .replace(/punct/g, _punctuation)\n .getRegex();\n// (6) Not allowed for _\nconst emStrongRDelimUnd = edit('^[^_*]*?\\\\*\\\\*[^_*]*?_[^_*]*?(?=\\\\*\\\\*)' // Skip orphan inside strong\n + '|[^_]+(?=[^_])' // Consume to delim\n + '|(?!_)[punct](_+)(?=[\\\\s]|$)' // (1) #___ can only be a Right Delimiter\n + '|[^punct\\\\s](_+)(?!_)(?=[punct\\\\s]|$)' // (2) a___#, a___ can only be a Right Delimiter\n + '|(?!_)[punct\\\\s](_+)(?=[^punct\\\\s])' // (3) #___a, ___a can only be Left Delimiter\n + '|[\\\\s](_+)(?!_)(?=[punct])' // (4) ___# can only be Left Delimiter\n + '|(?!_)[punct](_+)(?!_)(?=[punct])', 'gu') // (5) #___# can be either Left or Right Delimiter\n .replace(/punct/g, _punctuation)\n .getRegex();\nconst anyPunctuation = edit(/\\\\([punct])/, 'gu')\n .replace(/punct/g, _punctuation)\n .getRegex();\nconst autolink = edit(/^<(scheme:[^\\s\\x00-\\x1f<>]*|email)>/)\n .replace('scheme', /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/)\n .replace('email', /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/)\n .getRegex();\nconst _inlineComment = edit(_comment).replace('(?:-->|$)', '-->').getRegex();\nconst tag = edit('^comment'\n + '|^' // self-closing tag\n + '|^<[a-zA-Z][\\\\w-]*(?:attribute)*?\\\\s*/?>' // open tag\n + '|^<\\\\?[\\\\s\\\\S]*?\\\\?>' // processing instruction, e.g. \n + '|^' // declaration, e.g. \n + '|^') // CDATA section\n .replace('comment', _inlineComment)\n .replace('attribute', /\\s+[a-zA-Z:_][\\w.:-]*(?:\\s*=\\s*\"[^\"]*\"|\\s*=\\s*'[^']*'|\\s*=\\s*[^\\s\"'=<>`]+)?/)\n .getRegex();\nconst _inlineLabel = /(?:\\[(?:\\\\.|[^\\[\\]\\\\])*\\]|\\\\.|`[^`]*`|[^\\[\\]\\\\`])*?/;\nconst link = edit(/^!?\\[(label)\\]\\(\\s*(href)(?:\\s+(title))?\\s*\\)/)\n .replace('label', _inlineLabel)\n .replace('href', /<(?:\\\\.|[^\\n<>\\\\])+>|[^\\s\\x00-\\x1f]*/)\n .replace('title', /\"(?:\\\\\"?|[^\"\\\\])*\"|'(?:\\\\'?|[^'\\\\])*'|\\((?:\\\\\\)?|[^)\\\\])*\\)/)\n .getRegex();\nconst reflink = edit(/^!?\\[(label)\\]\\[(ref)\\]/)\n .replace('label', _inlineLabel)\n .replace('ref', _blockLabel)\n .getRegex();\nconst nolink = edit(/^!?\\[(ref)\\](?:\\[\\])?/)\n .replace('ref', _blockLabel)\n .getRegex();\nconst reflinkSearch = edit('reflink|nolink(?!\\\\()', 'g')\n .replace('reflink', reflink)\n .replace('nolink', nolink)\n .getRegex();\n/**\n * Normal Inline Grammar\n */\nconst inlineNormal = {\n _backpedal: noopTest, // only used for GFM url\n anyPunctuation,\n autolink,\n blockSkip,\n br,\n code: inlineCode,\n del: noopTest,\n emStrongLDelim,\n emStrongRDelimAst,\n emStrongRDelimUnd,\n escape,\n link,\n nolink,\n punctuation,\n reflink,\n reflinkSearch,\n tag,\n text: inlineText,\n url: noopTest\n};\n/**\n * Pedantic Inline Grammar\n */\nconst inlinePedantic = {\n ...inlineNormal,\n link: edit(/^!?\\[(label)\\]\\((.*?)\\)/)\n .replace('label', _inlineLabel)\n .getRegex(),\n reflink: edit(/^!?\\[(label)\\]\\s*\\[([^\\]]*)\\]/)\n .replace('label', _inlineLabel)\n .getRegex()\n};\n/**\n * GFM Inline Grammar\n */\nconst inlineGfm = {\n ...inlineNormal,\n escape: edit(escape).replace('])', '~|])').getRegex(),\n url: edit(/^((?:ftp|https?):\\/\\/|www\\.)(?:[a-zA-Z0-9\\-]+\\.?)+[^\\s<]*|^email/, 'i')\n .replace('email', /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/)\n .getRegex(),\n _backpedal: /(?:[^?!.,:;*_'\"~()&]+|\\([^)]*\\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'\"~)]+(?!$))+/,\n del: /^(~~?)(?=[^\\s~])([\\s\\S]*?[^\\s~])\\1(?=[^~]|$)/,\n text: /^([`~]+|[^`~])(?:(?= {2,}\\n)|(?=[a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-]+@)|[\\s\\S]*?(?:(?=[\\\\ {\n return leading + ' '.repeat(tabs.length);\n });\n }\n let token;\n let lastToken;\n let cutSrc;\n while (src) {\n if (this.options.extensions\n && this.options.extensions.block\n && this.options.extensions.block.some((extTokenizer) => {\n if (token = extTokenizer.call({ lexer: this }, src, tokens)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n return true;\n }\n return false;\n })) {\n continue;\n }\n // newline\n if (token = this.tokenizer.space(src)) {\n src = src.substring(token.raw.length);\n if (token.raw.length === 1 && tokens.length > 0) {\n // if there's a single \\n as a spacer, it's terminating the last line,\n // so move it there so that we don't get unnecessary paragraph tags\n tokens[tokens.length - 1].raw += '\\n';\n }\n else {\n tokens.push(token);\n }\n continue;\n }\n // code\n if (token = this.tokenizer.code(src)) {\n src = src.substring(token.raw.length);\n lastToken = tokens[tokens.length - 1];\n // An indented code block cannot interrupt a paragraph.\n if (lastToken && (lastToken.type === 'paragraph' || lastToken.type === 'text')) {\n lastToken.raw += '\\n' + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;\n }\n else {\n tokens.push(token);\n }\n continue;\n }\n // fences\n if (token = this.tokenizer.fences(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // heading\n if (token = this.tokenizer.heading(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // hr\n if (token = this.tokenizer.hr(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // blockquote\n if (token = this.tokenizer.blockquote(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // list\n if (token = this.tokenizer.list(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // html\n if (token = this.tokenizer.html(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // def\n if (token = this.tokenizer.def(src)) {\n src = src.substring(token.raw.length);\n lastToken = tokens[tokens.length - 1];\n if (lastToken && (lastToken.type === 'paragraph' || lastToken.type === 'text')) {\n lastToken.raw += '\\n' + token.raw;\n lastToken.text += '\\n' + token.raw;\n this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;\n }\n else if (!this.tokens.links[token.tag]) {\n this.tokens.links[token.tag] = {\n href: token.href,\n title: token.title\n };\n }\n continue;\n }\n // table (gfm)\n if (token = this.tokenizer.table(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // lheading\n if (token = this.tokenizer.lheading(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // top-level paragraph\n // prevent paragraph consuming extensions by clipping 'src' to extension start\n cutSrc = src;\n if (this.options.extensions && this.options.extensions.startBlock) {\n let startIndex = Infinity;\n const tempSrc = src.slice(1);\n let tempStart;\n this.options.extensions.startBlock.forEach((getStartIndex) => {\n tempStart = getStartIndex.call({ lexer: this }, tempSrc);\n if (typeof tempStart === 'number' && tempStart >= 0) {\n startIndex = Math.min(startIndex, tempStart);\n }\n });\n if (startIndex < Infinity && startIndex >= 0) {\n cutSrc = src.substring(0, startIndex + 1);\n }\n }\n if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) {\n lastToken = tokens[tokens.length - 1];\n if (lastParagraphClipped && lastToken?.type === 'paragraph') {\n lastToken.raw += '\\n' + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.pop();\n this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;\n }\n else {\n tokens.push(token);\n }\n lastParagraphClipped = (cutSrc.length !== src.length);\n src = src.substring(token.raw.length);\n continue;\n }\n // text\n if (token = this.tokenizer.text(src)) {\n src = src.substring(token.raw.length);\n lastToken = tokens[tokens.length - 1];\n if (lastToken && lastToken.type === 'text') {\n lastToken.raw += '\\n' + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.pop();\n this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;\n }\n else {\n tokens.push(token);\n }\n continue;\n }\n if (src) {\n const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);\n if (this.options.silent) {\n console.error(errMsg);\n break;\n }\n else {\n throw new Error(errMsg);\n }\n }\n }\n this.state.top = true;\n return tokens;\n }\n inline(src, tokens = []) {\n this.inlineQueue.push({ src, tokens });\n return tokens;\n }\n /**\n * Lexing/Compiling\n */\n inlineTokens(src, tokens = []) {\n let token, lastToken, cutSrc;\n // String with links masked to avoid interference with em and strong\n let maskedSrc = src;\n let match;\n let keepPrevChar, prevChar;\n // Mask out reflinks\n if (this.tokens.links) {\n const links = Object.keys(this.tokens.links);\n if (links.length > 0) {\n while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) {\n if (links.includes(match[0].slice(match[0].lastIndexOf('[') + 1, -1))) {\n maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex);\n }\n }\n }\n }\n // Mask out other blocks\n while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) {\n maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);\n }\n // Mask out escaped characters\n while ((match = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) != null) {\n maskedSrc = maskedSrc.slice(0, match.index) + '++' + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);\n }\n while (src) {\n if (!keepPrevChar) {\n prevChar = '';\n }\n keepPrevChar = false;\n // extensions\n if (this.options.extensions\n && this.options.extensions.inline\n && this.options.extensions.inline.some((extTokenizer) => {\n if (token = extTokenizer.call({ lexer: this }, src, tokens)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n return true;\n }\n return false;\n })) {\n continue;\n }\n // escape\n if (token = this.tokenizer.escape(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // tag\n if (token = this.tokenizer.tag(src)) {\n src = src.substring(token.raw.length);\n lastToken = tokens[tokens.length - 1];\n if (lastToken && token.type === 'text' && lastToken.type === 'text') {\n lastToken.raw += token.raw;\n lastToken.text += token.text;\n }\n else {\n tokens.push(token);\n }\n continue;\n }\n // link\n if (token = this.tokenizer.link(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // reflink, nolink\n if (token = this.tokenizer.reflink(src, this.tokens.links)) {\n src = src.substring(token.raw.length);\n lastToken = tokens[tokens.length - 1];\n if (lastToken && token.type === 'text' && lastToken.type === 'text') {\n lastToken.raw += token.raw;\n lastToken.text += token.text;\n }\n else {\n tokens.push(token);\n }\n continue;\n }\n // em & strong\n if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // code\n if (token = this.tokenizer.codespan(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // br\n if (token = this.tokenizer.br(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // del (gfm)\n if (token = this.tokenizer.del(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // autolink\n if (token = this.tokenizer.autolink(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // url (gfm)\n if (!this.state.inLink && (token = this.tokenizer.url(src))) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // text\n // prevent inlineText consuming extensions by clipping 'src' to extension start\n cutSrc = src;\n if (this.options.extensions && this.options.extensions.startInline) {\n let startIndex = Infinity;\n const tempSrc = src.slice(1);\n let tempStart;\n this.options.extensions.startInline.forEach((getStartIndex) => {\n tempStart = getStartIndex.call({ lexer: this }, tempSrc);\n if (typeof tempStart === 'number' && tempStart >= 0) {\n startIndex = Math.min(startIndex, tempStart);\n }\n });\n if (startIndex < Infinity && startIndex >= 0) {\n cutSrc = src.substring(0, startIndex + 1);\n }\n }\n if (token = this.tokenizer.inlineText(cutSrc)) {\n src = src.substring(token.raw.length);\n if (token.raw.slice(-1) !== '_') { // Track prevChar before string of ____ started\n prevChar = token.raw.slice(-1);\n }\n keepPrevChar = true;\n lastToken = tokens[tokens.length - 1];\n if (lastToken && lastToken.type === 'text') {\n lastToken.raw += token.raw;\n lastToken.text += token.text;\n }\n else {\n tokens.push(token);\n }\n continue;\n }\n if (src) {\n const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);\n if (this.options.silent) {\n console.error(errMsg);\n break;\n }\n else {\n throw new Error(errMsg);\n }\n }\n }\n return tokens;\n }\n}\n","import { _defaults } from './defaults.ts';\nimport { cleanUrl, escape } from './helpers.ts';\n/**\n * Renderer\n */\nexport class _Renderer {\n options;\n parser; // set by the parser\n constructor(options) {\n this.options = options || _defaults;\n }\n space(token) {\n return '';\n }\n code({ text, lang, escaped }) {\n const langString = (lang || '').match(/^\\S*/)?.[0];\n const code = text.replace(/\\n$/, '') + '\\n';\n if (!langString) {\n return '
    '\n                + (escaped ? code : escape(code, true))\n                + '
    \\n';\n }\n return '
    '\n            + (escaped ? code : escape(code, true))\n            + '
    \\n';\n }\n blockquote({ tokens }) {\n const body = this.parser.parse(tokens);\n return `
    \\n${body}
    \\n`;\n }\n html({ text }) {\n return text;\n }\n heading({ tokens, depth }) {\n return `${this.parser.parseInline(tokens)}\\n`;\n }\n hr(token) {\n return '
    \\n';\n }\n list(token) {\n const ordered = token.ordered;\n const start = token.start;\n let body = '';\n for (let j = 0; j < token.items.length; j++) {\n const item = token.items[j];\n body += this.listitem(item);\n }\n const type = ordered ? 'ol' : 'ul';\n const startAttr = (ordered && start !== 1) ? (' start=\"' + start + '\"') : '';\n return '<' + type + startAttr + '>\\n' + body + '\\n';\n }\n listitem(item) {\n let itemBody = '';\n if (item.task) {\n const checkbox = this.checkbox({ checked: !!item.checked });\n if (item.loose) {\n if (item.tokens.length > 0 && item.tokens[0].type === 'paragraph') {\n item.tokens[0].text = checkbox + ' ' + item.tokens[0].text;\n if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') {\n item.tokens[0].tokens[0].text = checkbox + ' ' + item.tokens[0].tokens[0].text;\n }\n }\n else {\n item.tokens.unshift({\n type: 'text',\n raw: checkbox + ' ',\n text: checkbox + ' '\n });\n }\n }\n else {\n itemBody += checkbox + ' ';\n }\n }\n itemBody += this.parser.parse(item.tokens, !!item.loose);\n return `
  • ${itemBody}
  • \\n`;\n }\n checkbox({ checked }) {\n return '';\n }\n paragraph({ tokens }) {\n return `

    ${this.parser.parseInline(tokens)}

    \\n`;\n }\n table(token) {\n let header = '';\n // header\n let cell = '';\n for (let j = 0; j < token.header.length; j++) {\n cell += this.tablecell(token.header[j]);\n }\n header += this.tablerow({ text: cell });\n let body = '';\n for (let j = 0; j < token.rows.length; j++) {\n const row = token.rows[j];\n cell = '';\n for (let k = 0; k < row.length; k++) {\n cell += this.tablecell(row[k]);\n }\n body += this.tablerow({ text: cell });\n }\n if (body)\n body = `${body}`;\n return '\\n'\n + '\\n'\n + header\n + '\\n'\n + body\n + '
    \\n';\n }\n tablerow({ text }) {\n return `\\n${text}\\n`;\n }\n tablecell(token) {\n const content = this.parser.parseInline(token.tokens);\n const type = token.header ? 'th' : 'td';\n const tag = token.align\n ? `<${type} align=\"${token.align}\">`\n : `<${type}>`;\n return tag + content + `\\n`;\n }\n /**\n * span level renderer\n */\n strong({ tokens }) {\n return `${this.parser.parseInline(tokens)}`;\n }\n em({ tokens }) {\n return `${this.parser.parseInline(tokens)}`;\n }\n codespan({ text }) {\n return `${text}`;\n }\n br(token) {\n return '
    ';\n }\n del({ tokens }) {\n return `${this.parser.parseInline(tokens)}`;\n }\n link({ href, title, tokens }) {\n const text = this.parser.parseInline(tokens);\n const cleanHref = cleanUrl(href);\n if (cleanHref === null) {\n return text;\n }\n href = cleanHref;\n let out = '
    ';\n return out;\n }\n image({ href, title, text }) {\n const cleanHref = cleanUrl(href);\n if (cleanHref === null) {\n return text;\n }\n href = cleanHref;\n let out = `\"${text}\"`;\n {\n const tokens = genericToken[childTokens].flat(Infinity);\n values = values.concat(this.walkTokens(tokens, callback));\n });\n }\n else if (genericToken.tokens) {\n values = values.concat(this.walkTokens(genericToken.tokens, callback));\n }\n }\n }\n }\n return values;\n }\n use(...args) {\n const extensions = this.defaults.extensions || { renderers: {}, childTokens: {} };\n args.forEach((pack) => {\n // copy options to new object\n const opts = { ...pack };\n // set async to true if it was set to true before\n opts.async = this.defaults.async || opts.async || false;\n // ==-- Parse \"addon\" extensions --== //\n if (pack.extensions) {\n pack.extensions.forEach((ext) => {\n if (!ext.name) {\n throw new Error('extension name required');\n }\n if ('renderer' in ext) { // Renderer extensions\n const prevRenderer = extensions.renderers[ext.name];\n if (prevRenderer) {\n // Replace extension with func to run new extension but fall back if false\n extensions.renderers[ext.name] = function (...args) {\n let ret = ext.renderer.apply(this, args);\n if (ret === false) {\n ret = prevRenderer.apply(this, args);\n }\n return ret;\n };\n }\n else {\n extensions.renderers[ext.name] = ext.renderer;\n }\n }\n if ('tokenizer' in ext) { // Tokenizer Extensions\n if (!ext.level || (ext.level !== 'block' && ext.level !== 'inline')) {\n throw new Error(\"extension level must be 'block' or 'inline'\");\n }\n const extLevel = extensions[ext.level];\n if (extLevel) {\n extLevel.unshift(ext.tokenizer);\n }\n else {\n extensions[ext.level] = [ext.tokenizer];\n }\n if (ext.start) { // Function to check for start of token\n if (ext.level === 'block') {\n if (extensions.startBlock) {\n extensions.startBlock.push(ext.start);\n }\n else {\n extensions.startBlock = [ext.start];\n }\n }\n else if (ext.level === 'inline') {\n if (extensions.startInline) {\n extensions.startInline.push(ext.start);\n }\n else {\n extensions.startInline = [ext.start];\n }\n }\n }\n }\n if ('childTokens' in ext && ext.childTokens) { // Child tokens to be visited by walkTokens\n extensions.childTokens[ext.name] = ext.childTokens;\n }\n });\n opts.extensions = extensions;\n }\n // ==-- Parse \"overwrite\" extensions --== //\n if (pack.renderer) {\n const renderer = this.defaults.renderer || new _Renderer(this.defaults);\n for (const prop in pack.renderer) {\n if (!(prop in renderer)) {\n throw new Error(`renderer '${prop}' does not exist`);\n }\n if (['options', 'parser'].includes(prop)) {\n // ignore options property\n continue;\n }\n const rendererProp = prop;\n let rendererFunc = pack.renderer[rendererProp];\n const prevRenderer = renderer[rendererProp];\n // Replace renderer with func to run extension, but fall back if false\n renderer[rendererProp] = (...args) => {\n if (!pack.useNewRenderer) {\n // TODO: Remove this in next major version\n rendererFunc = this.#convertRendererFunction(rendererFunc, rendererProp, renderer);\n }\n let ret = rendererFunc.apply(renderer, args);\n if (ret === false) {\n ret = prevRenderer.apply(renderer, args);\n }\n return ret || '';\n };\n }\n opts.renderer = renderer;\n }\n if (pack.tokenizer) {\n const tokenizer = this.defaults.tokenizer || new _Tokenizer(this.defaults);\n for (const prop in pack.tokenizer) {\n if (!(prop in tokenizer)) {\n throw new Error(`tokenizer '${prop}' does not exist`);\n }\n if (['options', 'rules', 'lexer'].includes(prop)) {\n // ignore options, rules, and lexer properties\n continue;\n }\n const tokenizerProp = prop;\n const tokenizerFunc = pack.tokenizer[tokenizerProp];\n const prevTokenizer = tokenizer[tokenizerProp];\n // Replace tokenizer with func to run extension, but fall back if false\n // @ts-expect-error cannot type tokenizer function dynamically\n tokenizer[tokenizerProp] = (...args) => {\n let ret = tokenizerFunc.apply(tokenizer, args);\n if (ret === false) {\n ret = prevTokenizer.apply(tokenizer, args);\n }\n return ret;\n };\n }\n opts.tokenizer = tokenizer;\n }\n // ==-- Parse Hooks extensions --== //\n if (pack.hooks) {\n const hooks = this.defaults.hooks || new _Hooks();\n for (const prop in pack.hooks) {\n if (!(prop in hooks)) {\n throw new Error(`hook '${prop}' does not exist`);\n }\n if (prop === 'options') {\n // ignore options property\n continue;\n }\n const hooksProp = prop;\n const hooksFunc = pack.hooks[hooksProp];\n const prevHook = hooks[hooksProp];\n if (_Hooks.passThroughHooks.has(prop)) {\n // @ts-expect-error cannot type hook function dynamically\n hooks[hooksProp] = (arg) => {\n if (this.defaults.async) {\n return Promise.resolve(hooksFunc.call(hooks, arg)).then(ret => {\n return prevHook.call(hooks, ret);\n });\n }\n const ret = hooksFunc.call(hooks, arg);\n return prevHook.call(hooks, ret);\n };\n }\n else {\n // @ts-expect-error cannot type hook function dynamically\n hooks[hooksProp] = (...args) => {\n let ret = hooksFunc.apply(hooks, args);\n if (ret === false) {\n ret = prevHook.apply(hooks, args);\n }\n return ret;\n };\n }\n }\n opts.hooks = hooks;\n }\n // ==-- Parse WalkTokens extensions --== //\n if (pack.walkTokens) {\n const walkTokens = this.defaults.walkTokens;\n const packWalktokens = pack.walkTokens;\n opts.walkTokens = function (token) {\n let values = [];\n values.push(packWalktokens.call(this, token));\n if (walkTokens) {\n values = values.concat(walkTokens.call(this, token));\n }\n return values;\n };\n }\n this.defaults = { ...this.defaults, ...opts };\n });\n return this;\n }\n // TODO: Remove this in next major release\n #convertRendererFunction(func, prop, renderer) {\n switch (prop) {\n case 'heading':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n return func.call(this, renderer.parser.parseInline(token.tokens), token.depth, unescape(renderer.parser.parseInline(token.tokens, renderer.parser.textRenderer)));\n };\n case 'code':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n return func.call(this, token.text, token.lang, !!token.escaped);\n };\n case 'table':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n let header = '';\n // header\n let cell = '';\n for (let j = 0; j < token.header.length; j++) {\n cell += this.tablecell({\n text: token.header[j].text,\n tokens: token.header[j].tokens,\n header: true,\n align: token.align[j]\n });\n }\n header += this.tablerow({ text: cell });\n let body = '';\n for (let j = 0; j < token.rows.length; j++) {\n const row = token.rows[j];\n cell = '';\n for (let k = 0; k < row.length; k++) {\n cell += this.tablecell({\n text: row[k].text,\n tokens: row[k].tokens,\n header: false,\n align: token.align[k]\n });\n }\n body += this.tablerow({ text: cell });\n }\n return func.call(this, header, body);\n };\n case 'blockquote':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n const body = this.parser.parse(token.tokens);\n return func.call(this, body);\n };\n case 'list':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n const ordered = token.ordered;\n const start = token.start;\n const loose = token.loose;\n let body = '';\n for (let j = 0; j < token.items.length; j++) {\n const item = token.items[j];\n const checked = item.checked;\n const task = item.task;\n let itemBody = '';\n if (item.task) {\n const checkbox = this.checkbox({ checked: !!checked });\n if (loose) {\n if (item.tokens.length > 0 && item.tokens[0].type === 'paragraph') {\n item.tokens[0].text = checkbox + ' ' + item.tokens[0].text;\n if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') {\n item.tokens[0].tokens[0].text = checkbox + ' ' + item.tokens[0].tokens[0].text;\n }\n }\n else {\n item.tokens.unshift({\n type: 'text',\n text: checkbox + ' '\n });\n }\n }\n else {\n itemBody += checkbox + ' ';\n }\n }\n itemBody += this.parser.parse(item.tokens, loose);\n body += this.listitem({\n type: 'list_item',\n raw: itemBody,\n text: itemBody,\n task,\n checked: !!checked,\n loose,\n tokens: item.tokens\n });\n }\n return func.call(this, body, ordered, start);\n };\n case 'html':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n return func.call(this, token.text, token.block);\n };\n case 'paragraph':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n return func.call(this, this.parser.parseInline(token.tokens));\n };\n case 'escape':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n return func.call(this, token.text);\n };\n case 'link':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n return func.call(this, token.href, token.title, this.parser.parseInline(token.tokens));\n };\n case 'image':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n return func.call(this, token.href, token.title, token.text);\n };\n case 'strong':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n return func.call(this, this.parser.parseInline(token.tokens));\n };\n case 'em':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n return func.call(this, this.parser.parseInline(token.tokens));\n };\n case 'codespan':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n return func.call(this, token.text);\n };\n case 'del':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n return func.call(this, this.parser.parseInline(token.tokens));\n };\n case 'text':\n return function (token) {\n if (!token.type || token.type !== prop) {\n // @ts-ignore\n // eslint-disable-next-line prefer-rest-params\n return func.apply(this, arguments);\n }\n return func.call(this, token.text);\n };\n default:\n // do nothing\n }\n return func;\n }\n setOptions(opt) {\n this.defaults = { ...this.defaults, ...opt };\n return this;\n }\n lexer(src, options) {\n return _Lexer.lex(src, options ?? this.defaults);\n }\n parser(tokens, options) {\n return _Parser.parse(tokens, options ?? this.defaults);\n }\n #parseMarkdown(lexer, parser) {\n return (src, options) => {\n const origOpt = { ...options };\n const opt = { ...this.defaults, ...origOpt };\n // Show warning if an extension set async to true but the parse was called with async: false\n if (this.defaults.async === true && origOpt.async === false) {\n if (!opt.silent) {\n console.warn('marked(): The async option was set to true by an extension. The async: false option sent to parse will be ignored.');\n }\n opt.async = true;\n }\n const throwError = this.#onError(!!opt.silent, !!opt.async);\n // throw error in case of non string input\n if (typeof src === 'undefined' || src === null) {\n return throwError(new Error('marked(): input parameter is undefined or null'));\n }\n if (typeof src !== 'string') {\n return throwError(new Error('marked(): input parameter is of type '\n + Object.prototype.toString.call(src) + ', string expected'));\n }\n if (opt.hooks) {\n opt.hooks.options = opt;\n }\n if (opt.async) {\n return Promise.resolve(opt.hooks ? opt.hooks.preprocess(src) : src)\n .then(src => lexer(src, opt))\n .then(tokens => opt.hooks ? opt.hooks.processAllTokens(tokens) : tokens)\n .then(tokens => opt.walkTokens ? Promise.all(this.walkTokens(tokens, opt.walkTokens)).then(() => tokens) : tokens)\n .then(tokens => parser(tokens, opt))\n .then(html => opt.hooks ? opt.hooks.postprocess(html) : html)\n .catch(throwError);\n }\n try {\n if (opt.hooks) {\n src = opt.hooks.preprocess(src);\n }\n let tokens = lexer(src, opt);\n if (opt.hooks) {\n tokens = opt.hooks.processAllTokens(tokens);\n }\n if (opt.walkTokens) {\n this.walkTokens(tokens, opt.walkTokens);\n }\n let html = parser(tokens, opt);\n if (opt.hooks) {\n html = opt.hooks.postprocess(html);\n }\n return html;\n }\n catch (e) {\n return throwError(e);\n }\n };\n }\n #onError(silent, async) {\n return (e) => {\n e.message += '\\nPlease report this to https://github.com/markedjs/marked.';\n if (silent) {\n const msg = '

    An error occurred:

    '\n                    + escape(e.message + '', true)\n                    + '
    ';\n if (async) {\n return Promise.resolve(msg);\n }\n return msg;\n }\n if (async) {\n return Promise.reject(e);\n }\n throw e;\n };\n }\n}\n","import { _Lexer } from './Lexer.ts';\nimport { _Parser } from './Parser.ts';\nimport { _Tokenizer } from './Tokenizer.ts';\nimport { _Renderer } from './Renderer.ts';\nimport { _TextRenderer } from './TextRenderer.ts';\nimport { _Hooks } from './Hooks.ts';\nimport { Marked } from './Instance.ts';\nimport { _getDefaults, changeDefaults, _defaults } from './defaults.ts';\nconst markedInstance = new Marked();\nexport function marked(src, opt) {\n return markedInstance.parse(src, opt);\n}\n/**\n * Sets the default options.\n *\n * @param options Hash of options\n */\nmarked.options =\n marked.setOptions = function (options) {\n markedInstance.setOptions(options);\n marked.defaults = markedInstance.defaults;\n changeDefaults(marked.defaults);\n return marked;\n };\n/**\n * Gets the original marked default options.\n */\nmarked.getDefaults = _getDefaults;\nmarked.defaults = _defaults;\n/**\n * Use Extension\n */\nmarked.use = function (...args) {\n markedInstance.use(...args);\n marked.defaults = markedInstance.defaults;\n changeDefaults(marked.defaults);\n return marked;\n};\n/**\n * Run callback for every token\n */\nmarked.walkTokens = function (tokens, callback) {\n return markedInstance.walkTokens(tokens, callback);\n};\n/**\n * Compiles markdown to HTML without enclosing `p` tag.\n *\n * @param src String of markdown source to be compiled\n * @param options Hash of options\n * @return String of compiled HTML\n */\nmarked.parseInline = markedInstance.parseInline;\n/**\n * Expose\n */\nmarked.Parser = _Parser;\nmarked.parser = _Parser.parse;\nmarked.Renderer = _Renderer;\nmarked.TextRenderer = _TextRenderer;\nmarked.Lexer = _Lexer;\nmarked.lexer = _Lexer.lex;\nmarked.Tokenizer = _Tokenizer;\nmarked.Hooks = _Hooks;\nmarked.parse = marked;\nexport const options = marked.options;\nexport const setOptions = marked.setOptions;\nexport const use = marked.use;\nexport const walkTokens = marked.walkTokens;\nexport const parseInline = marked.parseInline;\nexport const parse = marked;\nexport const parser = _Parser.parse;\nexport const lexer = _Lexer.lex;\nexport { _defaults as defaults, _getDefaults as getDefaults } from './defaults.ts';\nexport { _Lexer as Lexer } from './Lexer.ts';\nexport { _Parser as Parser } from './Parser.ts';\nexport { _Tokenizer as Tokenizer } from './Tokenizer.ts';\nexport { _Renderer as Renderer } from './Renderer.ts';\nexport { _TextRenderer as TextRenderer } from './TextRenderer.ts';\nexport { _Hooks as Hooks } from './Hooks.ts';\nexport { Marked } from './Instance.ts';\n"],"names":["_defaults","escape"],"mappings":";;;;;;;;;;;;;;;;;IAAA;IACA;IACA;IACO,SAAS,YAAY,GAAG;IAC/B,IAAI,OAAO;IACX,QAAQ,KAAK,EAAE,KAAK;IACpB,QAAQ,MAAM,EAAE,KAAK;IACrB,QAAQ,UAAU,EAAE,IAAI;IACxB,QAAQ,GAAG,EAAE,IAAI;IACjB,QAAQ,KAAK,EAAE,IAAI;IACnB,QAAQ,QAAQ,EAAE,KAAK;IACvB,QAAQ,QAAQ,EAAE,IAAI;IACtB,QAAQ,MAAM,EAAE,KAAK;IACrB,QAAQ,SAAS,EAAE,IAAI;IACvB,QAAQ,UAAU,EAAE,IAAI;IACxB,KAAK,CAAC;IACN,CAAC;AACUA,oBAAS,GAAG,YAAY,GAAG;IAC/B,SAAS,cAAc,CAAC,WAAW,EAAE;IAC5C,IAAIA,gBAAS,GAAG,WAAW,CAAC;IAC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AY;AAClC,UAAC,KAAK,GAAG,OAAO;AAChB,UAAC,MAAM,GAAG,OAAO,CAAC,MAAM;AACxB,UAAC,KAAK,GAAG,MAAM,CAAC;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/scripts/node_modules/marked/man/marked.1 b/scripts/node_modules/marked/man/marked.1 new file mode 100644 index 000000000..40f4d0374 --- /dev/null +++ b/scripts/node_modules/marked/man/marked.1 @@ -0,0 +1,111 @@ +.TH "MARKED" "1" "June 2024" "13.0.0" +.SH "NAME" +\fBmarked\fR \- a javascript markdown parser +.SH SYNOPSIS +.P +\fBmarked\fP [\fB\-o\fP ] [\fB\-i\fP ] [\fB\-s\fP ] [\fB\-c\fP ] [\fB\-\-help\fP] [\fB\-\-version\fP] [\fB\-\-tokens\fP] [\fB\-\-no\-clobber\fP] [\fB\-\-pedantic\fP] [\fB\-\-gfm\fP] [\fB\-\-breaks\fP] [\fB\-\-no\-etc\.\.\.\fP] [\fB\-\-silent\fP] [filename] +.SH DESCRIPTION +.P +marked is a full\-featured javascript markdown parser, built for speed\. +.br +It also includes multiple GFM features\. +.SH EXAMPLES +.RS 2 +.nf +cat in\.md | marked > out\.html +.fi +.RE +.RS 2 +.nf +echo "hello *world*" | marked +.fi +.RE +.RS 2 +.nf +marked \-o out\.html \-i in\.md \-\-gfm +.fi +.RE +.RS 2 +.nf +marked \-\-output="hello world\.html" \-i in\.md \-\-no\-breaks +.fi +.RE +.SH OPTIONS + +.RS 1 +.IP \(bu 2 +\-o, \-\-output [output file] +.br +Specify file output\. If none is specified, write to stdout\. +.IP \(bu 2 +\-i, \-\-input [input file] +.br +Specify file input, otherwise use last argument as input file\. +.br +If no input file is specified, read from stdin\. +.IP \(bu 2 +\-s, \-\-string [markdown string] +.br +Specify string input instead of a file\. +.IP \(bu 2 +\-c, \-\-config [config file] +.br +Specify config file to use instead of the default \fB~/\.marked\.json\fP or \fB~/\.marked\.js\fP or \fB~/\.marked/index\.js\fP\|\. +.IP \(bu 2 +\-t, \-\-tokens +.br +Output a token list instead of html\. +.IP \(bu 2 +\-n, \-\-no\-clobber +.br +Do not overwrite \fBoutput\fP if it exists\. +.IP \(bu 2 +\-\-pedantic +.br +Conform to obscure parts of markdown\.pl as much as possible\. +.br +Don't fix original markdown bugs\. +.IP \(bu 2 +\-\-gfm +.br +Enable github flavored markdown\. +.IP \(bu 2 +\-\-breaks +.br +Enable GFM line breaks\. Only works with the gfm option\. +.IP \(bu 2 +\-\-no\-breaks, \-no\-etc\.\.\. +.br +The inverse of any of the marked options above\. +.IP \(bu 2 +\-\-silent +.br +Silence error output\. +.IP \(bu 2 +\-h, \-\-help +.br +Display help information\. + +.RE +.SH CONFIGURATION +.P +For configuring and running programmatically\. +.P +Example +.RS 2 +.nf +import { Marked } from 'marked'; +const marked = new Marked({ gfm: true }); +marked\.parse('*foo*'); +.fi +.RE +.SH BUGS +.P +Please report any bugs to https://github.com/markedjs/marked +.SH LICENSE +.P +Copyright (c) 2011\-2014, Christopher Jeffrey (MIT License)\. +.SH SEE ALSO +.P +markdown(1), nodejs(1) + diff --git a/scripts/node_modules/marked/man/marked.1.md b/scripts/node_modules/marked/man/marked.1.md new file mode 100644 index 000000000..d5b94a45e --- /dev/null +++ b/scripts/node_modules/marked/man/marked.1.md @@ -0,0 +1,92 @@ +# marked(1) -- a javascript markdown parser + +## SYNOPSIS + +`marked` [`-o` ] [`-i` ] [`-s` ] [`-c` ] [`--help`] [`--version`] [`--tokens`] [`--no-clobber`] [`--pedantic`] [`--gfm`] [`--breaks`] [`--no-etc...`] [`--silent`] [filename] + +## DESCRIPTION + +marked is a full-featured javascript markdown parser, built for speed. +It also includes multiple GFM features. + +## EXAMPLES + +```sh +cat in.md | marked > out.html +``` + +```sh +echo "hello *world*" | marked +``` + +```sh +marked -o out.html -i in.md --gfm +``` + +```sh +marked --output="hello world.html" -i in.md --no-breaks +``` + +## OPTIONS + +* -o, --output [output file] +Specify file output. If none is specified, write to stdout. + +* -i, --input [input file] +Specify file input, otherwise use last argument as input file. +If no input file is specified, read from stdin. + +* -s, --string [markdown string] +Specify string input instead of a file. + +* -c, --config [config file] +Specify config file to use instead of the default `~/.marked.json` or `~/.marked.js` or `~/.marked/index.js`. + +* -t, --tokens +Output a token list instead of html. + +* -n, --no-clobber +Do not overwrite `output` if it exists. + +* --pedantic +Conform to obscure parts of markdown.pl as much as possible. +Don't fix original markdown bugs. + +* --gfm +Enable github flavored markdown. + +* --breaks +Enable GFM line breaks. Only works with the gfm option. + +* --no-breaks, -no-etc... +The inverse of any of the marked options above. + +* --silent +Silence error output. + +* -h, --help +Display help information. + +## CONFIGURATION + +For configuring and running programmatically. + +Example + +```js +import { Marked } from 'marked'; +const marked = new Marked({ gfm: true }); +marked.parse('*foo*'); +``` + +## BUGS + +Please report any bugs to . + +## LICENSE + +Copyright (c) 2011-2014, Christopher Jeffrey (MIT License). + +## SEE ALSO + +markdown(1), nodejs(1) diff --git a/scripts/node_modules/marked/marked.min.js b/scripts/node_modules/marked/marked.min.js new file mode 100644 index 000000000..87bfe0a5a --- /dev/null +++ b/scripts/node_modules/marked/marked.min.js @@ -0,0 +1,6 @@ +/** + * marked v13.0.1 - a markdown parser + * Copyright (c) 2011-2024, Christopher Jeffrey. (MIT Licensed) + * https://github.com/markedjs/marked + */ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).marked={})}(this,(function(e){"use strict";function t(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}function n(t){e.defaults=t}e.defaults={async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null};const s=/[&<>"']/,r=new RegExp(s.source,"g"),i=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,l=new RegExp(i.source,"g"),o={"&":"&","<":"<",">":">",'"':""","'":"'"},a=e=>o[e];function c(e,t){if(t){if(s.test(e))return e.replace(r,a)}else if(i.test(e))return e.replace(l,a);return e}const h=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/gi;const p=/(^|[^\[])\^/g;function u(e,t){let n="string"==typeof e?e:e.source;t=t||"";const s={replace:(e,t)=>{let r="string"==typeof t?t:t.source;return r=r.replace(p,"$1"),n=n.replace(e,r),s},getRegex:()=>new RegExp(n,t)};return s}function k(e){try{e=encodeURI(e).replace(/%25/g,"%")}catch(e){return null}return e}const g={exec:()=>null};function f(e,t){const n=e.replace(/\|/g,((e,t,n)=>{let s=!1,r=t;for(;--r>=0&&"\\"===n[r];)s=!s;return s?"|":" |"})).split(/ \|/);let s=0;if(n[0].trim()||n.shift(),n.length>0&&!n[n.length-1].trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length0)return{type:"space",raw:t[0]}}code(e){const t=this.rules.block.code.exec(e);if(t){const e=t[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?e:d(e,"\n")}}}fences(e){const t=this.rules.block.fences.exec(e);if(t){const e=t[0],n=function(e,t){const n=e.match(/^(\s+)(?:```)/);if(null===n)return t;const s=n[1];return t.split("\n").map((e=>{const t=e.match(/^\s+/);if(null===t)return e;const[n]=t;return n.length>=s.length?e.slice(s.length):e})).join("\n")}(e,t[3]||"");return{type:"code",raw:e,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:n}}}heading(e){const t=this.rules.block.heading.exec(e);if(t){let e=t[2].trim();if(/#$/.test(e)){const t=d(e,"#");this.options.pedantic?e=t.trim():t&&!/ $/.test(t)||(e=t.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:e,tokens:this.lexer.inline(e)}}}hr(e){const t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:d(t[0],"\n")}}blockquote(e){const t=this.rules.block.blockquote.exec(e);if(t){let e=d(t[0],"\n").split("\n"),n="",s="";const r=[];for(;e.length>0;){let t=!1;const i=[];let l;for(l=0;l/.test(e[l]))i.push(e[l]),t=!0;else{if(t)break;i.push(e[l])}e=e.slice(l);const o=i.join("\n"),a=o.replace(/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,"\n $1").replace(/^ {0,3}>[ \t]?/gm,"");n=n?`${n}\n${o}`:o,s=s?`${s}\n${a}`:a;const c=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(a,r,!0),this.lexer.state.top=c,0===e.length)break;const h=r[r.length-1];if("code"===h?.type)break;if("blockquote"===h?.type){const t=h,i=t.raw+"\n"+e.join("\n"),l=this.blockquote(i);r[r.length-1]=l,n=n.substring(0,n.length-t.raw.length)+l.raw,s=s.substring(0,s.length-t.text.length)+l.text;break}if("list"!==h?.type);else{const t=h,i=t.raw+"\n"+e.join("\n"),l=this.list(i);r[r.length-1]=l,n=n.substring(0,n.length-h.raw.length)+l.raw,s=s.substring(0,s.length-t.raw.length)+l.raw,e=i.substring(r[r.length-1].raw.length).split("\n")}}return{type:"blockquote",raw:n,tokens:r,text:s}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim();const s=n.length>1,r={type:"list",raw:"",ordered:s,start:s?+n.slice(0,-1):"",loose:!1,items:[]};n=s?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=s?n:"[*+-]");const i=new RegExp(`^( {0,3}${n})((?:[\t ][^\\n]*)?(?:\\n|$))`);let l="",o="",a=!1;for(;e;){let n=!1;if(!(t=i.exec(e)))break;if(this.rules.block.hr.test(e))break;l=t[0],e=e.substring(l.length);let s=t[2].split("\n",1)[0].replace(/^\t+/,(e=>" ".repeat(3*e.length))),c=e.split("\n",1)[0],h=0;this.options.pedantic?(h=2,o=s.trimStart()):(h=t[2].search(/[^ ]/),h=h>4?1:h,o=s.slice(h),h+=t[1].length);let p=!1;if(!s&&/^ *$/.test(c)&&(l+=c+"\n",e=e.substring(c.length+1),n=!0),!n){const t=new RegExp(`^ {0,${Math.min(3,h-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ \t][^\\n]*)?(?:\\n|$))`),n=new RegExp(`^ {0,${Math.min(3,h-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),r=new RegExp(`^ {0,${Math.min(3,h-1)}}(?:\`\`\`|~~~)`),i=new RegExp(`^ {0,${Math.min(3,h-1)}}#`);for(;e;){const a=e.split("\n",1)[0];if(c=a,this.options.pedantic&&(c=c.replace(/^ {1,4}(?=( {4})*[^ ])/g," ")),r.test(c))break;if(i.test(c))break;if(t.test(c))break;if(n.test(e))break;if(c.search(/[^ ]/)>=h||!c.trim())o+="\n"+c.slice(h);else{if(p)break;if(s.search(/[^ ]/)>=4)break;if(r.test(s))break;if(i.test(s))break;if(n.test(s))break;o+="\n"+c}p||c.trim()||(p=!0),l+=a+"\n",e=e.substring(a.length+1),s=c.slice(h)}}r.loose||(a?r.loose=!0:/\n *\n *$/.test(l)&&(a=!0));let u,k=null;this.options.gfm&&(k=/^\[[ xX]\] /.exec(o),k&&(u="[ ] "!==k[0],o=o.replace(/^\[[ xX]\] +/,""))),r.items.push({type:"list_item",raw:l,task:!!k,checked:u,loose:!1,text:o,tokens:[]}),r.raw+=l}r.items[r.items.length-1].raw=l.trimEnd(),r.items[r.items.length-1].text=o.trimEnd(),r.raw=r.raw.trimEnd();for(let e=0;e"space"===e.type)),n=t.length>0&&t.some((e=>/\n.*\n/.test(e.raw)));r.loose=n}if(r.loose)for(let e=0;e$/,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",s=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:e,raw:t[0],href:n,title:s}}}table(e){const t=this.rules.block.table.exec(e);if(!t)return;if(!/[:|]/.test(t[2]))return;const n=f(t[1]),s=t[2].replace(/^\||\| *$/g,"").split("|"),r=t[3]&&t[3].trim()?t[3].replace(/\n[ \t]*$/,"").split("\n"):[],i={type:"table",raw:t[0],header:[],align:[],rows:[]};if(n.length===s.length){for(const e of s)/^ *-+: *$/.test(e)?i.align.push("right"):/^ *:-+: *$/.test(e)?i.align.push("center"):/^ *:-+ *$/.test(e)?i.align.push("left"):i.align.push(null);for(let e=0;e({text:e,tokens:this.lexer.inline(e),header:!1,align:i.align[t]}))));return i}}lheading(e){const t=this.rules.block.lheading.exec(e);if(t)return{type:"heading",raw:t[0],depth:"="===t[2].charAt(0)?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){const t=this.rules.block.paragraph.exec(e);if(t){const e="\n"===t[1].charAt(t[1].length-1)?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:e,tokens:this.lexer.inline(e)}}}text(e){const t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){const t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:c(t[1])}}tag(e){const t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&/^
    /i.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){const t=this.rules.inline.link.exec(e);if(t){const e=t[2].trim();if(!this.options.pedantic&&/^$/.test(e))return;const t=d(e.slice(0,-1),"\\");if((e.length-t.length)%2==0)return}else{const e=function(e,t){if(-1===e.indexOf(t[1]))return-1;let n=0;for(let s=0;s-1){const n=(0===t[0].indexOf("!")?5:4)+t[1].length+e;t[2]=t[2].substring(0,e),t[0]=t[0].substring(0,n).trim(),t[3]=""}}let n=t[2],s="";if(this.options.pedantic){const e=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(n);e&&(n=e[1],s=e[3])}else s=t[3]?t[3].slice(1,-1):"";return n=n.trim(),/^$/.test(e)?n.slice(1):n.slice(1,-1)),x(t,{href:n?n.replace(this.rules.inline.anyPunctuation,"$1"):n,title:s?s.replace(this.rules.inline.anyPunctuation,"$1"):s},t[0],this.lexer)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){const e=t[(n[2]||n[1]).replace(/\s+/g," ").toLowerCase()];if(!e){const e=n[0].charAt(0);return{type:"text",raw:e,text:e}}return x(n,e,n[0],this.lexer)}}emStrong(e,t,n=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!s)return;if(s[3]&&n.match(/[\p{L}\p{N}]/u))return;if(!(s[1]||s[2]||"")||!n||this.rules.inline.punctuation.exec(n)){const n=[...s[0]].length-1;let r,i,l=n,o=0;const a="*"===s[0][0]?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(a.lastIndex=0,t=t.slice(-1*e.length+n);null!=(s=a.exec(t));){if(r=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!r)continue;if(i=[...r].length,s[3]||s[4]){l+=i;continue}if((s[5]||s[6])&&n%3&&!((n+i)%3)){o+=i;continue}if(l-=i,l>0)continue;i=Math.min(i,i+l+o);const t=[...s[0]][0].length,a=e.slice(0,n+s.index+t+i);if(Math.min(n,i)%2){const e=a.slice(1,-1);return{type:"em",raw:a,text:e,tokens:this.lexer.inlineTokens(e)}}const c=a.slice(2,-2);return{type:"strong",raw:a,text:c,tokens:this.lexer.inlineTokens(c)}}}}codespan(e){const t=this.rules.inline.code.exec(e);if(t){let e=t[2].replace(/\n/g," ");const n=/[^ ]/.test(e),s=/^ /.test(e)&&/ $/.test(e);return n&&s&&(e=e.substring(1,e.length-1)),e=c(e,!0),{type:"codespan",raw:t[0],text:e}}}br(e){const t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e){const t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e){const t=this.rules.inline.autolink.exec(e);if(t){let e,n;return"@"===t[2]?(e=c(t[1]),n="mailto:"+e):(e=c(t[1]),n=e),{type:"link",raw:t[0],text:e,href:n,tokens:[{type:"text",raw:e,text:e}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let e,n;if("@"===t[2])e=c(t[0]),n="mailto:"+e;else{let s;do{s=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??""}while(s!==t[0]);e=c(t[0]),n="www."===t[1]?"http://"+t[0]:t[0]}return{type:"link",raw:t[0],text:e,href:n,tokens:[{type:"text",raw:e,text:e}]}}}inlineText(e){const t=this.rules.inline.text.exec(e);if(t){let e;return e=this.lexer.state.inRawBlock?t[0]:c(t[0]),{type:"text",raw:t[0],text:e}}}}const w=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,m=/(?:[*+-]|\d{1,9}[.)])/,y=u(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/).replace(/bull/g,m).replace(/blockCode/g,/ {4}/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).getRegex(),$=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,z=/(?!\s*\])(?:\\.|[^\[\]\\])+/,T=u(/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/).replace("label",z).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),R=u(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,m).getRegex(),_="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",A=/|$))/,S=u("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))","i").replace("comment",A).replace("tag",_).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),I=u($).replace("hr",w).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",_).getRegex(),E={blockquote:u(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",I).getRegex(),code:/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,def:T,fences:/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,heading:/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,hr:w,html:S,lheading:y,list:R,newline:/^(?: *(?:\n|$))+/,paragraph:I,table:g,text:/^[^\n]+/},q=u("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",w).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",_).getRegex(),Z={...E,table:q,paragraph:u($).replace("hr",w).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",q).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",_).getRegex()},L={...E,html:u("^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))").replace("comment",A).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:g,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:u($).replace("hr",w).replace("heading"," *#{1,6} *[^\n]").replace("lheading",y).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},P=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,v=/^( {2,}|\\)\n(?!\s*$)/,Q="\\p{P}\\p{S}",B=u(/^((?![*_])[\spunctuation])/,"u").replace(/punctuation/g,Q).getRegex(),C=u(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/,"u").replace(/punct/g,Q).getRegex(),M=u("^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)[punct](\\*+)(?=[\\s]|$)|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])|[\\s](\\*+)(?!\\*)(?=[punct])|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])|[^punct\\s](\\*+)(?=[^punct\\s])","gu").replace(/punct/g,Q).getRegex(),O=u("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)[punct](_+)(?=[\\s]|$)|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)|(?!_)[punct\\s](_+)(?=[^punct\\s])|[\\s](_+)(?!_)(?=[punct])|(?!_)[punct](_+)(?!_)(?=[punct])","gu").replace(/punct/g,Q).getRegex(),j=u(/\\([punct])/,"gu").replace(/punct/g,Q).getRegex(),D=u(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),H=u(A).replace("(?:--\x3e|$)","--\x3e").getRegex(),F=u("^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment",H).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),U=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,X=u(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/).replace("label",U).replace("href",/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),N=u(/^!?\[(label)\]\[(ref)\]/).replace("label",U).replace("ref",z).getRegex(),G=u(/^!?\[(ref)\](?:\[\])?/).replace("ref",z).getRegex(),J={_backpedal:g,anyPunctuation:j,autolink:D,blockSkip:/\[[^[\]]*?\]\([^\(\)]*?\)|`[^`]*?`|<[^<>]*?>/g,br:v,code:/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,del:g,emStrongLDelim:C,emStrongRDelimAst:M,emStrongRDelimUnd:O,escape:P,link:X,nolink:G,punctuation:B,reflink:N,reflinkSearch:u("reflink|nolink(?!\\()","g").replace("reflink",N).replace("nolink",G).getRegex(),tag:F,text:/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\t+" ".repeat(n.length)));e;)if(!(this.options.extensions&&this.options.extensions.block&&this.options.extensions.block.some((n=>!!(s=n.call({lexer:this},e,t))&&(e=e.substring(s.raw.length),t.push(s),!0)))))if(s=this.tokenizer.space(e))e=e.substring(s.raw.length),1===s.raw.length&&t.length>0?t[t.length-1].raw+="\n":t.push(s);else if(s=this.tokenizer.code(e))e=e.substring(s.raw.length),r=t[t.length-1],!r||"paragraph"!==r.type&&"text"!==r.type?t.push(s):(r.raw+="\n"+s.raw,r.text+="\n"+s.text,this.inlineQueue[this.inlineQueue.length-1].src=r.text);else if(s=this.tokenizer.fences(e))e=e.substring(s.raw.length),t.push(s);else if(s=this.tokenizer.heading(e))e=e.substring(s.raw.length),t.push(s);else if(s=this.tokenizer.hr(e))e=e.substring(s.raw.length),t.push(s);else if(s=this.tokenizer.blockquote(e))e=e.substring(s.raw.length),t.push(s);else if(s=this.tokenizer.list(e))e=e.substring(s.raw.length),t.push(s);else if(s=this.tokenizer.html(e))e=e.substring(s.raw.length),t.push(s);else if(s=this.tokenizer.def(e))e=e.substring(s.raw.length),r=t[t.length-1],!r||"paragraph"!==r.type&&"text"!==r.type?this.tokens.links[s.tag]||(this.tokens.links[s.tag]={href:s.href,title:s.title}):(r.raw+="\n"+s.raw,r.text+="\n"+s.raw,this.inlineQueue[this.inlineQueue.length-1].src=r.text);else if(s=this.tokenizer.table(e))e=e.substring(s.raw.length),t.push(s);else if(s=this.tokenizer.lheading(e))e=e.substring(s.raw.length),t.push(s);else{if(i=e,this.options.extensions&&this.options.extensions.startBlock){let t=1/0;const n=e.slice(1);let s;this.options.extensions.startBlock.forEach((e=>{s=e.call({lexer:this},n),"number"==typeof s&&s>=0&&(t=Math.min(t,s))})),t<1/0&&t>=0&&(i=e.substring(0,t+1))}if(this.state.top&&(s=this.tokenizer.paragraph(i)))r=t[t.length-1],n&&"paragraph"===r?.type?(r.raw+="\n"+s.raw,r.text+="\n"+s.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=r.text):t.push(s),n=i.length!==e.length,e=e.substring(s.raw.length);else if(s=this.tokenizer.text(e))e=e.substring(s.raw.length),r=t[t.length-1],r&&"text"===r.type?(r.raw+="\n"+s.raw,r.text+="\n"+s.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=r.text):t.push(s);else if(e){const t="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(t);break}throw new Error(t)}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){let n,s,r,i,l,o,a=e;if(this.tokens.links){const e=Object.keys(this.tokens.links);if(e.length>0)for(;null!=(i=this.tokenizer.rules.inline.reflinkSearch.exec(a));)e.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(a=a.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+a.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;null!=(i=this.tokenizer.rules.inline.blockSkip.exec(a));)a=a.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+a.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);for(;null!=(i=this.tokenizer.rules.inline.anyPunctuation.exec(a));)a=a.slice(0,i.index)+"++"+a.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);for(;e;)if(l||(o=""),l=!1,!(this.options.extensions&&this.options.extensions.inline&&this.options.extensions.inline.some((s=>!!(n=s.call({lexer:this},e,t))&&(e=e.substring(n.raw.length),t.push(n),!0)))))if(n=this.tokenizer.escape(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.tag(e))e=e.substring(n.raw.length),s=t[t.length-1],s&&"text"===n.type&&"text"===s.type?(s.raw+=n.raw,s.text+=n.text):t.push(n);else if(n=this.tokenizer.link(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.reflink(e,this.tokens.links))e=e.substring(n.raw.length),s=t[t.length-1],s&&"text"===n.type&&"text"===s.type?(s.raw+=n.raw,s.text+=n.text):t.push(n);else if(n=this.tokenizer.emStrong(e,a,o))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.codespan(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.br(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.del(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.autolink(e))e=e.substring(n.raw.length),t.push(n);else if(this.state.inLink||!(n=this.tokenizer.url(e))){if(r=e,this.options.extensions&&this.options.extensions.startInline){let t=1/0;const n=e.slice(1);let s;this.options.extensions.startInline.forEach((e=>{s=e.call({lexer:this},n),"number"==typeof s&&s>=0&&(t=Math.min(t,s))})),t<1/0&&t>=0&&(r=e.substring(0,t+1))}if(n=this.tokenizer.inlineText(r))e=e.substring(n.raw.length),"_"!==n.raw.slice(-1)&&(o=n.raw.slice(-1)),l=!0,s=t[t.length-1],s&&"text"===s.type?(s.raw+=n.raw,s.text+=n.text):t.push(n);else if(e){const t="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(t);break}throw new Error(t)}}else e=e.substring(n.raw.length),t.push(n);return t}}class ne{options;parser;constructor(t){this.options=t||e.defaults}space(e){return""}code({text:e,lang:t,escaped:n}){const s=(t||"").match(/^\S*/)?.[0],r=e.replace(/\n$/,"")+"\n";return s?'
    '+(n?r:c(r,!0))+"
    \n":"
    "+(n?r:c(r,!0))+"
    \n"}blockquote({tokens:e}){return`
    \n${this.parser.parse(e)}
    \n`}html({text:e}){return e}heading({tokens:e,depth:t}){return`${this.parser.parseInline(e)}\n`}hr(e){return"
    \n"}list(e){const t=e.ordered,n=e.start;let s="";for(let t=0;t\n"+s+"\n"}listitem(e){let t="";if(e.task){const n=this.checkbox({checked:!!e.checked});e.loose?e.tokens.length>0&&"paragraph"===e.tokens[0].type?(e.tokens[0].text=n+" "+e.tokens[0].text,e.tokens[0].tokens&&e.tokens[0].tokens.length>0&&"text"===e.tokens[0].tokens[0].type&&(e.tokens[0].tokens[0].text=n+" "+e.tokens[0].tokens[0].text)):e.tokens.unshift({type:"text",raw:n+" ",text:n+" "}):t+=n+" "}return t+=this.parser.parse(e.tokens,!!e.loose),`
  • ${t}
  • \n`}checkbox({checked:e}){return"'}paragraph({tokens:e}){return`

    ${this.parser.parseInline(e)}

    \n`}table(e){let t="",n="";for(let t=0;t${s}`),"\n\n"+t+"\n"+s+"
    \n"}tablerow({text:e}){return`\n${e}\n`}tablecell(e){const t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`\n`}strong({tokens:e}){return`${this.parser.parseInline(e)}`}em({tokens:e}){return`${this.parser.parseInline(e)}`}codespan({text:e}){return`${e}`}br(e){return"
    "}del({tokens:e}){return`${this.parser.parseInline(e)}`}link({href:e,title:t,tokens:n}){const s=this.parser.parseInline(n),r=k(e);if(null===r)return s;let i='
    ",i}image({href:e,title:t,text:n}){const s=k(e);if(null===s)return n;let r=`${n}{const r=e[s].flat(1/0);n=n.concat(this.walkTokens(r,t))})):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}use(...e){const t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach((e=>{const n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach((e=>{if(!e.name)throw new Error("extension name required");if("renderer"in e){const n=t.renderers[e.name];t.renderers[e.name]=n?function(...t){let s=e.renderer.apply(this,t);return!1===s&&(s=n.apply(this,t)),s}:e.renderer}if("tokenizer"in e){if(!e.level||"block"!==e.level&&"inline"!==e.level)throw new Error("extension level must be 'block' or 'inline'");const n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&("block"===e.level?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:"inline"===e.level&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}"childTokens"in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)})),n.extensions=t),e.renderer){const t=this.defaults.renderer||new ne(this.defaults);for(const n in e.renderer){if(!(n in t))throw new Error(`renderer '${n}' does not exist`);if(["options","parser"].includes(n))continue;const s=n;let r=e.renderer[s];const i=t[s];t[s]=(...n)=>{e.useNewRenderer||(r=this.#t(r,s,t));let l=r.apply(t,n);return!1===l&&(l=i.apply(t,n)),l||""}}n.renderer=t}if(e.tokenizer){const t=this.defaults.tokenizer||new b(this.defaults);for(const n in e.tokenizer){if(!(n in t))throw new Error(`tokenizer '${n}' does not exist`);if(["options","rules","lexer"].includes(n))continue;const s=n,r=e.tokenizer[s],i=t[s];t[s]=(...e)=>{let n=r.apply(t,e);return!1===n&&(n=i.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){const t=this.defaults.hooks||new ie;for(const n in e.hooks){if(!(n in t))throw new Error(`hook '${n}' does not exist`);if("options"===n)continue;const s=n,r=e.hooks[s],i=t[s];ie.passThroughHooks.has(n)?t[s]=e=>{if(this.defaults.async)return Promise.resolve(r.call(t,e)).then((e=>i.call(t,e)));const n=r.call(t,e);return i.call(t,n)}:t[s]=(...e)=>{let n=r.apply(t,e);return!1===n&&(n=i.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){const t=this.defaults.walkTokens,s=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(s.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}})),this}#t(e,t,n){switch(t){case"heading":return function(s){return s.type&&s.type===t?e.call(this,n.parser.parseInline(s.tokens),s.depth,function(e){return e.replace(h,((e,t)=>"colon"===(t=t.toLowerCase())?":":"#"===t.charAt(0)?"x"===t.charAt(1)?String.fromCharCode(parseInt(t.substring(2),16)):String.fromCharCode(+t.substring(1)):""))}(n.parser.parseInline(s.tokens,n.parser.textRenderer))):e.apply(this,arguments)};case"code":return function(n){return n.type&&n.type===t?e.call(this,n.text,n.lang,!!n.escaped):e.apply(this,arguments)};case"table":return function(n){if(!n.type||n.type!==t)return e.apply(this,arguments);let s="",r="";for(let e=0;e0&&"paragraph"===t.tokens[0].type?(t.tokens[0].text=e+" "+t.tokens[0].text,t.tokens[0].tokens&&t.tokens[0].tokens.length>0&&"text"===t.tokens[0].tokens[0].type&&(t.tokens[0].tokens[0].text=e+" "+t.tokens[0].tokens[0].text)):t.tokens.unshift({type:"text",text:e+" "}):o+=e+" "}o+=this.parser.parse(t.tokens,i),l+=this.listitem({type:"list_item",raw:o,text:o,task:r,checked:!!s,loose:i,tokens:t.tokens})}return e.call(this,l,s,r)};case"html":return function(n){return n.type&&n.type===t?e.call(this,n.text,n.block):e.apply(this,arguments)};case"paragraph":case"strong":case"em":case"del":return function(n){return n.type&&n.type===t?e.call(this,this.parser.parseInline(n.tokens)):e.apply(this,arguments)};case"escape":case"codespan":case"text":return function(n){return n.type&&n.type===t?e.call(this,n.text):e.apply(this,arguments)};case"link":return function(n){return n.type&&n.type===t?e.call(this,n.href,n.title,this.parser.parseInline(n.tokens)):e.apply(this,arguments)};case"image":return function(n){return n.type&&n.type===t?e.call(this,n.href,n.title,n.text):e.apply(this,arguments)}}return e}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return te.lex(e,t??this.defaults)}parser(e,t){return re.parse(e,t??this.defaults)}#e(e,t){return(n,s)=>{const r={...s},i={...this.defaults,...r};!0===this.defaults.async&&!1===r.async&&(i.silent||console.warn("marked(): The async option was set to true by an extension. The async: false option sent to parse will be ignored."),i.async=!0);const l=this.#n(!!i.silent,!!i.async);if(null==n)return l(new Error("marked(): input parameter is undefined or null"));if("string"!=typeof n)return l(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(i.hooks&&(i.hooks.options=i),i.async)return Promise.resolve(i.hooks?i.hooks.preprocess(n):n).then((t=>e(t,i))).then((e=>i.hooks?i.hooks.processAllTokens(e):e)).then((e=>i.walkTokens?Promise.all(this.walkTokens(e,i.walkTokens)).then((()=>e)):e)).then((e=>t(e,i))).then((e=>i.hooks?i.hooks.postprocess(e):e)).catch(l);try{i.hooks&&(n=i.hooks.preprocess(n));let s=e(n,i);i.hooks&&(s=i.hooks.processAllTokens(s)),i.walkTokens&&this.walkTokens(s,i.walkTokens);let r=t(s,i);return i.hooks&&(r=i.hooks.postprocess(r)),r}catch(e){return l(e)}}}#n(e,t){return n=>{if(n.message+="\nPlease report this to https://github.com/markedjs/marked.",e){const e="

    An error occurred:

    "+c(n.message+"",!0)+"
    ";return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}}const oe=new le;function ae(e,t){return oe.parse(e,t)}ae.options=ae.setOptions=function(e){return oe.setOptions(e),ae.defaults=oe.defaults,n(ae.defaults),ae},ae.getDefaults=t,ae.defaults=e.defaults,ae.use=function(...e){return oe.use(...e),ae.defaults=oe.defaults,n(ae.defaults),ae},ae.walkTokens=function(e,t){return oe.walkTokens(e,t)},ae.parseInline=oe.parseInline,ae.Parser=re,ae.parser=re.parse,ae.Renderer=ne,ae.TextRenderer=se,ae.Lexer=te,ae.lexer=te.lex,ae.Tokenizer=b,ae.Hooks=ie,ae.parse=ae;const ce=ae.options,he=ae.setOptions,pe=ae.use,ue=ae.walkTokens,ke=ae.parseInline,ge=ae,fe=re.parse,de=te.lex;e.Hooks=ie,e.Lexer=te,e.Marked=le,e.Parser=re,e.Renderer=ne,e.TextRenderer=se,e.Tokenizer=b,e.getDefaults=t,e.lexer=de,e.marked=ae,e.options=ce,e.parse=ge,e.parseInline=ke,e.parser=fe,e.setOptions=he,e.use=pe,e.walkTokens=ue})); diff --git a/scripts/node_modules/marked/package.json b/scripts/node_modules/marked/package.json new file mode 100644 index 000000000..c09a7e1f5 --- /dev/null +++ b/scripts/node_modules/marked/package.json @@ -0,0 +1,111 @@ +{ + "name": "marked", + "description": "A markdown parser built for speed", + "author": "Christopher Jeffrey", + "version": "13.0.1", + "type": "module", + "main": "./lib/marked.cjs", + "module": "./lib/marked.esm.js", + "browser": "./lib/marked.umd.js", + "types": "./lib/marked.d.ts", + "bin": { + "marked": "bin/marked.js" + }, + "man": "./man/marked.1", + "files": [ + "bin/", + "lib/", + "man/", + "marked.min.js" + ], + "exports": { + ".": { + "import": { + "types": "./lib/marked.d.ts", + "default": "./lib/marked.esm.js" + }, + "default": { + "types": "./lib/marked.d.cts", + "default": "./lib/marked.cjs" + } + }, + "./bin/marked": "./bin/marked.js", + "./marked.min.js": "./marked.min.js", + "./package.json": "./package.json" + }, + "publishConfig": { + "provenance": true + }, + "repository": "git://github.com/markedjs/marked.git", + "homepage": "https://marked.js.org", + "bugs": { + "url": "http://github.com/markedjs/marked/issues" + }, + "license": "MIT", + "keywords": [ + "markdown", + "markup", + "html" + ], + "tags": [ + "markdown", + "markup", + "html" + ], + "devDependencies": { + "@markedjs/testutils": "12.0.0-0", + "@arethetypeswrong/cli": "^0.15.3", + "@rollup/plugin-terser": "^0.4.4", + "@rollup/plugin-typescript": "^11.1.6", + "@semantic-release/commit-analyzer": "^13.0.0", + "@semantic-release/git": "^10.0.1", + "@semantic-release/github": "^10.0.6", + "@semantic-release/npm": "^12.0.1", + "@semantic-release/release-notes-generator": "^14.0.0", + "@typescript-eslint/eslint-plugin": "^7.13.0", + "@typescript-eslint/parser": "^7.13.1", + "cheerio": "1.0.0-rc.12", + "commonmark": "0.31.0", + "cross-env": "^7.0.3", + "dts-bundle-generator": "^9.5.1", + "eslint": "^8.57.0", + "eslint-config-standard": "^17.1.0", + "eslint-plugin-import": "^2.29.1", + "eslint-plugin-n": "^16.6.2", + "eslint-plugin-promise": "^6.2.0", + "highlight.js": "^11.9.0", + "markdown-it": "14.1.0", + "marked-highlight": "^2.1.2", + "marked-man": "^2.1.0", + "node-fetch": "^3.3.2", + "recheck": "^4.4.5", + "rollup": "^4.18.0", + "semantic-release": "^24.0.0", + "titleize": "^4.0.0", + "ts-expect": "^1.3.0", + "typescript": "5.4.5" + }, + "scripts": { + "test": "npm run build && npm run test:specs && npm run test:unit", + "test:all": "npm test && npm run test:umd && npm run test:types && npm run test:lint", + "test:unit": "node --test --test-reporter=spec test/unit/*.test.js", + "test:specs": "node --test --test-reporter=spec test/run-spec-tests.js", + "test:lint": "eslint .", + "test:redos": "node test/recheck.js > vuln.js", + "test:types": "tsc --project tsconfig-type-test.json && attw -P --exclude-entrypoints ./bin/marked ./marked.min.js", + "test:umd": "node test/umd-test.js", + "test:update": "node test/update-specs.js", + "rules": "node test/rules.js", + "bench": "npm run build && node test/bench.js", + "lint": "eslint --fix .", + "build:reset": "git checkout upstream/master lib/marked.cjs lib/marked.umd.js lib/marked.esm.js marked.min.js", + "build": "npm run rollup && npm run build:types && npm run build:man", + "build:docs": "npm run build && node docs/build.js", + "build:types": "tsc && dts-bundle-generator --project tsconfig.json -o lib/marked.d.ts src/marked.ts && dts-bundle-generator --project tsconfig.json -o lib/marked.d.cts src/marked.ts", + "build:man": "marked-man man/marked.1.md > man/marked.1", + "rollup": "rollup -c rollup.config.js" + }, + "engines": { + "node": ">= 18" + } +} diff --git a/scripts/node_modules/section-matter/LICENSE b/scripts/node_modules/section-matter/LICENSE new file mode 100644 index 000000000..5385a0983 --- /dev/null +++ b/scripts/node_modules/section-matter/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017, Jon Schlinkert. + +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/scripts/node_modules/section-matter/README.md b/scripts/node_modules/section-matter/README.md new file mode 100644 index 000000000..95a7a4619 --- /dev/null +++ b/scripts/node_modules/section-matter/README.md @@ -0,0 +1,236 @@ +# section-matter [![NPM version](https://img.shields.io/npm/v/section-matter.svg?style=flat)](https://www.npmjs.com/package/section-matter) [![NPM monthly downloads](https://img.shields.io/npm/dm/section-matter.svg?style=flat)](https://npmjs.org/package/section-matter) [![NPM total downloads](https://img.shields.io/npm/dt/section-matter.svg?style=flat)](https://npmjs.org/package/section-matter) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/section-matter.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/section-matter) + +> Like front-matter, but supports multiple sections in a document. + +Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. + +## Install +Install with [npm](https://www.npmjs.com/): + +```sh +$ npm install --save section-matter +``` + +## Usage + +**Params** + +* `input` **{String|Buffer|Object}**: If input is an object, it's `content` property must be a string or buffer. +* **{Object}**: options +* `returns` **{Object}**: Returns an object with a `content` string and an array of `sections` objects. + +**Example** + +```js +var sections = require('{%= name %}'); +var result = sections(input, options); +// { content: 'Content before sections', sections: [] } +``` + +See available [options](#options). + +## Example + +_With the exception of front-matter, **which must be the very first thing in the string**, the opening delimiter of all other sections must be followed by a string to be used as the `key` for the section._ + +Given the following string: + +``` +Content before the sections. + +--- + +More content. + +---one +title: One +--- + +This is the first section. +``` + +The following code: + +```js +console.log(sections(input)); +``` + +Results in: + +```js +{ + content: 'Content before the sections.\n\n---\n\nMore content.\n', + sections: [ + { + key: 'one', + data: 'title: One', + content: '\nThis is the first section.' + } + ] +} +``` + +## Options + +### options.section_parse + +**Type**: `function` + +**Default**: `undefined` + +Function to be called on each section after it's parsed from the string. + +**Example** + +Given the following string (`foo.md`): + +``` +This is content before the sections. + +---one +title: First section +--- + +This is section one. + +---two +title: Second section +--- + +This is section two. +``` + +Using the following custom `section_parse` function: + +```js +var fs = require('fs'); +var path = require('path'); +var yaml = require('js-yaml'); +var sections = require('section-matter'); + +var str = fs.readFileSync('foo.md'); +var options = { + section_parse: function(section) { + console.log(section) + section.key = 'section-' + section.key; + section.data = yaml.safeLoad(section.data); + } +}; + +var result = sections(str, options); +console.log(result); +``` + +Results in: + +```js +{ + content: 'This is content before the sections.\n', + sections: [ + { + key: 'section-one', + data: { title: 'First section' }, + content: '\nThis is section one.\n' + }, + { + key: 'section-two', + data: { title: 'Second section' }, + content: '\nThis is section two.\n' + } + ] +} +``` + +### options.section_delimiter + +**Type**: `string` + +**Default**: `---` + +Delimiter to use as the separator for sections. _With the exception of front-matter, which must be the very first thing in the string, the opening delimiter of all other sections must be followed by a string to be used as the `key` for the section._ + +**Example** + +```js +var input = '~~~\ntitle: bar\n~~~\n\nfoo\n~~~one\ntitle: One\n~~~\nThis is one'; +console.log(sections(input, {section_delimiter: '~~~'})); +``` + +Results in: + +```js +{ + content: '', + sections: [ + { + key: '', + data: 'title: bar', + content: '\nfoo' + }, + { + key: 'one', + data: 'title: One', + content: 'This is one' + } + ] +} +``` + +## About +
    + Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +Please read the [contributing guide](.github/contributing.md) for advice on opening issues, pull requests, and coding standards. + +
    + +
    + Running Tests + +Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: + +```sh +$ npm install && npm test +``` + +
    + +
    + Building docs + +_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ + +To generate the readme, run the following command: + +```sh +$ npm install -g verbose/verb#dev verb-generate-readme && verb +``` + +
    + +### Related projects + +You might also be interested in these projects: + +- [assemble](https://www.npmjs.com/package/assemble): Get the rocks out of your socks! Assemble makes you fast at creating web projects… [more](https://github.com/assemble/assemble) | [homepage](https://github.com/assemble/assemble "Get the rocks out of your socks! Assemble makes you fast at creating web projects. Assemble is used by thousands of projects for rapid prototyping, creating themes, scaffolds, boilerplates, e-books, UI components, API documentation, blogs, building websit") +- [gray-matter](https://www.npmjs.com/package/gray-matter): Parse front-matter from a string or file. Fast, reliable and easy to use. Parses YAML… [more](https://github.com/jonschlinkert/gray-matter) | [homepage](https://github.com/jonschlinkert/gray-matter "Parse front-matter from a string or file. Fast, reliable and easy to use. Parses YAML front matter by default, but also has support for YAML, JSON, TOML or Coffee Front-Matter, with options to set custom delimiters. Used by metalsmith, assemble, verb and ") +- [verb](https://www.npmjs.com/package/verb): Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used… [more](https://github.com/verbose/verb) | [homepage](https://github.com/verbose/verb "Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used on hundreds of projects of all sizes to generate everything from API docs to readmes.") + +### Contributors + +### Author +**Jon Schlinkert** + ++ [github/jonschlinkert](https://github.com/jonschlinkert) ++ [twitter/jonschlinkert](https://twitter.com/jonschlinkert) + +### License +Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT License](LICENSE). + +*** + +_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on October 23, 2017._ + diff --git a/scripts/node_modules/section-matter/index.js b/scripts/node_modules/section-matter/index.js new file mode 100644 index 000000000..2b4d21e8f --- /dev/null +++ b/scripts/node_modules/section-matter/index.js @@ -0,0 +1,136 @@ +'use strict'; + +var typeOf = require('kind-of'); +var extend = require('extend-shallow'); + +/** + * Parse sections in `input` with the given `options`. + * + * ```js + * var sections = require('{%= name %}'); + * var result = sections(input, options); + * // { content: 'Content before sections', sections: [] } + * ``` + * @param {String|Buffer|Object} `input` If input is an object, it's `content` property must be a string or buffer. + * @param {Object} options + * @return {Object} Returns an object with a `content` string and an array of `sections` objects. + * @api public + */ + +module.exports = function(input, options) { + if (typeof options === 'function') { + options = { parse: options }; + } + + var file = toObject(input); + var defaults = {section_delimiter: '---', parse: identity}; + var opts = extend({}, defaults, options); + var delim = opts.section_delimiter; + var lines = file.content.split(/\r?\n/); + var sections = null; + var section = createSection(); + var content = []; + var stack = []; + + function initSections(val) { + file.content = val; + sections = []; + content = []; + } + + function closeSection(val) { + if (stack.length) { + section.key = getKey(stack[0], delim); + section.content = val; + opts.parse(section, sections); + sections.push(section); + section = createSection(); + content = []; + stack = []; + } + } + + for (var i = 0; i < lines.length; i++) { + var line = lines[i]; + var len = stack.length; + var ln = line.trim(); + + if (isDelimiter(ln, delim)) { + if (ln.length === 3 && i !== 0) { + if (len === 0 || len === 2) { + content.push(line); + continue; + } + stack.push(ln); + section.data = content.join('\n'); + content = []; + continue; + } + + if (sections === null) { + initSections(content.join('\n')); + } + + if (len === 2) { + closeSection(content.join('\n')); + } + + stack.push(ln); + continue; + } + + content.push(line); + } + + if (sections === null) { + initSections(content.join('\n')); + } else { + closeSection(content.join('\n')); + } + + file.sections = sections; + return file; +}; + +function isDelimiter(line, delim) { + if (line.slice(0, delim.length) !== delim) { + return false; + } + if (line.charAt(delim.length + 1) === delim.slice(-1)) { + return false; + } + return true; +} + +function toObject(input) { + if (typeOf(input) !== 'object') { + input = { content: input }; + } + + if (typeof input.content !== 'string' && !isBuffer(input.content)) { + throw new TypeError('expected a buffer or string'); + } + + input.content = input.content.toString(); + input.sections = []; + return input; +} + +function getKey(val, delim) { + return val ? val.slice(delim.length).trim() : ''; +} + +function createSection() { + return { key: '', data: '', content: '' }; +} + +function identity(val) { + return val; +} + +function isBuffer(val) { + if (val && val.constructor && typeof val.constructor.isBuffer === 'function') { + return val.constructor.isBuffer(val); + } + return false; +} diff --git a/scripts/node_modules/section-matter/package.json b/scripts/node_modules/section-matter/package.json new file mode 100644 index 000000000..a706c6d0b --- /dev/null +++ b/scripts/node_modules/section-matter/package.json @@ -0,0 +1,55 @@ +{ + "name": "section-matter", + "description": "Like front-matter, but supports multiple sections in a document.", + "version": "1.0.0", + "homepage": "https://github.com/jonschlinkert/section-matter", + "author": "Jon Schlinkert (https://github.com/jonschlinkert)", + "repository": "jonschlinkert/section-matter", + "bugs": { + "url": "https://github.com/jonschlinkert/section-matter/issues" + }, + "license": "MIT", + "files": [ + "index.js" + ], + "main": "index.js", + "engines": { + "node": ">=4" + }, + "scripts": { + "test": "mocha" + }, + "dependencies": { + "extend-shallow": "^2.0.1", + "kind-of": "^6.0.0" + }, + "devDependencies": { + "gulp-format-md": "^1.0.0", + "js-yaml": "^3.10.0", + "mocha": "^4.0.1" + }, + "keywords": [ + "matter", + "section" + ], + "verb": { + "toc": false, + "layout": "default", + "tasks": [ + "readme" + ], + "plugins": [ + "gulp-format-md" + ], + "related": { + "list": [ + "gray-matter", + "assemble", + "verb" + ] + }, + "lint": { + "reflinks": true + } + } +} diff --git a/scripts/node_modules/sprintf-js/.npmignore b/scripts/node_modules/sprintf-js/.npmignore new file mode 100644 index 000000000..096746c14 --- /dev/null +++ b/scripts/node_modules/sprintf-js/.npmignore @@ -0,0 +1 @@ +/node_modules/ \ No newline at end of file diff --git a/scripts/node_modules/sprintf-js/LICENSE b/scripts/node_modules/sprintf-js/LICENSE new file mode 100644 index 000000000..663ac52e4 --- /dev/null +++ b/scripts/node_modules/sprintf-js/LICENSE @@ -0,0 +1,24 @@ +Copyright (c) 2007-2014, Alexandru Marasteanu +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of this software nor the names of its contributors may be + used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/scripts/node_modules/sprintf-js/README.md b/scripts/node_modules/sprintf-js/README.md new file mode 100644 index 000000000..83863561b --- /dev/null +++ b/scripts/node_modules/sprintf-js/README.md @@ -0,0 +1,88 @@ +# sprintf.js +**sprintf.js** is a complete open source JavaScript sprintf implementation for the *browser* and *node.js*. + +Its prototype is simple: + + string sprintf(string format , [mixed arg1 [, mixed arg2 [ ,...]]]) + +The placeholders in the format string are marked by `%` and are followed by one or more of these elements, in this order: + +* An optional number followed by a `$` sign that selects which argument index to use for the value. If not specified, arguments will be placed in the same order as the placeholders in the input string. +* An optional `+` sign that forces to preceed the result with a plus or minus sign on numeric values. By default, only the `-` sign is used on negative numbers. +* An optional padding specifier that says what character to use for padding (if specified). Possible values are `0` or any other character precedeed by a `'` (single quote). The default is to pad with *spaces*. +* An optional `-` sign, that causes sprintf to left-align the result of this placeholder. The default is to right-align the result. +* An optional number, that says how many characters the result should have. If the value to be returned is shorter than this number, the result will be padded. When used with the `j` (JSON) type specifier, the padding length specifies the tab size used for indentation. +* An optional precision modifier, consisting of a `.` (dot) followed by a number, that says how many digits should be displayed for floating point numbers. When used with the `g` type specifier, it specifies the number of significant digits. When used on a string, it causes the result to be truncated. +* A type specifier that can be any of: + * `%` — yields a literal `%` character + * `b` — yields an integer as a binary number + * `c` — yields an integer as the character with that ASCII value + * `d` or `i` — yields an integer as a signed decimal number + * `e` — yields a float using scientific notation + * `u` — yields an integer as an unsigned decimal number + * `f` — yields a float as is; see notes on precision above + * `g` — yields a float as is; see notes on precision above + * `o` — yields an integer as an octal number + * `s` — yields a string as is + * `x` — yields an integer as a hexadecimal number (lower-case) + * `X` — yields an integer as a hexadecimal number (upper-case) + * `j` — yields a JavaScript object or array as a JSON encoded string + +## JavaScript `vsprintf` +`vsprintf` is the same as `sprintf` except that it accepts an array of arguments, rather than a variable number of arguments: + + vsprintf("The first 4 letters of the english alphabet are: %s, %s, %s and %s", ["a", "b", "c", "d"]) + +## Argument swapping +You can also swap the arguments. That is, the order of the placeholders doesn't have to match the order of the arguments. You can do that by simply indicating in the format string which arguments the placeholders refer to: + + sprintf("%2$s %3$s a %1$s", "cracker", "Polly", "wants") +And, of course, you can repeat the placeholders without having to increase the number of arguments. + +## Named arguments +Format strings may contain replacement fields rather than positional placeholders. Instead of referring to a certain argument, you can now refer to a certain key within an object. Replacement fields are surrounded by rounded parentheses - `(` and `)` - and begin with a keyword that refers to a key: + + var user = { + name: "Dolly" + } + sprintf("Hello %(name)s", user) // Hello Dolly +Keywords in replacement fields can be optionally followed by any number of keywords or indexes: + + var users = [ + {name: "Dolly"}, + {name: "Molly"}, + {name: "Polly"} + ] + sprintf("Hello %(users[0].name)s, %(users[1].name)s and %(users[2].name)s", {users: users}) // Hello Dolly, Molly and Polly +Note: mixing positional and named placeholders is not (yet) supported + +## Computed values +You can pass in a function as a dynamic value and it will be invoked (with no arguments) in order to compute the value on-the-fly. + + sprintf("Current timestamp: %d", Date.now) // Current timestamp: 1398005382890 + sprintf("Current date and time: %s", function() { return new Date().toString() }) + +# AngularJS +You can now use `sprintf` and `vsprintf` (also aliased as `fmt` and `vfmt` respectively) in your AngularJS projects. See `demo/`. + +# Installation + +## Via Bower + + bower install sprintf + +## Or as a node.js module + + npm install sprintf-js + +### Usage + + var sprintf = require("sprintf-js").sprintf, + vsprintf = require("sprintf-js").vsprintf + + sprintf("%2$s %3$s a %1$s", "cracker", "Polly", "wants") + vsprintf("The first 4 letters of the english alphabet are: %s, %s, %s and %s", ["a", "b", "c", "d"]) + +# License + +**sprintf.js** is licensed under the terms of the 3-clause BSD license. diff --git a/scripts/node_modules/sprintf-js/bower.json b/scripts/node_modules/sprintf-js/bower.json new file mode 100644 index 000000000..d90a75989 --- /dev/null +++ b/scripts/node_modules/sprintf-js/bower.json @@ -0,0 +1,14 @@ +{ + "name": "sprintf", + "description": "JavaScript sprintf implementation", + "version": "1.0.3", + "main": "src/sprintf.js", + "license": "BSD-3-Clause-Clear", + "keywords": ["sprintf", "string", "formatting"], + "authors": ["Alexandru Marasteanu (http://alexei.ro/)"], + "homepage": "https://github.com/alexei/sprintf.js", + "repository": { + "type": "git", + "url": "git://github.com/alexei/sprintf.js.git" + } +} diff --git a/scripts/node_modules/sprintf-js/demo/angular.html b/scripts/node_modules/sprintf-js/demo/angular.html new file mode 100644 index 000000000..3559efd76 --- /dev/null +++ b/scripts/node_modules/sprintf-js/demo/angular.html @@ -0,0 +1,20 @@ + + + + + + + + +
    {{ "%+010d"|sprintf:-123 }}
    +
    {{ "%+010d"|vsprintf:[-123] }}
    +
    {{ "%+010d"|fmt:-123 }}
    +
    {{ "%+010d"|vfmt:[-123] }}
    +
    {{ "I've got %2$d apples and %1$d oranges."|fmt:4:2 }}
    +
    {{ "I've got %(apples)d apples and %(oranges)d oranges."|fmt:{apples: 2, oranges: 4} }}
    + + + + diff --git a/scripts/node_modules/sprintf-js/dist/angular-sprintf.min.js b/scripts/node_modules/sprintf-js/dist/angular-sprintf.min.js new file mode 100644 index 000000000..dbaf744d8 --- /dev/null +++ b/scripts/node_modules/sprintf-js/dist/angular-sprintf.min.js @@ -0,0 +1,4 @@ +/*! sprintf-js | Alexandru Marasteanu (http://alexei.ro/) | BSD-3-Clause */ + +angular.module("sprintf",[]).filter("sprintf",function(){return function(){return sprintf.apply(null,arguments)}}).filter("fmt",["$filter",function(a){return a("sprintf")}]).filter("vsprintf",function(){return function(a,b){return vsprintf(a,b)}}).filter("vfmt",["$filter",function(a){return a("vsprintf")}]); +//# sourceMappingURL=angular-sprintf.min.map \ No newline at end of file diff --git a/scripts/node_modules/sprintf-js/dist/angular-sprintf.min.js.map b/scripts/node_modules/sprintf-js/dist/angular-sprintf.min.js.map new file mode 100644 index 000000000..055964c62 --- /dev/null +++ b/scripts/node_modules/sprintf-js/dist/angular-sprintf.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"angular-sprintf.min.js","sources":["../src/angular-sprintf.js"],"names":["angular","module","filter","sprintf","apply","arguments","$filter","format","argv","vsprintf"],"mappings":";;AAAAA,QACIC,OAAO,cACPC,OAAO,UAAW,WACd,MAAO,YACH,MAAOC,SAAQC,MAAM,KAAMC,cAGnCH,OAAO,OAAQ,UAAW,SAASI,GAC/B,MAAOA,GAAQ,cAEnBJ,OAAO,WAAY,WACf,MAAO,UAASK,EAAQC,GACpB,MAAOC,UAASF,EAAQC,MAGhCN,OAAO,QAAS,UAAW,SAASI,GAChC,MAAOA,GAAQ"} \ No newline at end of file diff --git a/scripts/node_modules/sprintf-js/dist/angular-sprintf.min.map b/scripts/node_modules/sprintf-js/dist/angular-sprintf.min.map new file mode 100644 index 000000000..055964c62 --- /dev/null +++ b/scripts/node_modules/sprintf-js/dist/angular-sprintf.min.map @@ -0,0 +1 @@ +{"version":3,"file":"angular-sprintf.min.js","sources":["../src/angular-sprintf.js"],"names":["angular","module","filter","sprintf","apply","arguments","$filter","format","argv","vsprintf"],"mappings":";;AAAAA,QACIC,OAAO,cACPC,OAAO,UAAW,WACd,MAAO,YACH,MAAOC,SAAQC,MAAM,KAAMC,cAGnCH,OAAO,OAAQ,UAAW,SAASI,GAC/B,MAAOA,GAAQ,cAEnBJ,OAAO,WAAY,WACf,MAAO,UAASK,EAAQC,GACpB,MAAOC,UAASF,EAAQC,MAGhCN,OAAO,QAAS,UAAW,SAASI,GAChC,MAAOA,GAAQ"} \ No newline at end of file diff --git a/scripts/node_modules/sprintf-js/dist/sprintf.min.js b/scripts/node_modules/sprintf-js/dist/sprintf.min.js new file mode 100644 index 000000000..dc61e51ad --- /dev/null +++ b/scripts/node_modules/sprintf-js/dist/sprintf.min.js @@ -0,0 +1,4 @@ +/*! sprintf-js | Alexandru Marasteanu (http://alexei.ro/) | BSD-3-Clause */ + +!function(a){function b(){var a=arguments[0],c=b.cache;return c[a]&&c.hasOwnProperty(a)||(c[a]=b.parse(a)),b.format.call(null,c[a],arguments)}function c(a){return Object.prototype.toString.call(a).slice(8,-1).toLowerCase()}function d(a,b){return Array(b+1).join(a)}var e={not_string:/[^s]/,number:/[diefg]/,json:/[j]/,not_json:/[^j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijosuxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[\+\-]/};b.format=function(a,f){var g,h,i,j,k,l,m,n=1,o=a.length,p="",q=[],r=!0,s="";for(h=0;o>h;h++)if(p=c(a[h]),"string"===p)q[q.length]=a[h];else if("array"===p){if(j=a[h],j[2])for(g=f[n],i=0;i=0),j[8]){case"b":g=g.toString(2);break;case"c":g=String.fromCharCode(g);break;case"d":case"i":g=parseInt(g,10);break;case"j":g=JSON.stringify(g,null,j[6]?parseInt(j[6]):0);break;case"e":g=j[7]?g.toExponential(j[7]):g.toExponential();break;case"f":g=j[7]?parseFloat(g).toFixed(j[7]):parseFloat(g);break;case"g":g=j[7]?parseFloat(g).toPrecision(j[7]):parseFloat(g);break;case"o":g=g.toString(8);break;case"s":g=(g=String(g))&&j[7]?g.substring(0,j[7]):g;break;case"u":g>>>=0;break;case"x":g=g.toString(16);break;case"X":g=g.toString(16).toUpperCase()}e.json.test(j[8])?q[q.length]=g:(!e.number.test(j[8])||r&&!j[3]?s="":(s=r?"+":"-",g=g.toString().replace(e.sign,"")),l=j[4]?"0"===j[4]?"0":j[4].charAt(1):" ",m=j[6]-(s+g).length,k=j[6]&&m>0?d(l,m):"",q[q.length]=j[5]?s+g+k:"0"===l?s+k+g:k+s+g)}return q.join("")},b.cache={},b.parse=function(a){for(var b=a,c=[],d=[],f=0;b;){if(null!==(c=e.text.exec(b)))d[d.length]=c[0];else if(null!==(c=e.modulo.exec(b)))d[d.length]="%";else{if(null===(c=e.placeholder.exec(b)))throw new SyntaxError("[sprintf] unexpected placeholder");if(c[2]){f|=1;var g=[],h=c[2],i=[];if(null===(i=e.key.exec(h)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(g[g.length]=i[1];""!==(h=h.substring(i[0].length));)if(null!==(i=e.key_access.exec(h)))g[g.length]=i[1];else{if(null===(i=e.index_access.exec(h)))throw new SyntaxError("[sprintf] failed to parse named argument key");g[g.length]=i[1]}c[2]=g}else f|=2;if(3===f)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");d[d.length]=c}b=b.substring(c[0].length)}return d};var f=function(a,c,d){return d=(c||[]).slice(0),d.splice(0,0,a),b.apply(null,d)};"undefined"!=typeof exports?(exports.sprintf=b,exports.vsprintf=f):(a.sprintf=b,a.vsprintf=f,"function"==typeof define&&define.amd&&define(function(){return{sprintf:b,vsprintf:f}}))}("undefined"==typeof window?this:window); +//# sourceMappingURL=sprintf.min.map \ No newline at end of file diff --git a/scripts/node_modules/sprintf-js/dist/sprintf.min.js.map b/scripts/node_modules/sprintf-js/dist/sprintf.min.js.map new file mode 100644 index 000000000..369dbafab --- /dev/null +++ b/scripts/node_modules/sprintf-js/dist/sprintf.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sprintf.min.js","sources":["../src/sprintf.js"],"names":["window","sprintf","key","arguments","cache","hasOwnProperty","parse","format","call","get_type","variable","Object","prototype","toString","slice","toLowerCase","str_repeat","input","multiplier","Array","join","re","not_string","number","json","not_json","text","modulo","placeholder","key_access","index_access","sign","parse_tree","argv","arg","i","k","match","pad","pad_character","pad_length","cursor","tree_length","length","node_type","output","is_positive","Error","test","isNaN","TypeError","String","fromCharCode","parseInt","JSON","stringify","toExponential","parseFloat","toFixed","substring","toUpperCase","replace","charAt","fmt","_fmt","arg_names","exec","SyntaxError","field_list","repl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EpBf,GAAWA,EAAWW,QAAUN,EAKpC2B,EAAOA,EAAKL,UAAUtB,EAAM,GAAGM,QAEnC,MAAOX,GAGX,IAAIuC,GAAW,SAASR,EAAK9B,EAAMuC,GAG/B,MAFAA,IAASvC,OAAYnB,MAAM,GAC3B0D,EAAMC,OAAO,EAAG,EAAGV,GACZ9D,EAAQyE,MAAM,KAAMF,GAiBR,oBAAZG,UACPA,QAAQ1E,QAAUA,EAClB0E,QAAQJ,SAAWA,IAGnBvE,EAAOC,QAAUA,EACjBD,EAAOuE,SAAWA,EAEI,kBAAXK,SAAyBA,OAAOC,KACvCD,OAAO,WACH,OACI3E,QAASA,EACTsE,SAAUA,OAKT,mBAAXvE,QAAyB8E,KAAO9E"} \ No newline at end of file diff --git a/scripts/node_modules/sprintf-js/dist/sprintf.min.map b/scripts/node_modules/sprintf-js/dist/sprintf.min.map new file mode 100644 index 000000000..ee011aaa5 --- /dev/null +++ b/scripts/node_modules/sprintf-js/dist/sprintf.min.map @@ -0,0 +1 @@ +{"version":3,"file":"sprintf.min.js","sources":["../src/sprintf.js"],"names":["window","sprintf","key","arguments","cache","hasOwnProperty","parse","format","call","get_type","variable","Object","prototype","toString","slice","toLowerCase","str_repeat","input","multiplier","Array","join","re","not_string","number","json","not_json","text","modulo","placeholder","key_access","index_access","sign","parse_tree","argv","arg","i","k","match","pad","pad_character","pad_length","cursor","tree_length","length","node_type","output","is_positive","Error","test","isNaN","TypeError","String","fromCharCode","parseInt","JSON","stringify","toExponential","parseFloat","toFixed","toPrecision","substring","toUpperCase","replace","charAt","fmt","_fmt","arg_names","exec","SyntaxError","field_list","replacement_field","field_match","vsprintf","_argv","splice","apply","exports","define","amd","this"],"mappings":";;CAAA,SAAUA,GAeN,QAASC,KACL,GAAIC,GAAMC,UAAU,GAAIC,EAAQH,EAAQG,KAIxC,OAHMA,GAAMF,IAAQE,EAAMC,eAAeH,KACrCE,EAAMF,GAAOD,EAAQK,MAAMJ,IAExBD,EAAQM,OAAOC,KAA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AFAA,IAASxC,OAAYnB,MAAM,GAC3B2D,EAAMC,OAAO,EAAG,EAAGV,GACZ/D,EAAQ0E,MAAM,KAAMF,GAiBR,oBAAZG,UACPA,QAAQ3E,QAAUA,EAClB2E,QAAQJ,SAAWA,IAGnBxE,EAAOC,QAAUA,EACjBD,EAAOwE,SAAWA,EAEI,kBAAXK,SAAyBA,OAAOC,KACvCD,OAAO,WACH,OACI5E,QAASA,EACTuE,SAAUA,OAKT,mBAAXxE,QAAyB+E,KAAO/E"} \ No newline at end of file diff --git a/scripts/node_modules/sprintf-js/gruntfile.js b/scripts/node_modules/sprintf-js/gruntfile.js new file mode 100644 index 000000000..246e1c3b9 --- /dev/null +++ b/scripts/node_modules/sprintf-js/gruntfile.js @@ -0,0 +1,36 @@ +module.exports = function(grunt) { + grunt.initConfig({ + pkg: grunt.file.readJSON("package.json"), + + uglify: { + options: { + banner: "/*! <%= pkg.name %> | <%= pkg.author %> | <%= pkg.license %> */\n", + sourceMap: true + }, + build: { + files: [ + { + src: "src/sprintf.js", + dest: "dist/sprintf.min.js" + }, + { + src: "src/angular-sprintf.js", + dest: "dist/angular-sprintf.min.js" + } + ] + } + }, + + watch: { + js: { + files: "src/*.js", + tasks: ["uglify"] + } + } + }) + + grunt.loadNpmTasks("grunt-contrib-uglify") + grunt.loadNpmTasks("grunt-contrib-watch") + + grunt.registerTask("default", ["uglify", "watch"]) +} diff --git a/scripts/node_modules/sprintf-js/package.json b/scripts/node_modules/sprintf-js/package.json new file mode 100644 index 000000000..75f7eca71 --- /dev/null +++ b/scripts/node_modules/sprintf-js/package.json @@ -0,0 +1,22 @@ +{ + "name": "sprintf-js", + "version": "1.0.3", + "description": "JavaScript sprintf implementation", + "author": "Alexandru Marasteanu (http://alexei.ro/)", + "main": "src/sprintf.js", + "scripts": { + "test": "mocha test/test.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/alexei/sprintf.js.git" + }, + "license": "BSD-3-Clause", + "readmeFilename": "README.md", + "devDependencies": { + "mocha": "*", + "grunt": "*", + "grunt-contrib-watch": "*", + "grunt-contrib-uglify": "*" + } +} diff --git a/scripts/node_modules/sprintf-js/src/angular-sprintf.js b/scripts/node_modules/sprintf-js/src/angular-sprintf.js new file mode 100644 index 000000000..9c69123be --- /dev/null +++ b/scripts/node_modules/sprintf-js/src/angular-sprintf.js @@ -0,0 +1,18 @@ +angular. + module("sprintf", []). + filter("sprintf", function() { + return function() { + return sprintf.apply(null, arguments) + } + }). + filter("fmt", ["$filter", function($filter) { + return $filter("sprintf") + }]). + filter("vsprintf", function() { + return function(format, argv) { + return vsprintf(format, argv) + } + }). + filter("vfmt", ["$filter", function($filter) { + return $filter("vsprintf") + }]) diff --git a/scripts/node_modules/sprintf-js/src/sprintf.js b/scripts/node_modules/sprintf-js/src/sprintf.js new file mode 100644 index 000000000..c0fc7c08b --- /dev/null +++ b/scripts/node_modules/sprintf-js/src/sprintf.js @@ -0,0 +1,208 @@ +(function(window) { + var re = { + not_string: /[^s]/, + number: /[diefg]/, + json: /[j]/, + not_json: /[^j]/, + text: /^[^\x25]+/, + modulo: /^\x25{2}/, + placeholder: /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijosuxX])/, + key: /^([a-z_][a-z_\d]*)/i, + key_access: /^\.([a-z_][a-z_\d]*)/i, + index_access: /^\[(\d+)\]/, + sign: /^[\+\-]/ + } + + function sprintf() { + var key = arguments[0], cache = sprintf.cache + if (!(cache[key] && cache.hasOwnProperty(key))) { + cache[key] = sprintf.parse(key) + } + return sprintf.format.call(null, cache[key], arguments) + } + + sprintf.format = function(parse_tree, argv) { + var cursor = 1, tree_length = parse_tree.length, node_type = "", arg, output = [], i, k, match, pad, pad_character, pad_length, is_positive = true, sign = "" + for (i = 0; i < tree_length; i++) { + node_type = get_type(parse_tree[i]) + if (node_type === "string") { + output[output.length] = parse_tree[i] + } + else if (node_type === "array") { + match = parse_tree[i] // convenience purposes only + if (match[2]) { // keyword argument + arg = argv[cursor] + for (k = 0; k < match[2].length; k++) { + if (!arg.hasOwnProperty(match[2][k])) { + throw new Error(sprintf("[sprintf] property '%s' does not exist", match[2][k])) + } + arg = arg[match[2][k]] + } + } + else if (match[1]) { // positional argument (explicit) + arg = argv[match[1]] + } + else { // positional argument (implicit) + arg = argv[cursor++] + } + + if (get_type(arg) == "function") { + arg = arg() + } + + if (re.not_string.test(match[8]) && re.not_json.test(match[8]) && (get_type(arg) != "number" && isNaN(arg))) { + throw new TypeError(sprintf("[sprintf] expecting number but found %s", get_type(arg))) + } + + if (re.number.test(match[8])) { + is_positive = arg >= 0 + } + + switch (match[8]) { + case "b": + arg = arg.toString(2) + break + case "c": + arg = String.fromCharCode(arg) + break + case "d": + case "i": + arg = parseInt(arg, 10) + break + case "j": + arg = JSON.stringify(arg, null, match[6] ? parseInt(match[6]) : 0) + break + case "e": + arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential() + break + case "f": + arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg) + break + case "g": + arg = match[7] ? parseFloat(arg).toPrecision(match[7]) : parseFloat(arg) + break + case "o": + arg = arg.toString(8) + break + case "s": + arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg) + break + case "u": + arg = arg >>> 0 + break + case "x": + arg = arg.toString(16) + break + case "X": + arg = arg.toString(16).toUpperCase() + break + } + if (re.json.test(match[8])) { + output[output.length] = arg + } + else { + if (re.number.test(match[8]) && (!is_positive || match[3])) { + sign = is_positive ? "+" : "-" + arg = arg.toString().replace(re.sign, "") + } + else { + sign = "" + } + pad_character = match[4] ? match[4] === "0" ? "0" : match[4].charAt(1) : " " + pad_length = match[6] - (sign + arg).length + pad = match[6] ? (pad_length > 0 ? str_repeat(pad_character, pad_length) : "") : "" + output[output.length] = match[5] ? sign + arg + pad : (pad_character === "0" ? sign + pad + arg : pad + sign + arg) + } + } + } + return output.join("") + } + + sprintf.cache = {} + + sprintf.parse = function(fmt) { + var _fmt = fmt, match = [], parse_tree = [], arg_names = 0 + while (_fmt) { + if ((match = re.text.exec(_fmt)) !== null) { + parse_tree[parse_tree.length] = match[0] + } + else if ((match = re.modulo.exec(_fmt)) !== null) { + parse_tree[parse_tree.length] = "%" + } + else if ((match = re.placeholder.exec(_fmt)) !== null) { + if (match[2]) { + arg_names |= 1 + var field_list = [], replacement_field = match[2], field_match = [] + if ((field_match = re.key.exec(replacement_field)) !== null) { + field_list[field_list.length] = field_match[1] + while ((replacement_field = replacement_field.substring(field_match[0].length)) !== "") { + if ((field_match = re.key_access.exec(replacement_field)) !== null) { + field_list[field_list.length] = field_match[1] + } + else if ((field_match = re.index_access.exec(replacement_field)) !== null) { + field_list[field_list.length] = field_match[1] + } + else { + throw new SyntaxError("[sprintf] failed to parse named argument key") + } + } + } + else { + throw new SyntaxError("[sprintf] failed to parse named argument key") + } + match[2] = field_list + } + else { + arg_names |= 2 + } + if (arg_names === 3) { + throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported") + } + parse_tree[parse_tree.length] = match + } + else { + throw new SyntaxError("[sprintf] unexpected placeholder") + } + _fmt = _fmt.substring(match[0].length) + } + return parse_tree + } + + var vsprintf = function(fmt, argv, _argv) { + _argv = (argv || []).slice(0) + _argv.splice(0, 0, fmt) + return sprintf.apply(null, _argv) + } + + /** + * helpers + */ + function get_type(variable) { + return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase() + } + + function str_repeat(input, multiplier) { + return Array(multiplier + 1).join(input) + } + + /** + * export to either browser or node.js + */ + if (typeof exports !== "undefined") { + exports.sprintf = sprintf + exports.vsprintf = vsprintf + } + else { + window.sprintf = sprintf + window.vsprintf = vsprintf + + if (typeof define === "function" && define.amd) { + define(function() { + return { + sprintf: sprintf, + vsprintf: vsprintf + } + }) + } + } +})(typeof window === "undefined" ? this : window); diff --git a/scripts/node_modules/sprintf-js/test/test.js b/scripts/node_modules/sprintf-js/test/test.js new file mode 100644 index 000000000..6f57b2538 --- /dev/null +++ b/scripts/node_modules/sprintf-js/test/test.js @@ -0,0 +1,82 @@ +var assert = require("assert"), + sprintfjs = require("../src/sprintf.js"), + sprintf = sprintfjs.sprintf, + vsprintf = sprintfjs.vsprintf + +describe("sprintfjs", function() { + var pi = 3.141592653589793 + + it("should return formated strings for simple placeholders", function() { + assert.equal("%", sprintf("%%")) + assert.equal("10", sprintf("%b", 2)) + assert.equal("A", sprintf("%c", 65)) + assert.equal("2", sprintf("%d", 2)) + assert.equal("2", sprintf("%i", 2)) + assert.equal("2", sprintf("%d", "2")) + assert.equal("2", sprintf("%i", "2")) + assert.equal('{"foo":"bar"}', sprintf("%j", {foo: "bar"})) + assert.equal('["foo","bar"]', sprintf("%j", ["foo", "bar"])) + assert.equal("2e+0", sprintf("%e", 2)) + assert.equal("2", sprintf("%u", 2)) + assert.equal("4294967294", sprintf("%u", -2)) + assert.equal("2.2", sprintf("%f", 2.2)) + assert.equal("3.141592653589793", sprintf("%g", pi)) + assert.equal("10", sprintf("%o", 8)) + assert.equal("%s", sprintf("%s", "%s")) + assert.equal("ff", sprintf("%x", 255)) + assert.equal("FF", sprintf("%X", 255)) + assert.equal("Polly wants a cracker", sprintf("%2$s %3$s a %1$s", "cracker", "Polly", "wants")) + assert.equal("Hello world!", sprintf("Hello %(who)s!", {"who": "world"})) + }) + + it("should return formated strings for complex placeholders", function() { + // sign + assert.equal("2", sprintf("%d", 2)) + assert.equal("-2", sprintf("%d", -2)) + assert.equal("+2", sprintf("%+d", 2)) + assert.equal("-2", sprintf("%+d", -2)) + assert.equal("2", sprintf("%i", 2)) + assert.equal("-2", sprintf("%i", -2)) + assert.equal("+2", sprintf("%+i", 2)) + assert.equal("-2", sprintf("%+i", -2)) + assert.equal("2.2", sprintf("%f", 2.2)) + assert.equal("-2.2", sprintf("%f", -2.2)) + assert.equal("+2.2", sprintf("%+f", 2.2)) + assert.equal("-2.2", sprintf("%+f", -2.2)) + assert.equal("-2.3", sprintf("%+.1f", -2.34)) + assert.equal("-0.0", sprintf("%+.1f", -0.01)) + assert.equal("3.14159", sprintf("%.6g", pi)) + assert.equal("3.14", sprintf("%.3g", pi)) + assert.equal("3", sprintf("%.1g", pi)) + assert.equal("-000000123", sprintf("%+010d", -123)) + assert.equal("______-123", sprintf("%+'_10d", -123)) + assert.equal("-234.34 123.2", sprintf("%f %f", -234.34, 123.2)) + + // padding + assert.equal("-0002", sprintf("%05d", -2)) + assert.equal("-0002", sprintf("%05i", -2)) + assert.equal(" <", sprintf("%5s", "<")) + assert.equal("0000<", sprintf("%05s", "<")) + assert.equal("____<", sprintf("%'_5s", "<")) + assert.equal("> ", sprintf("%-5s", ">")) + assert.equal(">0000", sprintf("%0-5s", ">")) + assert.equal(">____", sprintf("%'_-5s", ">")) + assert.equal("xxxxxx", sprintf("%5s", "xxxxxx")) + assert.equal("1234", sprintf("%02u", 1234)) + assert.equal(" -10.235", sprintf("%8.3f", -10.23456)) + assert.equal("-12.34 xxx", sprintf("%f %s", -12.34, "xxx")) + assert.equal('{\n "foo": "bar"\n}', sprintf("%2j", {foo: "bar"})) + assert.equal('[\n "foo",\n "bar"\n]', sprintf("%2j", ["foo", "bar"])) + + // precision + assert.equal("2.3", sprintf("%.1f", 2.345)) + assert.equal("xxxxx", sprintf("%5.5s", "xxxxxx")) + assert.equal(" x", sprintf("%5.1s", "xxxxxx")) + + }) + + it("should return formated strings for callbacks", function() { + assert.equal("foobar", sprintf("%s", function() { return "foobar" })) + assert.equal(Date.now(), sprintf("%s", Date.now)) // should pass... + }) +}) diff --git a/scripts/node_modules/strip-bom-string/LICENSE b/scripts/node_modules/strip-bom-string/LICENSE new file mode 100644 index 000000000..ec85897eb --- /dev/null +++ b/scripts/node_modules/strip-bom-string/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015, 2017, Jon Schlinkert + +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/scripts/node_modules/strip-bom-string/README.md b/scripts/node_modules/strip-bom-string/README.md new file mode 100644 index 000000000..e7e5990fe --- /dev/null +++ b/scripts/node_modules/strip-bom-string/README.md @@ -0,0 +1,66 @@ +# strip-bom-string [![NPM version](https://img.shields.io/npm/v/strip-bom-string.svg?style=flat)](https://www.npmjs.com/package/strip-bom-string) [![NPM monthly downloads](https://img.shields.io/npm/dm/strip-bom-string.svg?style=flat)](https://npmjs.org/package/strip-bom-string) [![NPM total downloads](https://img.shields.io/npm/dt/strip-bom-string.svg?style=flat)](https://npmjs.org/package/strip-bom-string) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/strip-bom-string.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/strip-bom-string) + +> Strip a byte order mark (BOM) from a string. + +## Install + +Install with [npm](https://www.npmjs.com/): + +```sh +$ npm install --save strip-bom-string +``` + +## Usage + +```js +var strip = require('strip-bom-string'); +strip('\ufefffoo'); +//=> 'foo' +``` + +## About + +### Related projects + +* [cr](https://www.npmjs.com/package/cr): Strip windows carriage returns, or convert carriage returns to newlines. | [homepage](https://github.com/jonschlinkert/cr "Strip windows carriage returns, or convert carriage returns to newlines.") +* [has-bom](https://www.npmjs.com/package/has-bom): Returns true if a buffer or string has a byte order mark (BOM) | [homepage](https://github.com/jonschlinkert/has-bom "Returns true if a buffer or string has a byte order mark (BOM)") +* [read-file](https://www.npmjs.com/package/read-file): Thin wrapper around fs.readFile and fs.readFileSync that also strips byte order marks when `utf8` encoding… [more](https://github.com/jonschlinkert/read-file) | [homepage](https://github.com/jonschlinkert/read-file "Thin wrapper around fs.readFile and fs.readFileSync that also strips byte order marks when `utf8` encoding is chosen. Also optionally replaces windows newlines with unix newlines.") +* [strip-bom-buffer](https://www.npmjs.com/package/strip-bom-buffer): Strip a byte order mark (BOM) from a buffer. | [homepage](https://github.com/jonschlinkert/strip-bom-buffer "Strip a byte order mark (BOM) from a buffer.") + +### Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +### Building docs + +_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ + +To generate the readme, run the following command: + +```sh +$ npm install -g verbose/verb#dev verb-generate-readme && verb +``` + +### Running tests + +Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: + +```sh +$ npm install && npm test +``` + +### Author + +**Jon Schlinkert** + +* [github/jonschlinkert](https://github.com/jonschlinkert) +* [twitter/jonschlinkert](https://twitter.com/jonschlinkert) + +### License + +Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT License](LICENSE). + +*** + +_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.4.3, on March 29, 2017._ \ No newline at end of file diff --git a/scripts/node_modules/strip-bom-string/index.js b/scripts/node_modules/strip-bom-string/index.js new file mode 100644 index 000000000..4caff84d2 --- /dev/null +++ b/scripts/node_modules/strip-bom-string/index.js @@ -0,0 +1,15 @@ +/*! + * strip-bom-string + * + * Copyright (c) 2015, 2017, Jon Schlinkert. + * Released under the MIT License. + */ + +'use strict'; + +module.exports = function(str) { + if (typeof str === 'string' && str.charAt(0) === '\ufeff') { + return str.slice(1); + } + return str; +}; diff --git a/scripts/node_modules/strip-bom-string/package.json b/scripts/node_modules/strip-bom-string/package.json new file mode 100644 index 000000000..b0c80fa24 --- /dev/null +++ b/scripts/node_modules/strip-bom-string/package.json @@ -0,0 +1,60 @@ +{ + "name": "strip-bom-string", + "description": "Strip a byte order mark (BOM) from a string.", + "version": "1.0.0", + "homepage": "https://github.com/jonschlinkert/strip-bom-string", + "author": "Jon Schlinkert (https://github.com/jonschlinkert)", + "repository": "jonschlinkert/strip-bom-string", + "bugs": { + "url": "https://github.com/jonschlinkert/strip-bom-string/issues" + }, + "license": "MIT", + "files": [ + "index.js" + ], + "main": "index.js", + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "mocha" + }, + "devDependencies": { + "gulp-format-md": "^0.1.11", + "mocha": "^3.2.0" + }, + "keywords": [ + "bom", + "byte", + "byte-order-mark", + "file", + "fs", + "mark", + "nl", + "normalize", + "order", + "string", + "strip" + ], + "verb": { + "related": { + "list": [ + "cr", + "has-bom", + "read-file", + "strip-bom-buffer" + ] + }, + "toc": false, + "layout": "default", + "tasks": [ + "readme" + ], + "plugins": [ + "gulp-format-md" + ], + "lint": { + "reflinks": true + } + } +} diff --git a/scripts/node_modules/striptags/.travis.yml b/scripts/node_modules/striptags/.travis.yml new file mode 100644 index 000000000..de77c447e --- /dev/null +++ b/scripts/node_modules/striptags/.travis.yml @@ -0,0 +1,7 @@ +language: node_js +node_js: + - "node" + - "4" + - "5" + - "6" +sudo: false diff --git a/scripts/node_modules/striptags/LICENSE b/scripts/node_modules/striptags/LICENSE new file mode 100644 index 000000000..9cfc1ceb9 --- /dev/null +++ b/scripts/node_modules/striptags/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) [2017] [Eric Norris] + +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/scripts/node_modules/striptags/README.md b/scripts/node_modules/striptags/README.md new file mode 100644 index 000000000..c85cf25bd --- /dev/null +++ b/scripts/node_modules/striptags/README.md @@ -0,0 +1,91 @@ +# striptags [![Build Status](https://travis-ci.org/ericnorris/striptags.svg)](https://travis-ci.org/ericnorris/striptags) +An implementation of PHP's [strip_tags](http://www.php.net/manual/en/function.strip-tags.php) in Node.js. + +**Note:** `v3+` targets ES6, and is therefore incompatible with the master branch of `uglifyjs`. You can either: +- use `babili`, which supports ES6 +- use the `harmony` branch of `uglifyjs` +- stick with the [2.x.x](https://github.com/ericnorris/striptags/tree/v2.x.x) branch + +## Features +- Fast +- Zero dependencies +- 100% test code coverage +- No unsafe regular expressions + +## Installing +``` +npm install striptags +``` + +## Basic Usage +```javascript +striptags(html, allowed_tags, tag_replacement); +``` + +### Example +```javascript +var striptags = require('striptags'); + +var html = + '
    ' + + 'lorem ipsum dolor sit amet' + + ''; + +striptags(html); +striptags(html, ''); +striptags(html, ['a']); +striptags(html, [], '\n'); +``` + +Outputs: +``` +'lorem ipsum dolor sit amet' +``` + +``` +lorem ipsum dolor sit amet' +``` + +``` +'lorem ipsum dolor sit amet' +``` + +``` +lorem ipsum +dolor + +sit + amet +``` + +## Streaming Mode +`striptags` can also operate in streaming mode. Simply call `init_streaming_mode` to get back a function that accepts HTML and outputs stripped HTML. State is saved between calls so that partial HTML can be safely passed in. + +```javascript +let stream_function = striptags.init_streaming_mode( + allowed_tags, + tag_replacement +); + +let partial_text = stream_function(partial_html); +let more_text = stream_function(more_html); +``` + +Check out [test/striptags-test.js](test/striptags-test.js) for a concrete example. + +## Tests +You can run tests (powered by [mocha](http://mochajs.org/)) locally via: +``` +npm test +``` + +Generate test coverage (powered by [istanbul](https://github.com/gotwarlost/istanbul)) via : +``` +npm run coverage +``` + + +## Doesn't use regular expressions +`striptags` does not use any regular expressions for stripping HTML tags. + +Regular expressions are not capable of preventing all possible scripting attacks (see [this](http://stackoverflow.com/a/535022)). Here is a [great StackOverflow answer](http://stackoverflow.com/a/5793453) regarding how strip_tags (**when used without specifying allowableTags**) is not vulnerable to scripting attacks. diff --git a/scripts/node_modules/striptags/bower.json b/scripts/node_modules/striptags/bower.json new file mode 100644 index 000000000..8a3fc3edb --- /dev/null +++ b/scripts/node_modules/striptags/bower.json @@ -0,0 +1,24 @@ +{ + "name": "striptags", + "description": "PHP strip_tags in Node.js", + "main": "striptags.js", + "authors": [ + "Eric Norris (https://github.com/ericnorris)" + ], + "license": "MIT", + "keywords": [ + "striptags", + "strip_tags", + "html", + "strip", + "tags" + ], + "homepage": "https://github.com/ericnorris/striptags", + "ignore": [ + "**/.*", + "node_modules", + "bower_components", + "test", + "tests" + ] +} diff --git a/scripts/node_modules/striptags/index.d.ts b/scripts/node_modules/striptags/index.d.ts new file mode 100644 index 000000000..d5dc3a69a --- /dev/null +++ b/scripts/node_modules/striptags/index.d.ts @@ -0,0 +1,25 @@ +export as namespace striptags + +export = striptags + +/** + * Creates an array of elements split into groups the length of size. If collection can’t be split evenly, the + * final chunk will be the remaining elements. + * + * @param html The text to process. + * @param allowedTags Tags which aren't removed + * @param tagReplacement Removed tags are replaced with this + * @return Returns the input string, sans any html tags that weren't allowed + */ +declare function striptags( + html: string, + allowedTags?: string | string[], + tagReplacement?: string +): string + +declare namespace striptags { + export const init_streaming_mode: ( + allowedTags?: string | string[], + tagReplacement?: string + ) => (html: string) => string +} diff --git a/scripts/node_modules/striptags/package.json b/scripts/node_modules/striptags/package.json new file mode 100644 index 000000000..5c0e2ef53 --- /dev/null +++ b/scripts/node_modules/striptags/package.json @@ -0,0 +1,30 @@ +{ + "name": "striptags", + "description": "PHP strip_tags in Node.js", + "license": "MIT", + "author": "Eric Norris (https://github.com/ericnorris)", + "repository": { + "type": "git", + "url": "https://github.com/ericnorris/striptags.git" + }, + "main": "src/striptags.js", + "homepage": "https://github.com/ericnorris/striptags", + "bugs": "https://github.com/ericnorris/striptags/issues", + "version": "3.2.0", + "devDependencies": { + "istanbul": "^0.4.5", + "mocha": "^3.2.0" + }, + "keywords": [ + "striptags", + "strip_tags", + "html", + "strip", + "tags" + ], + "typings": "index.d.ts", + "scripts": { + "test": "mocha", + "coverage": "istanbul cover _mocha -- -R spec" + } +} diff --git a/scripts/node_modules/striptags/src/striptags.js b/scripts/node_modules/striptags/src/striptags.js new file mode 100644 index 000000000..d9b58a22a --- /dev/null +++ b/scripts/node_modules/striptags/src/striptags.js @@ -0,0 +1,239 @@ +'use strict'; + +(function (global) { + + // minimal symbol polyfill for IE11 and others + if (typeof Symbol !== 'function') { + var Symbol = function(name) { + return name; + } + + Symbol.nonNative = true; + } + + const STATE_PLAINTEXT = Symbol('plaintext'); + const STATE_HTML = Symbol('html'); + const STATE_COMMENT = Symbol('comment'); + + const ALLOWED_TAGS_REGEX = /<(\w*)>/g; + const NORMALIZE_TAG_REGEX = /<\/?([^\s\/>]+)/; + + function striptags(html, allowable_tags, tag_replacement) { + html = html || ''; + allowable_tags = allowable_tags || []; + tag_replacement = tag_replacement || ''; + + let context = init_context(allowable_tags, tag_replacement); + + return striptags_internal(html, context); + } + + function init_striptags_stream(allowable_tags, tag_replacement) { + allowable_tags = allowable_tags || []; + tag_replacement = tag_replacement || ''; + + let context = init_context(allowable_tags, tag_replacement); + + return function striptags_stream(html) { + return striptags_internal(html || '', context); + }; + } + + striptags.init_streaming_mode = init_striptags_stream; + + function init_context(allowable_tags, tag_replacement) { + allowable_tags = parse_allowable_tags(allowable_tags); + + return { + allowable_tags : allowable_tags, + tag_replacement: tag_replacement, + + state : STATE_PLAINTEXT, + tag_buffer : '', + depth : 0, + in_quote_char : '' + }; + } + + function striptags_internal(html, context) { + if (typeof html != "string") { + throw new TypeError("'html' parameter must be a string"); + } + + let allowable_tags = context.allowable_tags; + let tag_replacement = context.tag_replacement; + + let state = context.state; + let tag_buffer = context.tag_buffer; + let depth = context.depth; + let in_quote_char = context.in_quote_char; + let output = ''; + + for (let idx = 0, length = html.length; idx < length; idx++) { + let char = html[idx]; + + if (state === STATE_PLAINTEXT) { + switch (char) { + case '<': + state = STATE_HTML; + tag_buffer += char; + break; + + default: + output += char; + break; + } + } + + else if (state === STATE_HTML) { + switch (char) { + case '<': + // ignore '<' if inside a quote + if (in_quote_char) { + break; + } + + // we're seeing a nested '<' + depth++; + break; + + case '>': + // ignore '>' if inside a quote + if (in_quote_char) { + break; + } + + // something like this is happening: '<<>>' + if (depth) { + depth--; + + break; + } + + // this is closing the tag in tag_buffer + in_quote_char = ''; + state = STATE_PLAINTEXT; + tag_buffer += '>'; + + if (allowable_tags.has(normalize_tag(tag_buffer))) { + output += tag_buffer; + } else { + output += tag_replacement; + } + + tag_buffer = ''; + break; + + case '"': + case '\'': + // catch both single and double quotes + + if (char === in_quote_char) { + in_quote_char = ''; + } else { + in_quote_char = in_quote_char || char; + } + + tag_buffer += char; + break; + + case '-': + if (tag_buffer === '': + if (tag_buffer.slice(-2) == '--') { + // close the comment + state = STATE_PLAINTEXT; + } + + tag_buffer = ''; + break; + + default: + tag_buffer += char; + break; + } + } + } + + // save the context for future iterations + context.state = state; + context.tag_buffer = tag_buffer; + context.depth = depth; + context.in_quote_char = in_quote_char; + + return output; + } + + function parse_allowable_tags(allowable_tags) { + let tag_set = new Set(); + + if (typeof allowable_tags === 'string') { + let match; + + while ((match = ALLOWED_TAGS_REGEX.exec(allowable_tags))) { + tag_set.add(match[1]); + } + } + + else if (!Symbol.nonNative && + typeof allowable_tags[Symbol.iterator] === 'function') { + + tag_set = new Set(allowable_tags); + } + + else if (typeof allowable_tags.forEach === 'function') { + // IE11 compatible + allowable_tags.forEach(tag_set.add, tag_set); + } + + return tag_set; + } + + function normalize_tag(tag_buffer) { + let match = NORMALIZE_TAG_REGEX.exec(tag_buffer); + + return match ? match[1].toLowerCase() : null; + } + + if (typeof define === 'function' && define.amd) { + // AMD + define(function module_factory() { return striptags; }); + } + + else if (typeof module === 'object' && module.exports) { + // Node + module.exports = striptags; + } + + else { + // Browser + global.striptags = striptags; + } +}(this)); diff --git a/scripts/node_modules/striptags/test/striptags-test.js b/scripts/node_modules/striptags/test/striptags-test.js new file mode 100644 index 000000000..36ae474fb --- /dev/null +++ b/scripts/node_modules/striptags/test/striptags-test.js @@ -0,0 +1,169 @@ +'use strict'; +/* global describe, it */ + +let assert = require('assert'); +let fs = require('fs'); +let vm = require('vm'); +let striptags = require('../'); + + +describe('striptags', function() { + describe('#module', function() { + let path = require.resolve('../'); + let src = fs.readFileSync(path); + let script = new vm.Script(src); + + it('should define a Node module', function() { + let module = { exports: {} }; + + script.runInNewContext({module}); + + assert.equal(module.exports.toString(), striptags.toString()); + }); + + it('should define an AMD module', function() { + let module = null; + let define = function(module_factory) { + module = module_factory(); + }; + + define.amd = true; + + script.runInNewContext({define}); + + assert.equal(module.toString(), striptags.toString()); + }); + + it('should define a browser global', function() { + let global = {}; + + script.runInNewContext(global); + + assert.notEqual(global.striptags, null); + }); + }); + + describe('with no optional parameters', function() { + it('should not strip invalid tags', function() { + let text = 'lorem ipsum < a> < div>'; + + assert.equal(striptags(text), text); + }); + + it('should remove simple HTML tags', function() { + let html = 'lorem ipsum', + text = 'lorem ipsum'; + + assert.equal(striptags(html), text); + }); + + it('should remove comments', function() { + let html = ' dolor sit amet', + text = ' dolor sit amet'; + + assert.equal(striptags(html), text); + }); + + it('should strip tags within comments', function() { + let html = ' dolor sit', + text = ' dolor sit'; + + assert.equal(striptags(html), text); + }); + + + it('should not fail with nested quotes', function() { + let html = '
    lorem
    ipsum', + text = 'lorem ipsum'; + + assert.equal(striptags(html), text); + }); + }); + + describe('#allowed_tags', function() { + it('should parse a string', function() { + let html = 'lorem ipsum', + allowed_tags = ''; + + assert.equal(striptags(html, allowed_tags), html); + }); + + it('should take an array', function() { + let html = 'lorem ipsum', + allowed_tags = ['strong', 'em']; + + assert.equal(striptags(html, allowed_tags), html); + }); + }); + + describe('with allowable_tags parameter', function() { + it('should leave attributes when allowing HTML', function() { + let html = 'lorem ipsum', + allowed_tags = ''; + + assert.equal(striptags(html, allowed_tags), html); + }); + + it('should strip extra < within tags', function() { + let html = '>lorem ipsum', + text = '
    lorem ipsum
    ', + allowed_tags = '
    '; + + assert.equal(striptags(html, allowed_tags), text); + }); + + it('should strip <> within quotes', function() { + let html = 'lorem ipsum', + text = 'lorem ipsum', + allowed_tags = ''; + + assert.equal(striptags(html, allowed_tags), text); + }); + }); + + describe('with tag_replacement parameter', function() { + it('should replace tags with that parameter', function() { + var html = 'Line One
    Line Two', + allowed_tags = [], + tag_replacement = '\n', + text = 'Line One\nLine Two'; + + assert.equal(striptags(html, allowed_tags, tag_replacement), text); + }); + }); + + describe('#streaming_mode', function() { + it('should strip streamed HTML', function() { + let striptags_stream = striptags.init_streaming_mode(); + + let part_one = striptags_stream('lorem ipsum dolor sit <'); + let part_three = striptags_stream(' amet'); + + assert.equal(part_one, 'lorem ipsum '); + assert.equal(part_two, 'dolor sit '); + assert.equal(part_three, '< amet'); + }); + + it('should work with allowable_tags', function() { + let striptags_stream = striptags.init_streaming_mode(['strong']); + + let part_one = striptags_stream('lorem ipsum dolor sit <'); + let part_three = striptags_stream(' amet'); + + assert.equal(part_one, 'lorem ipsum '); + assert.equal(part_two, 'dolor sit '); + assert.equal(part_three, '< amet'); + }); + }); + + it('GHSL-2021-074', function() { + assert.throws( + function() { + striptags(["type-confusion"]); + }, + TypeError, + ); + }); +}); diff --git a/scripts/package-lock.json b/scripts/package-lock.json new file mode 100644 index 000000000..5d6b93c1d --- /dev/null +++ b/scripts/package-lock.json @@ -0,0 +1,316 @@ +{ + "name": "scripts", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "scripts", + "version": "1.0.0", + "license": "ISC", + "devDependencies": { + "algoliasearch": "^4.24.0", + "gray-matter": "^4.0.3", + "marked": "^13.0.1", + "striptags": "^3.2.0" + } + }, + "node_modules/@algolia/cache-browser-local-storage": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/cache-browser-local-storage/-/cache-browser-local-storage-4.24.0.tgz", + "integrity": "sha512-t63W9BnoXVrGy9iYHBgObNXqYXM3tYXCjDSHeNwnsc324r4o5UiVKUiAB4THQ5z9U5hTj6qUvwg/Ez43ZD85ww==", + "dev": true, + "dependencies": { + "@algolia/cache-common": "4.24.0" + } + }, + "node_modules/@algolia/cache-common": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/cache-common/-/cache-common-4.24.0.tgz", + "integrity": "sha512-emi+v+DmVLpMGhp0V9q9h5CdkURsNmFC+cOS6uK9ndeJm9J4TiqSvPYVu+THUP8P/S08rxf5x2P+p3CfID0Y4g==", + "dev": true + }, + "node_modules/@algolia/cache-in-memory": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/cache-in-memory/-/cache-in-memory-4.24.0.tgz", + "integrity": "sha512-gDrt2so19jW26jY3/MkFg5mEypFIPbPoXsQGQWAi6TrCPsNOSEYepBMPlucqWigsmEy/prp5ug2jy/N3PVG/8w==", + "dev": true, + "dependencies": { + "@algolia/cache-common": "4.24.0" + } + }, + "node_modules/@algolia/client-account": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/client-account/-/client-account-4.24.0.tgz", + "integrity": "sha512-adcvyJ3KjPZFDybxlqnf+5KgxJtBjwTPTeyG2aOyoJvx0Y8dUQAEOEVOJ/GBxX0WWNbmaSrhDURMhc+QeevDsA==", + "dev": true, + "dependencies": { + "@algolia/client-common": "4.24.0", + "@algolia/client-search": "4.24.0", + "@algolia/transporter": "4.24.0" + } + }, + "node_modules/@algolia/client-analytics": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/client-analytics/-/client-analytics-4.24.0.tgz", + "integrity": "sha512-y8jOZt1OjwWU4N2qr8G4AxXAzaa8DBvyHTWlHzX/7Me1LX8OayfgHexqrsL4vSBcoMmVw2XnVW9MhL+Y2ZDJXg==", + "dev": true, + "dependencies": { + "@algolia/client-common": "4.24.0", + "@algolia/client-search": "4.24.0", + "@algolia/requester-common": "4.24.0", + "@algolia/transporter": "4.24.0" + } + }, + "node_modules/@algolia/client-common": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/client-common/-/client-common-4.24.0.tgz", + "integrity": "sha512-bc2ROsNL6w6rqpl5jj/UywlIYC21TwSSoFHKl01lYirGMW+9Eek6r02Tocg4gZ8HAw3iBvu6XQiM3BEbmEMoiA==", + "dev": true, + "dependencies": { + "@algolia/requester-common": "4.24.0", + "@algolia/transporter": "4.24.0" + } + }, + "node_modules/@algolia/client-personalization": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/client-personalization/-/client-personalization-4.24.0.tgz", + "integrity": "sha512-l5FRFm/yngztweU0HdUzz1rC4yoWCFo3IF+dVIVTfEPg906eZg5BOd1k0K6rZx5JzyyoP4LdmOikfkfGsKVE9w==", + "dev": true, + "dependencies": { + "@algolia/client-common": "4.24.0", + "@algolia/requester-common": "4.24.0", + "@algolia/transporter": "4.24.0" + } + }, + "node_modules/@algolia/client-search": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/client-search/-/client-search-4.24.0.tgz", + "integrity": "sha512-uRW6EpNapmLAD0mW47OXqTP8eiIx5F6qN9/x/7HHO6owL3N1IXqydGwW5nhDFBrV+ldouro2W1VX3XlcUXEFCA==", + "dev": true, + "dependencies": { + "@algolia/client-common": "4.24.0", + "@algolia/requester-common": "4.24.0", + "@algolia/transporter": "4.24.0" + } + }, + "node_modules/@algolia/logger-common": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/logger-common/-/logger-common-4.24.0.tgz", + "integrity": "sha512-LLUNjkahj9KtKYrQhFKCzMx0BY3RnNP4FEtO+sBybCjJ73E8jNdaKJ/Dd8A/VA4imVHP5tADZ8pn5B8Ga/wTMA==", + "dev": true + }, + "node_modules/@algolia/logger-console": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/logger-console/-/logger-console-4.24.0.tgz", + "integrity": "sha512-X4C8IoHgHfiUROfoRCV+lzSy+LHMgkoEEU1BbKcsfnV0i0S20zyy0NLww9dwVHUWNfPPxdMU+/wKmLGYf96yTg==", + "dev": true, + "dependencies": { + "@algolia/logger-common": "4.24.0" + } + }, + "node_modules/@algolia/recommend": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/recommend/-/recommend-4.24.0.tgz", + "integrity": "sha512-P9kcgerfVBpfYHDfVZDvvdJv0lEoCvzNlOy2nykyt5bK8TyieYyiD0lguIJdRZZYGre03WIAFf14pgE+V+IBlw==", + "dev": true, + "dependencies": { + "@algolia/cache-browser-local-storage": "4.24.0", + "@algolia/cache-common": "4.24.0", + "@algolia/cache-in-memory": "4.24.0", + "@algolia/client-common": "4.24.0", + "@algolia/client-search": "4.24.0", + "@algolia/logger-common": "4.24.0", + "@algolia/logger-console": "4.24.0", + "@algolia/requester-browser-xhr": "4.24.0", + "@algolia/requester-common": "4.24.0", + "@algolia/requester-node-http": "4.24.0", + "@algolia/transporter": "4.24.0" + } + }, + "node_modules/@algolia/requester-browser-xhr": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/requester-browser-xhr/-/requester-browser-xhr-4.24.0.tgz", + "integrity": "sha512-Z2NxZMb6+nVXSjF13YpjYTdvV3032YTBSGm2vnYvYPA6mMxzM3v5rsCiSspndn9rzIW4Qp1lPHBvuoKJV6jnAA==", + "dev": true, + "dependencies": { + "@algolia/requester-common": "4.24.0" + } + }, + "node_modules/@algolia/requester-common": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/requester-common/-/requester-common-4.24.0.tgz", + "integrity": "sha512-k3CXJ2OVnvgE3HMwcojpvY6d9kgKMPRxs/kVohrwF5WMr2fnqojnycZkxPoEg+bXm8fi5BBfFmOqgYztRtHsQA==", + "dev": true + }, + "node_modules/@algolia/requester-node-http": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/requester-node-http/-/requester-node-http-4.24.0.tgz", + "integrity": "sha512-JF18yTjNOVYvU/L3UosRcvbPMGT9B+/GQWNWnenIImglzNVGpyzChkXLnrSf6uxwVNO6ESGu6oN8MqcGQcjQJw==", + "dev": true, + "dependencies": { + "@algolia/requester-common": "4.24.0" + } + }, + "node_modules/@algolia/transporter": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/transporter/-/transporter-4.24.0.tgz", + "integrity": "sha512-86nI7w6NzWxd1Zp9q3413dRshDqAzSbsQjhcDhPIatEFiZrL1/TjnHL8S7jVKFePlIMzDsZWXAXwXzcok9c5oA==", + "dev": true, + "dependencies": { + "@algolia/cache-common": "4.24.0", + "@algolia/logger-common": "4.24.0", + "@algolia/requester-common": "4.24.0" + } + }, + "node_modules/algoliasearch": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/algoliasearch/-/algoliasearch-4.24.0.tgz", + "integrity": "sha512-bf0QV/9jVejssFBmz2HQLxUadxk574t4iwjCKp5E7NBzwKkrDEhKPISIIjAU/p6K5qDx3qoeh4+26zWN1jmw3g==", + "dev": true, + "dependencies": { + "@algolia/cache-browser-local-storage": "4.24.0", + "@algolia/cache-common": "4.24.0", + "@algolia/cache-in-memory": "4.24.0", + "@algolia/client-account": "4.24.0", + "@algolia/client-analytics": "4.24.0", + "@algolia/client-common": "4.24.0", + "@algolia/client-personalization": "4.24.0", + "@algolia/client-search": "4.24.0", + "@algolia/logger-common": "4.24.0", + "@algolia/logger-console": "4.24.0", + "@algolia/recommend": "4.24.0", + "@algolia/requester-browser-xhr": "4.24.0", + "@algolia/requester-common": "4.24.0", + "@algolia/requester-node-http": "4.24.0", + "@algolia/transporter": "4.24.0" + } + }, + "node_modules/argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "dev": true, + "dependencies": { + "sprintf-js": "~1.0.2" + } + }, + "node_modules/esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "dev": true, + "bin": { + "esparse": "bin/esparse.js", + "esvalidate": "bin/esvalidate.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha512-zCnTtlxNoAiDc3gqY2aYAWFx7XWWiasuF2K8Me5WbN8otHKTUKBwjPtNpRs/rbUZm7KxWAaNj7P1a/p52GbVug==", + "dev": true, + "dependencies": { + "is-extendable": "^0.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/gray-matter": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/gray-matter/-/gray-matter-4.0.3.tgz", + "integrity": "sha512-5v6yZd4JK3eMI3FqqCouswVqwugaA9r4dNZB1wwcmrD02QkV5H0y7XBQW8QwQqEaZY1pM9aqORSORhJRdNK44Q==", + "dev": true, + "dependencies": { + "js-yaml": "^3.13.1", + "kind-of": "^6.0.2", + "section-matter": "^1.0.0", + "strip-bom-string": "^1.0.0" + }, + "engines": { + "node": ">=6.0" + } + }, + "node_modules/is-extendable": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-0.1.1.tgz", + "integrity": "sha512-5BMULNob1vgFX6EjQw5izWDxrecWK9AM72rugNr0TFldMOi0fj6Jk+zeKIt0xGj4cEfQIJth4w3OKWOJ4f+AFw==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/js-yaml": { + "version": "3.14.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", + "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", + "dev": true, + "dependencies": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/kind-of": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz", + "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/marked": { + "version": "13.0.1", + "resolved": "https://registry.npmjs.org/marked/-/marked-13.0.1.tgz", + "integrity": "sha512-7kBohS6GrZKvCsNXZyVVXSW7/hGBHe49ng99YPkDCckSUrrG7MSFLCexsRxptzOmyW2eT5dySh4Md1V6my52fA==", + "dev": true, + "bin": { + "marked": "bin/marked.js" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/section-matter": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/section-matter/-/section-matter-1.0.0.tgz", + "integrity": "sha512-vfD3pmTzGpufjScBh50YHKzEu2lxBWhVEHsNGoEXmCmn2hKGfeNLYMzCJpe8cD7gqX7TJluOVpBkAequ6dgMmA==", + "dev": true, + "dependencies": { + "extend-shallow": "^2.0.1", + "kind-of": "^6.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/sprintf-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==", + "dev": true + }, + "node_modules/strip-bom-string": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/strip-bom-string/-/strip-bom-string-1.0.0.tgz", + "integrity": "sha512-uCC2VHvQRYu+lMh4My/sFNmF2klFymLX1wHJeXnbEJERpV/ZsVuonzerjfrGpIGF7LBVa1O7i9kjiWvJiFck8g==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/striptags": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/striptags/-/striptags-3.2.0.tgz", + "integrity": "sha512-g45ZOGzHDMe2bdYMdIvdAfCQkCTDMGBazSw1ypMowwGIee7ZQ5dU0rBJ8Jqgl+jAKIv4dbeE1jscZq9wid1Tkw==", + "dev": true + } + } +} diff --git a/scripts/package.json b/scripts/package.json new file mode 100644 index 000000000..7bc7ea729 --- /dev/null +++ b/scripts/package.json @@ -0,0 +1,20 @@ +{ + "name": "scripts", + "version": "1.0.0", + "main": "sync-docs.js", + "directories": { + "test": "test" + }, + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "", + "license": "ISC", + "description": "", + "devDependencies": { + "algoliasearch": "^4.24.0", + "gray-matter": "^4.0.3", + "marked": "^13.0.1", + "striptags": "^3.2.0" + } +}