commit c38d60e34ca7c8a3500c5bec6e6d7dc33f06cf57 Author: Alex Zaw Date: Fri Apr 10 11:09:26 2026 -0700 upload current sources diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..291cb46 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,19 @@ +FROM node:22-slim + +# Install Chrome dependencies +RUN apt-get update && apt-get install -y --no-install-recommends \ + chromium \ + fonts-freefont-ttf \ + fonts-noto-cjk \ + && rm -rf /var/lib/apt/lists/* + +WORKDIR /app + +COPY package.json package-lock.json ./ +RUN npm ci --omit=dev + +COPY md2html.js mermaid.min.js ./ + +ENV CHROME_PATH=/usr/bin/chromium + +ENTRYPOINT ["node", "md2html.js"] diff --git a/md2html.js b/md2html.js new file mode 100644 index 0000000..e0bc229 --- /dev/null +++ b/md2html.js @@ -0,0 +1,389 @@ +#!/usr/bin/env node +/** + * md2html — Convert Markdown files to styled HTML (and optionally PDF) + * with sidebar TOC + Mermaid diagrams. + * + * Usage: + * node md2html.js [output.html] + * node md2html.js --pdf [output.pdf] + * + * If output is omitted, writes to .html (or .pdf) alongside the source file. + */ + +const fs = require("fs"); +const path = require("path"); +const { marked } = require("marked"); + +// ── CLI args ────────────────────────────────────────────────────────────────── +const args = process.argv.slice(2); +if (args.length === 0 || args.includes("--help") || args.includes("-h")) { + console.log("Usage: node md2html.js [output.html]"); + console.log(" node md2html.js --pdf [output.pdf]"); + process.exit(0); +} + +const pdfMode = args.includes("--pdf"); +const filteredArgs = args.filter((a) => a !== "--pdf"); + +const inputPath = path.resolve(filteredArgs[0]); +const defaultExt = pdfMode ? ".pdf" : ".html"; +const outputPath = filteredArgs[1] + ? path.resolve(filteredArgs[1]) + : inputPath.replace(/\.md$/i, defaultExt); + +if (!fs.existsSync(inputPath)) { + console.error(`Error: file not found — ${inputPath}`); + process.exit(1); +} + +const md = fs.readFileSync(inputPath, "utf-8"); + +// ── Marked setup ────────────────────────────────────────────────────────────── +// Custom renderer: leave mermaid code blocks as
 for client‑side rendering
+const renderer = new marked.Renderer();
+const defaultCode = renderer.code.bind(renderer);
+
+renderer.code = function ({ text, lang }) {
+  if (lang === "mermaid") {
+    return `
${escapeHtml(text)}
\n`; + } + return defaultCode({ text, lang }); +}; + +// Collect headings for TOC while rendering +const tocItems = []; +renderer.heading = function ({ text, depth }) { + const slug = text + .toLowerCase() + .replace(/<[^>]*>/g, "") + .replace(/[^\w\s-]/g, "") + .replace(/\s+/g, "-") + .replace(/-+/g, "-") + .trim(); + tocItems.push({ text: stripHtml(text), depth, slug }); + return `${text}\n`; +}; + +function escapeHtml(s) { + return s + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """); +} + +function stripHtml(s) { + return s.replace(/<[^>]*>/g, ""); +} + +marked.setOptions({ renderer, gfm: true, breaks: false }); + +const bodyHtml = marked.parse(md); + +// ── Build TOC HTML ──────────────────────────────────────────────────────────── +function buildToc(items) { + if (items.length === 0) return ""; + let html = ""; + let prevDepth = 0; + for (const item of items) { + if (item.depth > prevDepth) { + for (let i = prevDepth; i < item.depth; i++) html += "
    "; + } else if (item.depth < prevDepth) { + for (let i = item.depth; i < prevDepth; i++) html += "
"; + } + html += `
  • ${escapeHtml(item.text)}
  • \n`; + prevDepth = item.depth; + } + for (let i = 0; i < prevDepth; i++) html += ""; + return html; +} + +const tocHtml = buildToc(tocItems); +const docTitle = tocItems.length > 0 ? tocItems[0].text : "Document"; + +// ── Full HTML template ──────────────────────────────────────────────────────── +const html = ` + + + + +${escapeHtml(docTitle)} + + + + + + + + + + + +
    +${bodyHtml} +
    + + + + + + + + +`; + +if (pdfMode) { + (async () => { + const puppeteer = require("puppeteer-core"); + + const browser = await puppeteer.launch({ + executablePath: + process.env.CHROME_PATH || "/usr/bin/google-chrome-stable", + args: ["--no-sandbox", "--disable-setuid-sandbox"], + }); + const page = await browser.newPage(); + + // Capture console for debugging + page.on("console", (msg) => { + if (msg.type() === "error") console.error(" [browser]", msg.text()); + }); + + // Load the HTML content directly (no CDN scripts — we inject mermaid below) + // Strip the CDN mermaid script so we can inject it ourselves via puppeteer + const htmlForPdf = html.replace( + / + +escodegen.browser.js can be found in tagged revisions on GitHub. + +Or in a Node.js application via npm: + + npm install escodegen + +### Usage + +A simple example: the program + + escodegen.generate({ + type: 'BinaryExpression', + operator: '+', + left: { type: 'Literal', value: 40 }, + right: { type: 'Literal', value: 2 } + }); + +produces the string `'40 + 2'`. + +See the [API page](https://github.com/estools/escodegen/wiki/API) for +options. To run the tests, execute `npm test` in the root directory. + +### Building browser bundle / minified browser bundle + +At first, execute `npm install` to install the all dev dependencies. +After that, + + npm run-script build + +will generate `escodegen.browser.js`, which can be used in browser environments. + +And, + + npm run-script build-min + +will generate the minified file `escodegen.browser.min.js`. + +### License + +#### Escodegen + +Copyright (C) 2012 [Yusuke Suzuki](http://github.com/Constellation) + (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors. + +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/node_modules/escodegen/bin/escodegen.js b/node_modules/escodegen/bin/escodegen.js new file mode 100755 index 0000000..a7c38aa --- /dev/null +++ b/node_modules/escodegen/bin/escodegen.js @@ -0,0 +1,77 @@ +#!/usr/bin/env node +/* + Copyright (C) 2012 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/*jslint sloppy:true node:true */ + +var fs = require('fs'), + path = require('path'), + root = path.join(path.dirname(fs.realpathSync(__filename)), '..'), + esprima = require('esprima'), + escodegen = require(root), + optionator = require('optionator')({ + prepend: 'Usage: escodegen [options] file...', + options: [ + { + option: 'config', + alias: 'c', + type: 'String', + description: 'configuration json for escodegen' + } + ] + }), + args = optionator.parse(process.argv), + files = args._, + options, + esprimaOptions = { + raw: true, + tokens: true, + range: true, + comment: true + }; + +if (files.length === 0) { + console.log(optionator.generateHelp()); + process.exit(1); +} + +if (args.config) { + try { + options = JSON.parse(fs.readFileSync(args.config, 'utf-8')); + } catch (err) { + console.error('Error parsing config: ', err); + } +} + +files.forEach(function (filename) { + var content = fs.readFileSync(filename, 'utf-8'), + syntax = esprima.parse(content, esprimaOptions); + + if (options.comment) { + escodegen.attachComments(syntax, syntax.comments, syntax.tokens); + } + + console.log(escodegen.generate(syntax, options)); +}); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/escodegen/bin/esgenerate.js b/node_modules/escodegen/bin/esgenerate.js new file mode 100755 index 0000000..449abcc --- /dev/null +++ b/node_modules/escodegen/bin/esgenerate.js @@ -0,0 +1,64 @@ +#!/usr/bin/env node +/* + Copyright (C) 2012 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/*jslint sloppy:true node:true */ + +var fs = require('fs'), + path = require('path'), + root = path.join(path.dirname(fs.realpathSync(__filename)), '..'), + escodegen = require(root), + optionator = require('optionator')({ + prepend: 'Usage: esgenerate [options] file.json ...', + options: [ + { + option: 'config', + alias: 'c', + type: 'String', + description: 'configuration json for escodegen' + } + ] + }), + args = optionator.parse(process.argv), + files = args._, + options; + +if (files.length === 0) { + console.log(optionator.generateHelp()); + process.exit(1); +} + +if (args.config) { + try { + options = JSON.parse(fs.readFileSync(args.config, 'utf-8')) + } catch (err) { + console.error('Error parsing config: ', err); + } +} + +files.forEach(function (filename) { + var content = fs.readFileSync(filename, 'utf-8'); + console.log(escodegen.generate(JSON.parse(content), options)); +}); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/escodegen/escodegen.js b/node_modules/escodegen/escodegen.js new file mode 100644 index 0000000..82417cd --- /dev/null +++ b/node_modules/escodegen/escodegen.js @@ -0,0 +1,2667 @@ +/* + Copyright (C) 2012-2014 Yusuke Suzuki + Copyright (C) 2015 Ingvar Stepanyan + Copyright (C) 2014 Ivan Nikulin + Copyright (C) 2012-2013 Michael Ficarra + Copyright (C) 2012-2013 Mathias Bynens + Copyright (C) 2013 Irakli Gozalishvili + Copyright (C) 2012 Robert Gust-Bardon + Copyright (C) 2012 John Freeman + Copyright (C) 2011-2012 Ariya Hidayat + Copyright (C) 2012 Joost-Wim Boekesteijn + Copyright (C) 2012 Kris Kowal + Copyright (C) 2012 Arpad Borsos + Copyright (C) 2020 Apple Inc. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 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. +*/ + +/*global exports:true, require:true, global:true*/ +(function () { + 'use strict'; + + var Syntax, + Precedence, + BinaryPrecedence, + SourceNode, + estraverse, + esutils, + base, + indent, + json, + renumber, + hexadecimal, + quotes, + escapeless, + newline, + space, + parentheses, + semicolons, + safeConcatenation, + directive, + extra, + parse, + sourceMap, + sourceCode, + preserveBlankLines, + FORMAT_MINIFY, + FORMAT_DEFAULTS; + + estraverse = require('estraverse'); + esutils = require('esutils'); + + Syntax = estraverse.Syntax; + + // Generation is done by generateExpression. + function isExpression(node) { + return CodeGenerator.Expression.hasOwnProperty(node.type); + } + + // Generation is done by generateStatement. + function isStatement(node) { + return CodeGenerator.Statement.hasOwnProperty(node.type); + } + + Precedence = { + Sequence: 0, + Yield: 1, + Assignment: 1, + Conditional: 2, + ArrowFunction: 2, + Coalesce: 3, + LogicalOR: 4, + LogicalAND: 5, + BitwiseOR: 6, + BitwiseXOR: 7, + BitwiseAND: 8, + Equality: 9, + Relational: 10, + BitwiseSHIFT: 11, + Additive: 12, + Multiplicative: 13, + Exponentiation: 14, + Await: 15, + Unary: 15, + Postfix: 16, + OptionalChaining: 17, + Call: 18, + New: 19, + TaggedTemplate: 20, + Member: 21, + Primary: 22 + }; + + BinaryPrecedence = { + '??': Precedence.Coalesce, + '||': Precedence.LogicalOR, + '&&': Precedence.LogicalAND, + '|': Precedence.BitwiseOR, + '^': Precedence.BitwiseXOR, + '&': Precedence.BitwiseAND, + '==': Precedence.Equality, + '!=': Precedence.Equality, + '===': Precedence.Equality, + '!==': Precedence.Equality, + 'is': Precedence.Equality, + 'isnt': Precedence.Equality, + '<': Precedence.Relational, + '>': Precedence.Relational, + '<=': Precedence.Relational, + '>=': Precedence.Relational, + 'in': Precedence.Relational, + 'instanceof': Precedence.Relational, + '<<': Precedence.BitwiseSHIFT, + '>>': Precedence.BitwiseSHIFT, + '>>>': Precedence.BitwiseSHIFT, + '+': Precedence.Additive, + '-': Precedence.Additive, + '*': Precedence.Multiplicative, + '%': Precedence.Multiplicative, + '/': Precedence.Multiplicative, + '**': Precedence.Exponentiation + }; + + //Flags + var F_ALLOW_IN = 1, + F_ALLOW_CALL = 1 << 1, + F_ALLOW_UNPARATH_NEW = 1 << 2, + F_FUNC_BODY = 1 << 3, + F_DIRECTIVE_CTX = 1 << 4, + F_SEMICOLON_OPT = 1 << 5, + F_FOUND_COALESCE = 1 << 6; + + //Expression flag sets + //NOTE: Flag order: + // F_ALLOW_IN + // F_ALLOW_CALL + // F_ALLOW_UNPARATH_NEW + var E_FTT = F_ALLOW_CALL | F_ALLOW_UNPARATH_NEW, + E_TTF = F_ALLOW_IN | F_ALLOW_CALL, + E_TTT = F_ALLOW_IN | F_ALLOW_CALL | F_ALLOW_UNPARATH_NEW, + E_TFF = F_ALLOW_IN, + E_FFT = F_ALLOW_UNPARATH_NEW, + E_TFT = F_ALLOW_IN | F_ALLOW_UNPARATH_NEW; + + //Statement flag sets + //NOTE: Flag order: + // F_ALLOW_IN + // F_FUNC_BODY + // F_DIRECTIVE_CTX + // F_SEMICOLON_OPT + var S_TFFF = F_ALLOW_IN, + S_TFFT = F_ALLOW_IN | F_SEMICOLON_OPT, + S_FFFF = 0x00, + S_TFTF = F_ALLOW_IN | F_DIRECTIVE_CTX, + S_TTFF = F_ALLOW_IN | F_FUNC_BODY; + + function getDefaultOptions() { + // default options + return { + indent: null, + base: null, + parse: null, + comment: false, + format: { + indent: { + style: ' ', + base: 0, + adjustMultilineComment: false + }, + newline: '\n', + space: ' ', + json: false, + renumber: false, + hexadecimal: false, + quotes: 'single', + escapeless: false, + compact: false, + parentheses: true, + semicolons: true, + safeConcatenation: false, + preserveBlankLines: false + }, + moz: { + comprehensionExpressionStartsWithAssignment: false, + starlessGenerator: false + }, + sourceMap: null, + sourceMapRoot: null, + sourceMapWithCode: false, + directive: false, + raw: true, + verbatim: null, + sourceCode: null + }; + } + + function stringRepeat(str, num) { + var result = ''; + + for (num |= 0; num > 0; num >>>= 1, str += str) { + if (num & 1) { + result += str; + } + } + + return result; + } + + function hasLineTerminator(str) { + return (/[\r\n]/g).test(str); + } + + function endsWithLineTerminator(str) { + var len = str.length; + return len && esutils.code.isLineTerminator(str.charCodeAt(len - 1)); + } + + function merge(target, override) { + var key; + for (key in override) { + if (override.hasOwnProperty(key)) { + target[key] = override[key]; + } + } + return target; + } + + function updateDeeply(target, override) { + var key, val; + + function isHashObject(target) { + return typeof target === 'object' && target instanceof Object && !(target instanceof RegExp); + } + + for (key in override) { + if (override.hasOwnProperty(key)) { + val = override[key]; + if (isHashObject(val)) { + if (isHashObject(target[key])) { + updateDeeply(target[key], val); + } else { + target[key] = updateDeeply({}, val); + } + } else { + target[key] = val; + } + } + } + return target; + } + + function generateNumber(value) { + var result, point, temp, exponent, pos; + + if (value !== value) { + throw new Error('Numeric literal whose value is NaN'); + } + if (value < 0 || (value === 0 && 1 / value < 0)) { + throw new Error('Numeric literal whose value is negative'); + } + + if (value === 1 / 0) { + return json ? 'null' : renumber ? '1e400' : '1e+400'; + } + + result = '' + value; + if (!renumber || result.length < 3) { + return result; + } + + point = result.indexOf('.'); + if (!json && result.charCodeAt(0) === 0x30 /* 0 */ && point === 1) { + point = 0; + result = result.slice(1); + } + temp = result; + result = result.replace('e+', 'e'); + exponent = 0; + if ((pos = temp.indexOf('e')) > 0) { + exponent = +temp.slice(pos + 1); + temp = temp.slice(0, pos); + } + if (point >= 0) { + exponent -= temp.length - point - 1; + temp = +(temp.slice(0, point) + temp.slice(point + 1)) + ''; + } + pos = 0; + while (temp.charCodeAt(temp.length + pos - 1) === 0x30 /* 0 */) { + --pos; + } + if (pos !== 0) { + exponent -= pos; + temp = temp.slice(0, pos); + } + if (exponent !== 0) { + temp += 'e' + exponent; + } + if ((temp.length < result.length || + (hexadecimal && value > 1e12 && Math.floor(value) === value && (temp = '0x' + value.toString(16)).length < result.length)) && + +temp === value) { + result = temp; + } + + return result; + } + + // Generate valid RegExp expression. + // This function is based on https://github.com/Constellation/iv Engine + + function escapeRegExpCharacter(ch, previousIsBackslash) { + // not handling '\' and handling \u2028 or \u2029 to unicode escape sequence + if ((ch & ~1) === 0x2028) { + return (previousIsBackslash ? 'u' : '\\u') + ((ch === 0x2028) ? '2028' : '2029'); + } else if (ch === 10 || ch === 13) { // \n, \r + return (previousIsBackslash ? '' : '\\') + ((ch === 10) ? 'n' : 'r'); + } + return String.fromCharCode(ch); + } + + function generateRegExp(reg) { + var match, result, flags, i, iz, ch, characterInBrack, previousIsBackslash; + + result = reg.toString(); + + if (reg.source) { + // extract flag from toString result + match = result.match(/\/([^/]*)$/); + if (!match) { + return result; + } + + flags = match[1]; + result = ''; + + characterInBrack = false; + previousIsBackslash = false; + for (i = 0, iz = reg.source.length; i < iz; ++i) { + ch = reg.source.charCodeAt(i); + + if (!previousIsBackslash) { + if (characterInBrack) { + if (ch === 93) { // ] + characterInBrack = false; + } + } else { + if (ch === 47) { // / + result += '\\'; + } else if (ch === 91) { // [ + characterInBrack = true; + } + } + result += escapeRegExpCharacter(ch, previousIsBackslash); + previousIsBackslash = ch === 92; // \ + } else { + // if new RegExp("\\\n') is provided, create /\n/ + result += escapeRegExpCharacter(ch, previousIsBackslash); + // prevent like /\\[/]/ + previousIsBackslash = false; + } + } + + return '/' + result + '/' + flags; + } + + return result; + } + + function escapeAllowedCharacter(code, next) { + var hex; + + if (code === 0x08 /* \b */) { + return '\\b'; + } + + if (code === 0x0C /* \f */) { + return '\\f'; + } + + if (code === 0x09 /* \t */) { + return '\\t'; + } + + hex = code.toString(16).toUpperCase(); + if (json || code > 0xFF) { + return '\\u' + '0000'.slice(hex.length) + hex; + } else if (code === 0x0000 && !esutils.code.isDecimalDigit(next)) { + return '\\0'; + } else if (code === 0x000B /* \v */) { // '\v' + return '\\x0B'; + } else { + return '\\x' + '00'.slice(hex.length) + hex; + } + } + + function escapeDisallowedCharacter(code) { + if (code === 0x5C /* \ */) { + return '\\\\'; + } + + if (code === 0x0A /* \n */) { + return '\\n'; + } + + if (code === 0x0D /* \r */) { + return '\\r'; + } + + if (code === 0x2028) { + return '\\u2028'; + } + + if (code === 0x2029) { + return '\\u2029'; + } + + throw new Error('Incorrectly classified character'); + } + + function escapeDirective(str) { + var i, iz, code, quote; + + quote = quotes === 'double' ? '"' : '\''; + for (i = 0, iz = str.length; i < iz; ++i) { + code = str.charCodeAt(i); + if (code === 0x27 /* ' */) { + quote = '"'; + break; + } else if (code === 0x22 /* " */) { + quote = '\''; + break; + } else if (code === 0x5C /* \ */) { + ++i; + } + } + + return quote + str + quote; + } + + function escapeString(str) { + var result = '', i, len, code, singleQuotes = 0, doubleQuotes = 0, single, quote; + + for (i = 0, len = str.length; i < len; ++i) { + code = str.charCodeAt(i); + if (code === 0x27 /* ' */) { + ++singleQuotes; + } else if (code === 0x22 /* " */) { + ++doubleQuotes; + } else if (code === 0x2F /* / */ && json) { + result += '\\'; + } else if (esutils.code.isLineTerminator(code) || code === 0x5C /* \ */) { + result += escapeDisallowedCharacter(code); + continue; + } else if (!esutils.code.isIdentifierPartES5(code) && (json && code < 0x20 /* SP */ || !json && !escapeless && (code < 0x20 /* SP */ || code > 0x7E /* ~ */))) { + result += escapeAllowedCharacter(code, str.charCodeAt(i + 1)); + continue; + } + result += String.fromCharCode(code); + } + + single = !(quotes === 'double' || (quotes === 'auto' && doubleQuotes < singleQuotes)); + quote = single ? '\'' : '"'; + + if (!(single ? singleQuotes : doubleQuotes)) { + return quote + result + quote; + } + + str = result; + result = quote; + + for (i = 0, len = str.length; i < len; ++i) { + code = str.charCodeAt(i); + if ((code === 0x27 /* ' */ && single) || (code === 0x22 /* " */ && !single)) { + result += '\\'; + } + result += String.fromCharCode(code); + } + + return result + quote; + } + + /** + * flatten an array to a string, where the array can contain + * either strings or nested arrays + */ + function flattenToString(arr) { + var i, iz, elem, result = ''; + for (i = 0, iz = arr.length; i < iz; ++i) { + elem = arr[i]; + result += Array.isArray(elem) ? flattenToString(elem) : elem; + } + return result; + } + + /** + * convert generated to a SourceNode when source maps are enabled. + */ + function toSourceNodeWhenNeeded(generated, node) { + if (!sourceMap) { + // with no source maps, generated is either an + // array or a string. if an array, flatten it. + // if a string, just return it + if (Array.isArray(generated)) { + return flattenToString(generated); + } else { + return generated; + } + } + if (node == null) { + if (generated instanceof SourceNode) { + return generated; + } else { + node = {}; + } + } + if (node.loc == null) { + return new SourceNode(null, null, sourceMap, generated, node.name || null); + } + return new SourceNode(node.loc.start.line, node.loc.start.column, (sourceMap === true ? node.loc.source || null : sourceMap), generated, node.name || null); + } + + function noEmptySpace() { + return (space) ? space : ' '; + } + + function join(left, right) { + var leftSource, + rightSource, + leftCharCode, + rightCharCode; + + leftSource = toSourceNodeWhenNeeded(left).toString(); + if (leftSource.length === 0) { + return [right]; + } + + rightSource = toSourceNodeWhenNeeded(right).toString(); + if (rightSource.length === 0) { + return [left]; + } + + leftCharCode = leftSource.charCodeAt(leftSource.length - 1); + rightCharCode = rightSource.charCodeAt(0); + + if ((leftCharCode === 0x2B /* + */ || leftCharCode === 0x2D /* - */) && leftCharCode === rightCharCode || + esutils.code.isIdentifierPartES5(leftCharCode) && esutils.code.isIdentifierPartES5(rightCharCode) || + leftCharCode === 0x2F /* / */ && rightCharCode === 0x69 /* i */) { // infix word operators all start with `i` + return [left, noEmptySpace(), right]; + } else if (esutils.code.isWhiteSpace(leftCharCode) || esutils.code.isLineTerminator(leftCharCode) || + esutils.code.isWhiteSpace(rightCharCode) || esutils.code.isLineTerminator(rightCharCode)) { + return [left, right]; + } + return [left, space, right]; + } + + function addIndent(stmt) { + return [base, stmt]; + } + + function withIndent(fn) { + var previousBase; + previousBase = base; + base += indent; + fn(base); + base = previousBase; + } + + function calculateSpaces(str) { + var i; + for (i = str.length - 1; i >= 0; --i) { + if (esutils.code.isLineTerminator(str.charCodeAt(i))) { + break; + } + } + return (str.length - 1) - i; + } + + function adjustMultilineComment(value, specialBase) { + var array, i, len, line, j, spaces, previousBase, sn; + + array = value.split(/\r\n|[\r\n]/); + spaces = Number.MAX_VALUE; + + // first line doesn't have indentation + for (i = 1, len = array.length; i < len; ++i) { + line = array[i]; + j = 0; + while (j < line.length && esutils.code.isWhiteSpace(line.charCodeAt(j))) { + ++j; + } + if (spaces > j) { + spaces = j; + } + } + + if (typeof specialBase !== 'undefined') { + // pattern like + // { + // var t = 20; /* + // * this is comment + // */ + // } + previousBase = base; + if (array[1][spaces] === '*') { + specialBase += ' '; + } + base = specialBase; + } else { + if (spaces & 1) { + // /* + // * + // */ + // If spaces are odd number, above pattern is considered. + // We waste 1 space. + --spaces; + } + previousBase = base; + } + + for (i = 1, len = array.length; i < len; ++i) { + sn = toSourceNodeWhenNeeded(addIndent(array[i].slice(spaces))); + array[i] = sourceMap ? sn.join('') : sn; + } + + base = previousBase; + + return array.join('\n'); + } + + function generateComment(comment, specialBase) { + if (comment.type === 'Line') { + if (endsWithLineTerminator(comment.value)) { + return '//' + comment.value; + } else { + // Always use LineTerminator + var result = '//' + comment.value; + if (!preserveBlankLines) { + result += '\n'; + } + return result; + } + } + if (extra.format.indent.adjustMultilineComment && /[\n\r]/.test(comment.value)) { + return adjustMultilineComment('/*' + comment.value + '*/', specialBase); + } + return '/*' + comment.value + '*/'; + } + + function addComments(stmt, result) { + var i, len, comment, save, tailingToStatement, specialBase, fragment, + extRange, range, prevRange, prefix, infix, suffix, count; + + if (stmt.leadingComments && stmt.leadingComments.length > 0) { + save = result; + + if (preserveBlankLines) { + comment = stmt.leadingComments[0]; + result = []; + + extRange = comment.extendedRange; + range = comment.range; + + prefix = sourceCode.substring(extRange[0], range[0]); + count = (prefix.match(/\n/g) || []).length; + if (count > 0) { + result.push(stringRepeat('\n', count)); + result.push(addIndent(generateComment(comment))); + } else { + result.push(prefix); + result.push(generateComment(comment)); + } + + prevRange = range; + + for (i = 1, len = stmt.leadingComments.length; i < len; i++) { + comment = stmt.leadingComments[i]; + range = comment.range; + + infix = sourceCode.substring(prevRange[1], range[0]); + count = (infix.match(/\n/g) || []).length; + result.push(stringRepeat('\n', count)); + result.push(addIndent(generateComment(comment))); + + prevRange = range; + } + + suffix = sourceCode.substring(range[1], extRange[1]); + count = (suffix.match(/\n/g) || []).length; + result.push(stringRepeat('\n', count)); + } else { + comment = stmt.leadingComments[0]; + result = []; + if (safeConcatenation && stmt.type === Syntax.Program && stmt.body.length === 0) { + result.push('\n'); + } + result.push(generateComment(comment)); + if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) { + result.push('\n'); + } + + for (i = 1, len = stmt.leadingComments.length; i < len; ++i) { + comment = stmt.leadingComments[i]; + fragment = [generateComment(comment)]; + if (!endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) { + fragment.push('\n'); + } + result.push(addIndent(fragment)); + } + } + + result.push(addIndent(save)); + } + + if (stmt.trailingComments) { + + if (preserveBlankLines) { + comment = stmt.trailingComments[0]; + extRange = comment.extendedRange; + range = comment.range; + + prefix = sourceCode.substring(extRange[0], range[0]); + count = (prefix.match(/\n/g) || []).length; + + if (count > 0) { + result.push(stringRepeat('\n', count)); + result.push(addIndent(generateComment(comment))); + } else { + result.push(prefix); + result.push(generateComment(comment)); + } + } else { + tailingToStatement = !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString()); + specialBase = stringRepeat(' ', calculateSpaces(toSourceNodeWhenNeeded([base, result, indent]).toString())); + for (i = 0, len = stmt.trailingComments.length; i < len; ++i) { + comment = stmt.trailingComments[i]; + if (tailingToStatement) { + // We assume target like following script + // + // var t = 20; /** + // * This is comment of t + // */ + if (i === 0) { + // first case + result = [result, indent]; + } else { + result = [result, specialBase]; + } + result.push(generateComment(comment, specialBase)); + } else { + result = [result, addIndent(generateComment(comment))]; + } + if (i !== len - 1 && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) { + result = [result, '\n']; + } + } + } + } + + return result; + } + + function generateBlankLines(start, end, result) { + var j, newlineCount = 0; + + for (j = start; j < end; j++) { + if (sourceCode[j] === '\n') { + newlineCount++; + } + } + + for (j = 1; j < newlineCount; j++) { + result.push(newline); + } + } + + function parenthesize(text, current, should) { + if (current < should) { + return ['(', text, ')']; + } + return text; + } + + function generateVerbatimString(string) { + var i, iz, result; + result = string.split(/\r\n|\n/); + for (i = 1, iz = result.length; i < iz; i++) { + result[i] = newline + base + result[i]; + } + return result; + } + + function generateVerbatim(expr, precedence) { + var verbatim, result, prec; + verbatim = expr[extra.verbatim]; + + if (typeof verbatim === 'string') { + result = parenthesize(generateVerbatimString(verbatim), Precedence.Sequence, precedence); + } else { + // verbatim is object + result = generateVerbatimString(verbatim.content); + prec = (verbatim.precedence != null) ? verbatim.precedence : Precedence.Sequence; + result = parenthesize(result, prec, precedence); + } + + return toSourceNodeWhenNeeded(result, expr); + } + + function CodeGenerator() { + } + + // Helpers. + + CodeGenerator.prototype.maybeBlock = function(stmt, flags) { + var result, noLeadingComment, that = this; + + noLeadingComment = !extra.comment || !stmt.leadingComments; + + if (stmt.type === Syntax.BlockStatement && noLeadingComment) { + return [space, this.generateStatement(stmt, flags)]; + } + + if (stmt.type === Syntax.EmptyStatement && noLeadingComment) { + return ';'; + } + + withIndent(function () { + result = [ + newline, + addIndent(that.generateStatement(stmt, flags)) + ]; + }); + + return result; + }; + + CodeGenerator.prototype.maybeBlockSuffix = function (stmt, result) { + var ends = endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString()); + if (stmt.type === Syntax.BlockStatement && (!extra.comment || !stmt.leadingComments) && !ends) { + return [result, space]; + } + if (ends) { + return [result, base]; + } + return [result, newline, base]; + }; + + function generateIdentifier(node) { + return toSourceNodeWhenNeeded(node.name, node); + } + + function generateAsyncPrefix(node, spaceRequired) { + return node.async ? 'async' + (spaceRequired ? noEmptySpace() : space) : ''; + } + + function generateStarSuffix(node) { + var isGenerator = node.generator && !extra.moz.starlessGenerator; + return isGenerator ? '*' + space : ''; + } + + function generateMethodPrefix(prop) { + var func = prop.value, prefix = ''; + if (func.async) { + prefix += generateAsyncPrefix(func, !prop.computed); + } + if (func.generator) { + // avoid space before method name + prefix += generateStarSuffix(func) ? '*' : ''; + } + return prefix; + } + + CodeGenerator.prototype.generatePattern = function (node, precedence, flags) { + if (node.type === Syntax.Identifier) { + return generateIdentifier(node); + } + return this.generateExpression(node, precedence, flags); + }; + + CodeGenerator.prototype.generateFunctionParams = function (node) { + var i, iz, result, hasDefault; + + hasDefault = false; + + if (node.type === Syntax.ArrowFunctionExpression && + !node.rest && (!node.defaults || node.defaults.length === 0) && + node.params.length === 1 && node.params[0].type === Syntax.Identifier) { + // arg => { } case + result = [generateAsyncPrefix(node, true), generateIdentifier(node.params[0])]; + } else { + result = node.type === Syntax.ArrowFunctionExpression ? [generateAsyncPrefix(node, false)] : []; + result.push('('); + if (node.defaults) { + hasDefault = true; + } + for (i = 0, iz = node.params.length; i < iz; ++i) { + if (hasDefault && node.defaults[i]) { + // Handle default values. + result.push(this.generateAssignment(node.params[i], node.defaults[i], '=', Precedence.Assignment, E_TTT)); + } else { + result.push(this.generatePattern(node.params[i], Precedence.Assignment, E_TTT)); + } + if (i + 1 < iz) { + result.push(',' + space); + } + } + + if (node.rest) { + if (node.params.length) { + result.push(',' + space); + } + result.push('...'); + result.push(generateIdentifier(node.rest)); + } + + result.push(')'); + } + + return result; + }; + + CodeGenerator.prototype.generateFunctionBody = function (node) { + var result, expr; + + result = this.generateFunctionParams(node); + + if (node.type === Syntax.ArrowFunctionExpression) { + result.push(space); + result.push('=>'); + } + + if (node.expression) { + result.push(space); + expr = this.generateExpression(node.body, Precedence.Assignment, E_TTT); + if (expr.toString().charAt(0) === '{') { + expr = ['(', expr, ')']; + } + result.push(expr); + } else { + result.push(this.maybeBlock(node.body, S_TTFF)); + } + + return result; + }; + + CodeGenerator.prototype.generateIterationForStatement = function (operator, stmt, flags) { + var result = ['for' + (stmt.await ? noEmptySpace() + 'await' : '') + space + '('], that = this; + withIndent(function () { + if (stmt.left.type === Syntax.VariableDeclaration) { + withIndent(function () { + result.push(stmt.left.kind + noEmptySpace()); + result.push(that.generateStatement(stmt.left.declarations[0], S_FFFF)); + }); + } else { + result.push(that.generateExpression(stmt.left, Precedence.Call, E_TTT)); + } + + result = join(result, operator); + result = [join( + result, + that.generateExpression(stmt.right, Precedence.Assignment, E_TTT) + ), ')']; + }); + result.push(this.maybeBlock(stmt.body, flags)); + return result; + }; + + CodeGenerator.prototype.generatePropertyKey = function (expr, computed) { + var result = []; + + if (computed) { + result.push('['); + } + + result.push(this.generateExpression(expr, Precedence.Assignment, E_TTT)); + + if (computed) { + result.push(']'); + } + + return result; + }; + + CodeGenerator.prototype.generateAssignment = function (left, right, operator, precedence, flags) { + if (Precedence.Assignment < precedence) { + flags |= F_ALLOW_IN; + } + + return parenthesize( + [ + this.generateExpression(left, Precedence.Call, flags), + space + operator + space, + this.generateExpression(right, Precedence.Assignment, flags) + ], + Precedence.Assignment, + precedence + ); + }; + + CodeGenerator.prototype.semicolon = function (flags) { + if (!semicolons && flags & F_SEMICOLON_OPT) { + return ''; + } + return ';'; + }; + + // Statements. + + CodeGenerator.Statement = { + + BlockStatement: function (stmt, flags) { + var range, content, result = ['{', newline], that = this; + + withIndent(function () { + // handle functions without any code + if (stmt.body.length === 0 && preserveBlankLines) { + range = stmt.range; + if (range[1] - range[0] > 2) { + content = sourceCode.substring(range[0] + 1, range[1] - 1); + if (content[0] === '\n') { + result = ['{']; + } + result.push(content); + } + } + + var i, iz, fragment, bodyFlags; + bodyFlags = S_TFFF; + if (flags & F_FUNC_BODY) { + bodyFlags |= F_DIRECTIVE_CTX; + } + + for (i = 0, iz = stmt.body.length; i < iz; ++i) { + if (preserveBlankLines) { + // handle spaces before the first line + if (i === 0) { + if (stmt.body[0].leadingComments) { + range = stmt.body[0].leadingComments[0].extendedRange; + content = sourceCode.substring(range[0], range[1]); + if (content[0] === '\n') { + result = ['{']; + } + } + if (!stmt.body[0].leadingComments) { + generateBlankLines(stmt.range[0], stmt.body[0].range[0], result); + } + } + + // handle spaces between lines + if (i > 0) { + if (!stmt.body[i - 1].trailingComments && !stmt.body[i].leadingComments) { + generateBlankLines(stmt.body[i - 1].range[1], stmt.body[i].range[0], result); + } + } + } + + if (i === iz - 1) { + bodyFlags |= F_SEMICOLON_OPT; + } + + if (stmt.body[i].leadingComments && preserveBlankLines) { + fragment = that.generateStatement(stmt.body[i], bodyFlags); + } else { + fragment = addIndent(that.generateStatement(stmt.body[i], bodyFlags)); + } + + result.push(fragment); + if (!endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) { + if (preserveBlankLines && i < iz - 1) { + // don't add a new line if there are leading coments + // in the next statement + if (!stmt.body[i + 1].leadingComments) { + result.push(newline); + } + } else { + result.push(newline); + } + } + + if (preserveBlankLines) { + // handle spaces after the last line + if (i === iz - 1) { + if (!stmt.body[i].trailingComments) { + generateBlankLines(stmt.body[i].range[1], stmt.range[1], result); + } + } + } + } + }); + + result.push(addIndent('}')); + return result; + }, + + BreakStatement: function (stmt, flags) { + if (stmt.label) { + return 'break ' + stmt.label.name + this.semicolon(flags); + } + return 'break' + this.semicolon(flags); + }, + + ContinueStatement: function (stmt, flags) { + if (stmt.label) { + return 'continue ' + stmt.label.name + this.semicolon(flags); + } + return 'continue' + this.semicolon(flags); + }, + + ClassBody: function (stmt, flags) { + var result = [ '{', newline], that = this; + + withIndent(function (indent) { + var i, iz; + + for (i = 0, iz = stmt.body.length; i < iz; ++i) { + result.push(indent); + result.push(that.generateExpression(stmt.body[i], Precedence.Sequence, E_TTT)); + if (i + 1 < iz) { + result.push(newline); + } + } + }); + + if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) { + result.push(newline); + } + result.push(base); + result.push('}'); + return result; + }, + + ClassDeclaration: function (stmt, flags) { + var result, fragment; + result = ['class']; + if (stmt.id) { + result = join(result, this.generateExpression(stmt.id, Precedence.Sequence, E_TTT)); + } + if (stmt.superClass) { + fragment = join('extends', this.generateExpression(stmt.superClass, Precedence.Unary, E_TTT)); + result = join(result, fragment); + } + result.push(space); + result.push(this.generateStatement(stmt.body, S_TFFT)); + return result; + }, + + DirectiveStatement: function (stmt, flags) { + if (extra.raw && stmt.raw) { + return stmt.raw + this.semicolon(flags); + } + return escapeDirective(stmt.directive) + this.semicolon(flags); + }, + + DoWhileStatement: function (stmt, flags) { + // Because `do 42 while (cond)` is Syntax Error. We need semicolon. + var result = join('do', this.maybeBlock(stmt.body, S_TFFF)); + result = this.maybeBlockSuffix(stmt.body, result); + return join(result, [ + 'while' + space + '(', + this.generateExpression(stmt.test, Precedence.Sequence, E_TTT), + ')' + this.semicolon(flags) + ]); + }, + + CatchClause: function (stmt, flags) { + var result, that = this; + withIndent(function () { + var guard; + + if (stmt.param) { + result = [ + 'catch' + space + '(', + that.generateExpression(stmt.param, Precedence.Sequence, E_TTT), + ')' + ]; + + if (stmt.guard) { + guard = that.generateExpression(stmt.guard, Precedence.Sequence, E_TTT); + result.splice(2, 0, ' if ', guard); + } + } else { + result = ['catch']; + } + }); + result.push(this.maybeBlock(stmt.body, S_TFFF)); + return result; + }, + + DebuggerStatement: function (stmt, flags) { + return 'debugger' + this.semicolon(flags); + }, + + EmptyStatement: function (stmt, flags) { + return ';'; + }, + + ExportDefaultDeclaration: function (stmt, flags) { + var result = [ 'export' ], bodyFlags; + + bodyFlags = (flags & F_SEMICOLON_OPT) ? S_TFFT : S_TFFF; + + // export default HoistableDeclaration[Default] + // export default AssignmentExpression[In] ; + result = join(result, 'default'); + if (isStatement(stmt.declaration)) { + result = join(result, this.generateStatement(stmt.declaration, bodyFlags)); + } else { + result = join(result, this.generateExpression(stmt.declaration, Precedence.Assignment, E_TTT) + this.semicolon(flags)); + } + return result; + }, + + ExportNamedDeclaration: function (stmt, flags) { + var result = [ 'export' ], bodyFlags, that = this; + + bodyFlags = (flags & F_SEMICOLON_OPT) ? S_TFFT : S_TFFF; + + // export VariableStatement + // export Declaration[Default] + if (stmt.declaration) { + return join(result, this.generateStatement(stmt.declaration, bodyFlags)); + } + + // export ExportClause[NoReference] FromClause ; + // export ExportClause ; + if (stmt.specifiers) { + if (stmt.specifiers.length === 0) { + result = join(result, '{' + space + '}'); + } else if (stmt.specifiers[0].type === Syntax.ExportBatchSpecifier) { + result = join(result, this.generateExpression(stmt.specifiers[0], Precedence.Sequence, E_TTT)); + } else { + result = join(result, '{'); + withIndent(function (indent) { + var i, iz; + result.push(newline); + for (i = 0, iz = stmt.specifiers.length; i < iz; ++i) { + result.push(indent); + result.push(that.generateExpression(stmt.specifiers[i], Precedence.Sequence, E_TTT)); + if (i + 1 < iz) { + result.push(',' + newline); + } + } + }); + if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) { + result.push(newline); + } + result.push(base + '}'); + } + + if (stmt.source) { + result = join(result, [ + 'from' + space, + // ModuleSpecifier + this.generateExpression(stmt.source, Precedence.Sequence, E_TTT), + this.semicolon(flags) + ]); + } else { + result.push(this.semicolon(flags)); + } + } + return result; + }, + + ExportAllDeclaration: function (stmt, flags) { + // export * FromClause ; + return [ + 'export' + space, + '*' + space, + 'from' + space, + // ModuleSpecifier + this.generateExpression(stmt.source, Precedence.Sequence, E_TTT), + this.semicolon(flags) + ]; + }, + + ExpressionStatement: function (stmt, flags) { + var result, fragment; + + function isClassPrefixed(fragment) { + var code; + if (fragment.slice(0, 5) !== 'class') { + return false; + } + code = fragment.charCodeAt(5); + return code === 0x7B /* '{' */ || esutils.code.isWhiteSpace(code) || esutils.code.isLineTerminator(code); + } + + function isFunctionPrefixed(fragment) { + var code; + if (fragment.slice(0, 8) !== 'function') { + return false; + } + code = fragment.charCodeAt(8); + return code === 0x28 /* '(' */ || esutils.code.isWhiteSpace(code) || code === 0x2A /* '*' */ || esutils.code.isLineTerminator(code); + } + + function isAsyncPrefixed(fragment) { + var code, i, iz; + if (fragment.slice(0, 5) !== 'async') { + return false; + } + if (!esutils.code.isWhiteSpace(fragment.charCodeAt(5))) { + return false; + } + for (i = 6, iz = fragment.length; i < iz; ++i) { + if (!esutils.code.isWhiteSpace(fragment.charCodeAt(i))) { + break; + } + } + if (i === iz) { + return false; + } + if (fragment.slice(i, i + 8) !== 'function') { + return false; + } + code = fragment.charCodeAt(i + 8); + return code === 0x28 /* '(' */ || esutils.code.isWhiteSpace(code) || code === 0x2A /* '*' */ || esutils.code.isLineTerminator(code); + } + + result = [this.generateExpression(stmt.expression, Precedence.Sequence, E_TTT)]; + // 12.4 '{', 'function', 'class' is not allowed in this position. + // wrap expression with parentheses + fragment = toSourceNodeWhenNeeded(result).toString(); + if (fragment.charCodeAt(0) === 0x7B /* '{' */ || // ObjectExpression + isClassPrefixed(fragment) || + isFunctionPrefixed(fragment) || + isAsyncPrefixed(fragment) || + (directive && (flags & F_DIRECTIVE_CTX) && stmt.expression.type === Syntax.Literal && typeof stmt.expression.value === 'string')) { + result = ['(', result, ')' + this.semicolon(flags)]; + } else { + result.push(this.semicolon(flags)); + } + return result; + }, + + ImportDeclaration: function (stmt, flags) { + // ES6: 15.2.1 valid import declarations: + // - import ImportClause FromClause ; + // - import ModuleSpecifier ; + var result, cursor, that = this; + + // If no ImportClause is present, + // this should be `import ModuleSpecifier` so skip `from` + // ModuleSpecifier is StringLiteral. + if (stmt.specifiers.length === 0) { + // import ModuleSpecifier ; + return [ + 'import', + space, + // ModuleSpecifier + this.generateExpression(stmt.source, Precedence.Sequence, E_TTT), + this.semicolon(flags) + ]; + } + + // import ImportClause FromClause ; + result = [ + 'import' + ]; + cursor = 0; + + // ImportedBinding + if (stmt.specifiers[cursor].type === Syntax.ImportDefaultSpecifier) { + result = join(result, [ + this.generateExpression(stmt.specifiers[cursor], Precedence.Sequence, E_TTT) + ]); + ++cursor; + } + + if (stmt.specifiers[cursor]) { + if (cursor !== 0) { + result.push(','); + } + + if (stmt.specifiers[cursor].type === Syntax.ImportNamespaceSpecifier) { + // NameSpaceImport + result = join(result, [ + space, + this.generateExpression(stmt.specifiers[cursor], Precedence.Sequence, E_TTT) + ]); + } else { + // NamedImports + result.push(space + '{'); + + if ((stmt.specifiers.length - cursor) === 1) { + // import { ... } from "..."; + result.push(space); + result.push(this.generateExpression(stmt.specifiers[cursor], Precedence.Sequence, E_TTT)); + result.push(space + '}' + space); + } else { + // import { + // ..., + // ..., + // } from "..."; + withIndent(function (indent) { + var i, iz; + result.push(newline); + for (i = cursor, iz = stmt.specifiers.length; i < iz; ++i) { + result.push(indent); + result.push(that.generateExpression(stmt.specifiers[i], Precedence.Sequence, E_TTT)); + if (i + 1 < iz) { + result.push(',' + newline); + } + } + }); + if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) { + result.push(newline); + } + result.push(base + '}' + space); + } + } + } + + result = join(result, [ + 'from' + space, + // ModuleSpecifier + this.generateExpression(stmt.source, Precedence.Sequence, E_TTT), + this.semicolon(flags) + ]); + return result; + }, + + VariableDeclarator: function (stmt, flags) { + var itemFlags = (flags & F_ALLOW_IN) ? E_TTT : E_FTT; + if (stmt.init) { + return [ + this.generateExpression(stmt.id, Precedence.Assignment, itemFlags), + space, + '=', + space, + this.generateExpression(stmt.init, Precedence.Assignment, itemFlags) + ]; + } + return this.generatePattern(stmt.id, Precedence.Assignment, itemFlags); + }, + + VariableDeclaration: function (stmt, flags) { + // VariableDeclarator is typed as Statement, + // but joined with comma (not LineTerminator). + // So if comment is attached to target node, we should specialize. + var result, i, iz, node, bodyFlags, that = this; + + result = [ stmt.kind ]; + + bodyFlags = (flags & F_ALLOW_IN) ? S_TFFF : S_FFFF; + + function block() { + node = stmt.declarations[0]; + if (extra.comment && node.leadingComments) { + result.push('\n'); + result.push(addIndent(that.generateStatement(node, bodyFlags))); + } else { + result.push(noEmptySpace()); + result.push(that.generateStatement(node, bodyFlags)); + } + + for (i = 1, iz = stmt.declarations.length; i < iz; ++i) { + node = stmt.declarations[i]; + if (extra.comment && node.leadingComments) { + result.push(',' + newline); + result.push(addIndent(that.generateStatement(node, bodyFlags))); + } else { + result.push(',' + space); + result.push(that.generateStatement(node, bodyFlags)); + } + } + } + + if (stmt.declarations.length > 1) { + withIndent(block); + } else { + block(); + } + + result.push(this.semicolon(flags)); + + return result; + }, + + ThrowStatement: function (stmt, flags) { + return [join( + 'throw', + this.generateExpression(stmt.argument, Precedence.Sequence, E_TTT) + ), this.semicolon(flags)]; + }, + + TryStatement: function (stmt, flags) { + var result, i, iz, guardedHandlers; + + result = ['try', this.maybeBlock(stmt.block, S_TFFF)]; + result = this.maybeBlockSuffix(stmt.block, result); + + if (stmt.handlers) { + // old interface + for (i = 0, iz = stmt.handlers.length; i < iz; ++i) { + result = join(result, this.generateStatement(stmt.handlers[i], S_TFFF)); + if (stmt.finalizer || i + 1 !== iz) { + result = this.maybeBlockSuffix(stmt.handlers[i].body, result); + } + } + } else { + guardedHandlers = stmt.guardedHandlers || []; + + for (i = 0, iz = guardedHandlers.length; i < iz; ++i) { + result = join(result, this.generateStatement(guardedHandlers[i], S_TFFF)); + if (stmt.finalizer || i + 1 !== iz) { + result = this.maybeBlockSuffix(guardedHandlers[i].body, result); + } + } + + // new interface + if (stmt.handler) { + if (Array.isArray(stmt.handler)) { + for (i = 0, iz = stmt.handler.length; i < iz; ++i) { + result = join(result, this.generateStatement(stmt.handler[i], S_TFFF)); + if (stmt.finalizer || i + 1 !== iz) { + result = this.maybeBlockSuffix(stmt.handler[i].body, result); + } + } + } else { + result = join(result, this.generateStatement(stmt.handler, S_TFFF)); + if (stmt.finalizer) { + result = this.maybeBlockSuffix(stmt.handler.body, result); + } + } + } + } + if (stmt.finalizer) { + result = join(result, ['finally', this.maybeBlock(stmt.finalizer, S_TFFF)]); + } + return result; + }, + + SwitchStatement: function (stmt, flags) { + var result, fragment, i, iz, bodyFlags, that = this; + withIndent(function () { + result = [ + 'switch' + space + '(', + that.generateExpression(stmt.discriminant, Precedence.Sequence, E_TTT), + ')' + space + '{' + newline + ]; + }); + if (stmt.cases) { + bodyFlags = S_TFFF; + for (i = 0, iz = stmt.cases.length; i < iz; ++i) { + if (i === iz - 1) { + bodyFlags |= F_SEMICOLON_OPT; + } + fragment = addIndent(this.generateStatement(stmt.cases[i], bodyFlags)); + result.push(fragment); + if (!endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) { + result.push(newline); + } + } + } + result.push(addIndent('}')); + return result; + }, + + SwitchCase: function (stmt, flags) { + var result, fragment, i, iz, bodyFlags, that = this; + withIndent(function () { + if (stmt.test) { + result = [ + join('case', that.generateExpression(stmt.test, Precedence.Sequence, E_TTT)), + ':' + ]; + } else { + result = ['default:']; + } + + i = 0; + iz = stmt.consequent.length; + if (iz && stmt.consequent[0].type === Syntax.BlockStatement) { + fragment = that.maybeBlock(stmt.consequent[0], S_TFFF); + result.push(fragment); + i = 1; + } + + if (i !== iz && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) { + result.push(newline); + } + + bodyFlags = S_TFFF; + for (; i < iz; ++i) { + if (i === iz - 1 && flags & F_SEMICOLON_OPT) { + bodyFlags |= F_SEMICOLON_OPT; + } + fragment = addIndent(that.generateStatement(stmt.consequent[i], bodyFlags)); + result.push(fragment); + if (i + 1 !== iz && !endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) { + result.push(newline); + } + } + }); + return result; + }, + + IfStatement: function (stmt, flags) { + var result, bodyFlags, semicolonOptional, that = this; + withIndent(function () { + result = [ + 'if' + space + '(', + that.generateExpression(stmt.test, Precedence.Sequence, E_TTT), + ')' + ]; + }); + semicolonOptional = flags & F_SEMICOLON_OPT; + bodyFlags = S_TFFF; + if (semicolonOptional) { + bodyFlags |= F_SEMICOLON_OPT; + } + if (stmt.alternate) { + result.push(this.maybeBlock(stmt.consequent, S_TFFF)); + result = this.maybeBlockSuffix(stmt.consequent, result); + if (stmt.alternate.type === Syntax.IfStatement) { + result = join(result, ['else ', this.generateStatement(stmt.alternate, bodyFlags)]); + } else { + result = join(result, join('else', this.maybeBlock(stmt.alternate, bodyFlags))); + } + } else { + result.push(this.maybeBlock(stmt.consequent, bodyFlags)); + } + return result; + }, + + ForStatement: function (stmt, flags) { + var result, that = this; + withIndent(function () { + result = ['for' + space + '(']; + if (stmt.init) { + if (stmt.init.type === Syntax.VariableDeclaration) { + result.push(that.generateStatement(stmt.init, S_FFFF)); + } else { + // F_ALLOW_IN becomes false. + result.push(that.generateExpression(stmt.init, Precedence.Sequence, E_FTT)); + result.push(';'); + } + } else { + result.push(';'); + } + + if (stmt.test) { + result.push(space); + result.push(that.generateExpression(stmt.test, Precedence.Sequence, E_TTT)); + result.push(';'); + } else { + result.push(';'); + } + + if (stmt.update) { + result.push(space); + result.push(that.generateExpression(stmt.update, Precedence.Sequence, E_TTT)); + result.push(')'); + } else { + result.push(')'); + } + }); + + result.push(this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF)); + return result; + }, + + ForInStatement: function (stmt, flags) { + return this.generateIterationForStatement('in', stmt, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF); + }, + + ForOfStatement: function (stmt, flags) { + return this.generateIterationForStatement('of', stmt, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF); + }, + + LabeledStatement: function (stmt, flags) { + return [stmt.label.name + ':', this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF)]; + }, + + Program: function (stmt, flags) { + var result, fragment, i, iz, bodyFlags; + iz = stmt.body.length; + result = [safeConcatenation && iz > 0 ? '\n' : '']; + bodyFlags = S_TFTF; + for (i = 0; i < iz; ++i) { + if (!safeConcatenation && i === iz - 1) { + bodyFlags |= F_SEMICOLON_OPT; + } + + if (preserveBlankLines) { + // handle spaces before the first line + if (i === 0) { + if (!stmt.body[0].leadingComments) { + generateBlankLines(stmt.range[0], stmt.body[i].range[0], result); + } + } + + // handle spaces between lines + if (i > 0) { + if (!stmt.body[i - 1].trailingComments && !stmt.body[i].leadingComments) { + generateBlankLines(stmt.body[i - 1].range[1], stmt.body[i].range[0], result); + } + } + } + + fragment = addIndent(this.generateStatement(stmt.body[i], bodyFlags)); + result.push(fragment); + if (i + 1 < iz && !endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) { + if (preserveBlankLines) { + if (!stmt.body[i + 1].leadingComments) { + result.push(newline); + } + } else { + result.push(newline); + } + } + + if (preserveBlankLines) { + // handle spaces after the last line + if (i === iz - 1) { + if (!stmt.body[i].trailingComments) { + generateBlankLines(stmt.body[i].range[1], stmt.range[1], result); + } + } + } + } + return result; + }, + + FunctionDeclaration: function (stmt, flags) { + return [ + generateAsyncPrefix(stmt, true), + 'function', + generateStarSuffix(stmt) || noEmptySpace(), + stmt.id ? generateIdentifier(stmt.id) : '', + this.generateFunctionBody(stmt) + ]; + }, + + ReturnStatement: function (stmt, flags) { + if (stmt.argument) { + return [join( + 'return', + this.generateExpression(stmt.argument, Precedence.Sequence, E_TTT) + ), this.semicolon(flags)]; + } + return ['return' + this.semicolon(flags)]; + }, + + WhileStatement: function (stmt, flags) { + var result, that = this; + withIndent(function () { + result = [ + 'while' + space + '(', + that.generateExpression(stmt.test, Precedence.Sequence, E_TTT), + ')' + ]; + }); + result.push(this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF)); + return result; + }, + + WithStatement: function (stmt, flags) { + var result, that = this; + withIndent(function () { + result = [ + 'with' + space + '(', + that.generateExpression(stmt.object, Precedence.Sequence, E_TTT), + ')' + ]; + }); + result.push(this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF)); + return result; + } + + }; + + merge(CodeGenerator.prototype, CodeGenerator.Statement); + + // Expressions. + + CodeGenerator.Expression = { + + SequenceExpression: function (expr, precedence, flags) { + var result, i, iz; + if (Precedence.Sequence < precedence) { + flags |= F_ALLOW_IN; + } + result = []; + for (i = 0, iz = expr.expressions.length; i < iz; ++i) { + result.push(this.generateExpression(expr.expressions[i], Precedence.Assignment, flags)); + if (i + 1 < iz) { + result.push(',' + space); + } + } + return parenthesize(result, Precedence.Sequence, precedence); + }, + + AssignmentExpression: function (expr, precedence, flags) { + return this.generateAssignment(expr.left, expr.right, expr.operator, precedence, flags); + }, + + ArrowFunctionExpression: function (expr, precedence, flags) { + return parenthesize(this.generateFunctionBody(expr), Precedence.ArrowFunction, precedence); + }, + + ConditionalExpression: function (expr, precedence, flags) { + if (Precedence.Conditional < precedence) { + flags |= F_ALLOW_IN; + } + return parenthesize( + [ + this.generateExpression(expr.test, Precedence.Coalesce, flags), + space + '?' + space, + this.generateExpression(expr.consequent, Precedence.Assignment, flags), + space + ':' + space, + this.generateExpression(expr.alternate, Precedence.Assignment, flags) + ], + Precedence.Conditional, + precedence + ); + }, + + LogicalExpression: function (expr, precedence, flags) { + if (expr.operator === '??') { + flags |= F_FOUND_COALESCE; + } + return this.BinaryExpression(expr, precedence, flags); + }, + + BinaryExpression: function (expr, precedence, flags) { + var result, leftPrecedence, rightPrecedence, currentPrecedence, fragment, leftSource; + currentPrecedence = BinaryPrecedence[expr.operator]; + leftPrecedence = expr.operator === '**' ? Precedence.Postfix : currentPrecedence; + rightPrecedence = expr.operator === '**' ? currentPrecedence : currentPrecedence + 1; + + if (currentPrecedence < precedence) { + flags |= F_ALLOW_IN; + } + + fragment = this.generateExpression(expr.left, leftPrecedence, flags); + + leftSource = fragment.toString(); + + if (leftSource.charCodeAt(leftSource.length - 1) === 0x2F /* / */ && esutils.code.isIdentifierPartES5(expr.operator.charCodeAt(0))) { + result = [fragment, noEmptySpace(), expr.operator]; + } else { + result = join(fragment, expr.operator); + } + + fragment = this.generateExpression(expr.right, rightPrecedence, flags); + + if (expr.operator === '/' && fragment.toString().charAt(0) === '/' || + expr.operator.slice(-1) === '<' && fragment.toString().slice(0, 3) === '!--') { + // If '/' concats with '/' or `<` concats with `!--`, it is interpreted as comment start + result.push(noEmptySpace()); + result.push(fragment); + } else { + result = join(result, fragment); + } + + if (expr.operator === 'in' && !(flags & F_ALLOW_IN)) { + return ['(', result, ')']; + } + if ((expr.operator === '||' || expr.operator === '&&') && (flags & F_FOUND_COALESCE)) { + return ['(', result, ')']; + } + return parenthesize(result, currentPrecedence, precedence); + }, + + CallExpression: function (expr, precedence, flags) { + var result, i, iz; + + // F_ALLOW_UNPARATH_NEW becomes false. + result = [this.generateExpression(expr.callee, Precedence.Call, E_TTF)]; + + if (expr.optional) { + result.push('?.'); + } + + result.push('('); + for (i = 0, iz = expr['arguments'].length; i < iz; ++i) { + result.push(this.generateExpression(expr['arguments'][i], Precedence.Assignment, E_TTT)); + if (i + 1 < iz) { + result.push(',' + space); + } + } + result.push(')'); + + if (!(flags & F_ALLOW_CALL)) { + return ['(', result, ')']; + } + + return parenthesize(result, Precedence.Call, precedence); + }, + + ChainExpression: function (expr, precedence, flags) { + if (Precedence.OptionalChaining < precedence) { + flags |= F_ALLOW_CALL; + } + + var result = this.generateExpression(expr.expression, Precedence.OptionalChaining, flags); + + return parenthesize(result, Precedence.OptionalChaining, precedence); + }, + + NewExpression: function (expr, precedence, flags) { + var result, length, i, iz, itemFlags; + length = expr['arguments'].length; + + // F_ALLOW_CALL becomes false. + // F_ALLOW_UNPARATH_NEW may become false. + itemFlags = (flags & F_ALLOW_UNPARATH_NEW && !parentheses && length === 0) ? E_TFT : E_TFF; + + result = join( + 'new', + this.generateExpression(expr.callee, Precedence.New, itemFlags) + ); + + if (!(flags & F_ALLOW_UNPARATH_NEW) || parentheses || length > 0) { + result.push('('); + for (i = 0, iz = length; i < iz; ++i) { + result.push(this.generateExpression(expr['arguments'][i], Precedence.Assignment, E_TTT)); + if (i + 1 < iz) { + result.push(',' + space); + } + } + result.push(')'); + } + + return parenthesize(result, Precedence.New, precedence); + }, + + MemberExpression: function (expr, precedence, flags) { + var result, fragment; + + // F_ALLOW_UNPARATH_NEW becomes false. + result = [this.generateExpression(expr.object, Precedence.Call, (flags & F_ALLOW_CALL) ? E_TTF : E_TFF)]; + + if (expr.computed) { + if (expr.optional) { + result.push('?.'); + } + + result.push('['); + result.push(this.generateExpression(expr.property, Precedence.Sequence, flags & F_ALLOW_CALL ? E_TTT : E_TFT)); + result.push(']'); + } else { + if (!expr.optional && expr.object.type === Syntax.Literal && typeof expr.object.value === 'number') { + fragment = toSourceNodeWhenNeeded(result).toString(); + // When the following conditions are all true, + // 1. No floating point + // 2. Don't have exponents + // 3. The last character is a decimal digit + // 4. Not hexadecimal OR octal number literal + // we should add a floating point. + if ( + fragment.indexOf('.') < 0 && + !/[eExX]/.test(fragment) && + esutils.code.isDecimalDigit(fragment.charCodeAt(fragment.length - 1)) && + !(fragment.length >= 2 && fragment.charCodeAt(0) === 48) // '0' + ) { + result.push(' '); + } + } + result.push(expr.optional ? '?.' : '.'); + result.push(generateIdentifier(expr.property)); + } + + return parenthesize(result, Precedence.Member, precedence); + }, + + MetaProperty: function (expr, precedence, flags) { + var result; + result = []; + result.push(typeof expr.meta === "string" ? expr.meta : generateIdentifier(expr.meta)); + result.push('.'); + result.push(typeof expr.property === "string" ? expr.property : generateIdentifier(expr.property)); + return parenthesize(result, Precedence.Member, precedence); + }, + + UnaryExpression: function (expr, precedence, flags) { + var result, fragment, rightCharCode, leftSource, leftCharCode; + fragment = this.generateExpression(expr.argument, Precedence.Unary, E_TTT); + + if (space === '') { + result = join(expr.operator, fragment); + } else { + result = [expr.operator]; + if (expr.operator.length > 2) { + // delete, void, typeof + // get `typeof []`, not `typeof[]` + result = join(result, fragment); + } else { + // Prevent inserting spaces between operator and argument if it is unnecessary + // like, `!cond` + leftSource = toSourceNodeWhenNeeded(result).toString(); + leftCharCode = leftSource.charCodeAt(leftSource.length - 1); + rightCharCode = fragment.toString().charCodeAt(0); + + if (((leftCharCode === 0x2B /* + */ || leftCharCode === 0x2D /* - */) && leftCharCode === rightCharCode) || + (esutils.code.isIdentifierPartES5(leftCharCode) && esutils.code.isIdentifierPartES5(rightCharCode))) { + result.push(noEmptySpace()); + result.push(fragment); + } else { + result.push(fragment); + } + } + } + return parenthesize(result, Precedence.Unary, precedence); + }, + + YieldExpression: function (expr, precedence, flags) { + var result; + if (expr.delegate) { + result = 'yield*'; + } else { + result = 'yield'; + } + if (expr.argument) { + result = join( + result, + this.generateExpression(expr.argument, Precedence.Yield, E_TTT) + ); + } + return parenthesize(result, Precedence.Yield, precedence); + }, + + AwaitExpression: function (expr, precedence, flags) { + var result = join( + expr.all ? 'await*' : 'await', + this.generateExpression(expr.argument, Precedence.Await, E_TTT) + ); + return parenthesize(result, Precedence.Await, precedence); + }, + + UpdateExpression: function (expr, precedence, flags) { + if (expr.prefix) { + return parenthesize( + [ + expr.operator, + this.generateExpression(expr.argument, Precedence.Unary, E_TTT) + ], + Precedence.Unary, + precedence + ); + } + return parenthesize( + [ + this.generateExpression(expr.argument, Precedence.Postfix, E_TTT), + expr.operator + ], + Precedence.Postfix, + precedence + ); + }, + + FunctionExpression: function (expr, precedence, flags) { + var result = [ + generateAsyncPrefix(expr, true), + 'function' + ]; + if (expr.id) { + result.push(generateStarSuffix(expr) || noEmptySpace()); + result.push(generateIdentifier(expr.id)); + } else { + result.push(generateStarSuffix(expr) || space); + } + result.push(this.generateFunctionBody(expr)); + return result; + }, + + ArrayPattern: function (expr, precedence, flags) { + return this.ArrayExpression(expr, precedence, flags, true); + }, + + ArrayExpression: function (expr, precedence, flags, isPattern) { + var result, multiline, that = this; + if (!expr.elements.length) { + return '[]'; + } + multiline = isPattern ? false : expr.elements.length > 1; + result = ['[', multiline ? newline : '']; + withIndent(function (indent) { + var i, iz; + for (i = 0, iz = expr.elements.length; i < iz; ++i) { + if (!expr.elements[i]) { + if (multiline) { + result.push(indent); + } + if (i + 1 === iz) { + result.push(','); + } + } else { + result.push(multiline ? indent : ''); + result.push(that.generateExpression(expr.elements[i], Precedence.Assignment, E_TTT)); + } + if (i + 1 < iz) { + result.push(',' + (multiline ? newline : space)); + } + } + }); + if (multiline && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) { + result.push(newline); + } + result.push(multiline ? base : ''); + result.push(']'); + return result; + }, + + RestElement: function(expr, precedence, flags) { + return '...' + this.generatePattern(expr.argument); + }, + + ClassExpression: function (expr, precedence, flags) { + var result, fragment; + result = ['class']; + if (expr.id) { + result = join(result, this.generateExpression(expr.id, Precedence.Sequence, E_TTT)); + } + if (expr.superClass) { + fragment = join('extends', this.generateExpression(expr.superClass, Precedence.Unary, E_TTT)); + result = join(result, fragment); + } + result.push(space); + result.push(this.generateStatement(expr.body, S_TFFT)); + return result; + }, + + MethodDefinition: function (expr, precedence, flags) { + var result, fragment; + if (expr['static']) { + result = ['static' + space]; + } else { + result = []; + } + if (expr.kind === 'get' || expr.kind === 'set') { + fragment = [ + join(expr.kind, this.generatePropertyKey(expr.key, expr.computed)), + this.generateFunctionBody(expr.value) + ]; + } else { + fragment = [ + generateMethodPrefix(expr), + this.generatePropertyKey(expr.key, expr.computed), + this.generateFunctionBody(expr.value) + ]; + } + return join(result, fragment); + }, + + Property: function (expr, precedence, flags) { + if (expr.kind === 'get' || expr.kind === 'set') { + return [ + expr.kind, noEmptySpace(), + this.generatePropertyKey(expr.key, expr.computed), + this.generateFunctionBody(expr.value) + ]; + } + + if (expr.shorthand) { + if (expr.value.type === "AssignmentPattern") { + return this.AssignmentPattern(expr.value, Precedence.Sequence, E_TTT); + } + return this.generatePropertyKey(expr.key, expr.computed); + } + + if (expr.method) { + return [ + generateMethodPrefix(expr), + this.generatePropertyKey(expr.key, expr.computed), + this.generateFunctionBody(expr.value) + ]; + } + + return [ + this.generatePropertyKey(expr.key, expr.computed), + ':' + space, + this.generateExpression(expr.value, Precedence.Assignment, E_TTT) + ]; + }, + + ObjectExpression: function (expr, precedence, flags) { + var multiline, result, fragment, that = this; + + if (!expr.properties.length) { + return '{}'; + } + multiline = expr.properties.length > 1; + + withIndent(function () { + fragment = that.generateExpression(expr.properties[0], Precedence.Sequence, E_TTT); + }); + + if (!multiline) { + // issues 4 + // Do not transform from + // dejavu.Class.declare({ + // method2: function () {} + // }); + // to + // dejavu.Class.declare({method2: function () { + // }}); + if (!hasLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) { + return [ '{', space, fragment, space, '}' ]; + } + } + + withIndent(function (indent) { + var i, iz; + result = [ '{', newline, indent, fragment ]; + + if (multiline) { + result.push(',' + newline); + for (i = 1, iz = expr.properties.length; i < iz; ++i) { + result.push(indent); + result.push(that.generateExpression(expr.properties[i], Precedence.Sequence, E_TTT)); + if (i + 1 < iz) { + result.push(',' + newline); + } + } + } + }); + + if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) { + result.push(newline); + } + result.push(base); + result.push('}'); + return result; + }, + + AssignmentPattern: function(expr, precedence, flags) { + return this.generateAssignment(expr.left, expr.right, '=', precedence, flags); + }, + + ObjectPattern: function (expr, precedence, flags) { + var result, i, iz, multiline, property, that = this; + if (!expr.properties.length) { + return '{}'; + } + + multiline = false; + if (expr.properties.length === 1) { + property = expr.properties[0]; + if ( + property.type === Syntax.Property + && property.value.type !== Syntax.Identifier + ) { + multiline = true; + } + } else { + for (i = 0, iz = expr.properties.length; i < iz; ++i) { + property = expr.properties[i]; + if ( + property.type === Syntax.Property + && !property.shorthand + ) { + multiline = true; + break; + } + } + } + result = ['{', multiline ? newline : '' ]; + + withIndent(function (indent) { + var i, iz; + for (i = 0, iz = expr.properties.length; i < iz; ++i) { + result.push(multiline ? indent : ''); + result.push(that.generateExpression(expr.properties[i], Precedence.Sequence, E_TTT)); + if (i + 1 < iz) { + result.push(',' + (multiline ? newline : space)); + } + } + }); + + if (multiline && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) { + result.push(newline); + } + result.push(multiline ? base : ''); + result.push('}'); + return result; + }, + + ThisExpression: function (expr, precedence, flags) { + return 'this'; + }, + + Super: function (expr, precedence, flags) { + return 'super'; + }, + + Identifier: function (expr, precedence, flags) { + return generateIdentifier(expr); + }, + + ImportDefaultSpecifier: function (expr, precedence, flags) { + return generateIdentifier(expr.id || expr.local); + }, + + ImportNamespaceSpecifier: function (expr, precedence, flags) { + var result = ['*']; + var id = expr.id || expr.local; + if (id) { + result.push(space + 'as' + noEmptySpace() + generateIdentifier(id)); + } + return result; + }, + + ImportSpecifier: function (expr, precedence, flags) { + var imported = expr.imported; + var result = [ imported.name ]; + var local = expr.local; + if (local && local.name !== imported.name) { + result.push(noEmptySpace() + 'as' + noEmptySpace() + generateIdentifier(local)); + } + return result; + }, + + ExportSpecifier: function (expr, precedence, flags) { + var local = expr.local; + var result = [ local.name ]; + var exported = expr.exported; + if (exported && exported.name !== local.name) { + result.push(noEmptySpace() + 'as' + noEmptySpace() + generateIdentifier(exported)); + } + return result; + }, + + Literal: function (expr, precedence, flags) { + var raw; + if (expr.hasOwnProperty('raw') && parse && extra.raw) { + try { + raw = parse(expr.raw).body[0].expression; + if (raw.type === Syntax.Literal) { + if (raw.value === expr.value) { + return expr.raw; + } + } + } catch (e) { + // not use raw property + } + } + + if (expr.regex) { + return '/' + expr.regex.pattern + '/' + expr.regex.flags; + } + + if (typeof expr.value === 'bigint') { + return expr.value.toString() + 'n'; + } + + // `expr.value` can be null if `expr.bigint` exists. We need to check + // `expr.bigint` first. + if (expr.bigint) { + return expr.bigint + 'n'; + } + + if (expr.value === null) { + return 'null'; + } + + if (typeof expr.value === 'string') { + return escapeString(expr.value); + } + + if (typeof expr.value === 'number') { + return generateNumber(expr.value); + } + + if (typeof expr.value === 'boolean') { + return expr.value ? 'true' : 'false'; + } + + return generateRegExp(expr.value); + }, + + GeneratorExpression: function (expr, precedence, flags) { + return this.ComprehensionExpression(expr, precedence, flags); + }, + + ComprehensionExpression: function (expr, precedence, flags) { + // GeneratorExpression should be parenthesized with (...), ComprehensionExpression with [...] + // Due to https://bugzilla.mozilla.org/show_bug.cgi?id=883468 position of expr.body can differ in Spidermonkey and ES6 + + var result, i, iz, fragment, that = this; + result = (expr.type === Syntax.GeneratorExpression) ? ['('] : ['[']; + + if (extra.moz.comprehensionExpressionStartsWithAssignment) { + fragment = this.generateExpression(expr.body, Precedence.Assignment, E_TTT); + result.push(fragment); + } + + if (expr.blocks) { + withIndent(function () { + for (i = 0, iz = expr.blocks.length; i < iz; ++i) { + fragment = that.generateExpression(expr.blocks[i], Precedence.Sequence, E_TTT); + if (i > 0 || extra.moz.comprehensionExpressionStartsWithAssignment) { + result = join(result, fragment); + } else { + result.push(fragment); + } + } + }); + } + + if (expr.filter) { + result = join(result, 'if' + space); + fragment = this.generateExpression(expr.filter, Precedence.Sequence, E_TTT); + result = join(result, [ '(', fragment, ')' ]); + } + + if (!extra.moz.comprehensionExpressionStartsWithAssignment) { + fragment = this.generateExpression(expr.body, Precedence.Assignment, E_TTT); + + result = join(result, fragment); + } + + result.push((expr.type === Syntax.GeneratorExpression) ? ')' : ']'); + return result; + }, + + ComprehensionBlock: function (expr, precedence, flags) { + var fragment; + if (expr.left.type === Syntax.VariableDeclaration) { + fragment = [ + expr.left.kind, noEmptySpace(), + this.generateStatement(expr.left.declarations[0], S_FFFF) + ]; + } else { + fragment = this.generateExpression(expr.left, Precedence.Call, E_TTT); + } + + fragment = join(fragment, expr.of ? 'of' : 'in'); + fragment = join(fragment, this.generateExpression(expr.right, Precedence.Sequence, E_TTT)); + + return [ 'for' + space + '(', fragment, ')' ]; + }, + + SpreadElement: function (expr, precedence, flags) { + return [ + '...', + this.generateExpression(expr.argument, Precedence.Assignment, E_TTT) + ]; + }, + + TaggedTemplateExpression: function (expr, precedence, flags) { + var itemFlags = E_TTF; + if (!(flags & F_ALLOW_CALL)) { + itemFlags = E_TFF; + } + var result = [ + this.generateExpression(expr.tag, Precedence.Call, itemFlags), + this.generateExpression(expr.quasi, Precedence.Primary, E_FFT) + ]; + return parenthesize(result, Precedence.TaggedTemplate, precedence); + }, + + TemplateElement: function (expr, precedence, flags) { + // Don't use "cooked". Since tagged template can use raw template + // representation. So if we do so, it breaks the script semantics. + return expr.value.raw; + }, + + TemplateLiteral: function (expr, precedence, flags) { + var result, i, iz; + result = [ '`' ]; + for (i = 0, iz = expr.quasis.length; i < iz; ++i) { + result.push(this.generateExpression(expr.quasis[i], Precedence.Primary, E_TTT)); + if (i + 1 < iz) { + result.push('${' + space); + result.push(this.generateExpression(expr.expressions[i], Precedence.Sequence, E_TTT)); + result.push(space + '}'); + } + } + result.push('`'); + return result; + }, + + ModuleSpecifier: function (expr, precedence, flags) { + return this.Literal(expr, precedence, flags); + }, + + ImportExpression: function(expr, precedence, flag) { + return parenthesize([ + 'import(', + this.generateExpression(expr.source, Precedence.Assignment, E_TTT), + ')' + ], Precedence.Call, precedence); + } + }; + + merge(CodeGenerator.prototype, CodeGenerator.Expression); + + CodeGenerator.prototype.generateExpression = function (expr, precedence, flags) { + var result, type; + + type = expr.type || Syntax.Property; + + if (extra.verbatim && expr.hasOwnProperty(extra.verbatim)) { + return generateVerbatim(expr, precedence); + } + + result = this[type](expr, precedence, flags); + + + if (extra.comment) { + result = addComments(expr, result); + } + return toSourceNodeWhenNeeded(result, expr); + }; + + CodeGenerator.prototype.generateStatement = function (stmt, flags) { + var result, + fragment; + + result = this[stmt.type](stmt, flags); + + // Attach comments + + if (extra.comment) { + result = addComments(stmt, result); + } + + fragment = toSourceNodeWhenNeeded(result).toString(); + if (stmt.type === Syntax.Program && !safeConcatenation && newline === '' && fragment.charAt(fragment.length - 1) === '\n') { + result = sourceMap ? toSourceNodeWhenNeeded(result).replaceRight(/\s+$/, '') : fragment.replace(/\s+$/, ''); + } + + return toSourceNodeWhenNeeded(result, stmt); + }; + + function generateInternal(node) { + var codegen; + + codegen = new CodeGenerator(); + if (isStatement(node)) { + return codegen.generateStatement(node, S_TFFF); + } + + if (isExpression(node)) { + return codegen.generateExpression(node, Precedence.Sequence, E_TTT); + } + + throw new Error('Unknown node type: ' + node.type); + } + + function generate(node, options) { + var defaultOptions = getDefaultOptions(), result, pair; + + if (options != null) { + // Obsolete options + // + // `options.indent` + // `options.base` + // + // Instead of them, we can use `option.format.indent`. + if (typeof options.indent === 'string') { + defaultOptions.format.indent.style = options.indent; + } + if (typeof options.base === 'number') { + defaultOptions.format.indent.base = options.base; + } + options = updateDeeply(defaultOptions, options); + indent = options.format.indent.style; + if (typeof options.base === 'string') { + base = options.base; + } else { + base = stringRepeat(indent, options.format.indent.base); + } + } else { + options = defaultOptions; + indent = options.format.indent.style; + base = stringRepeat(indent, options.format.indent.base); + } + json = options.format.json; + renumber = options.format.renumber; + hexadecimal = json ? false : options.format.hexadecimal; + quotes = json ? 'double' : options.format.quotes; + escapeless = options.format.escapeless; + newline = options.format.newline; + space = options.format.space; + if (options.format.compact) { + newline = space = indent = base = ''; + } + parentheses = options.format.parentheses; + semicolons = options.format.semicolons; + safeConcatenation = options.format.safeConcatenation; + directive = options.directive; + parse = json ? null : options.parse; + sourceMap = options.sourceMap; + sourceCode = options.sourceCode; + preserveBlankLines = options.format.preserveBlankLines && sourceCode !== null; + extra = options; + + if (sourceMap) { + if (!exports.browser) { + // We assume environment is node.js + // And prevent from including source-map by browserify + SourceNode = require('source-map').SourceNode; + } else { + SourceNode = global.sourceMap.SourceNode; + } + } + + result = generateInternal(node); + + if (!sourceMap) { + pair = {code: result.toString(), map: null}; + return options.sourceMapWithCode ? pair : pair.code; + } + + + pair = result.toStringWithSourceMap({ + file: options.file, + sourceRoot: options.sourceMapRoot + }); + + if (options.sourceContent) { + pair.map.setSourceContent(options.sourceMap, + options.sourceContent); + } + + if (options.sourceMapWithCode) { + return pair; + } + + return pair.map.toString(); + } + + FORMAT_MINIFY = { + indent: { + style: '', + base: 0 + }, + renumber: true, + hexadecimal: true, + quotes: 'auto', + escapeless: true, + compact: true, + parentheses: false, + semicolons: false + }; + + FORMAT_DEFAULTS = getDefaultOptions().format; + + exports.version = require('./package.json').version; + exports.generate = generate; + exports.attachComments = estraverse.attachComments; + exports.Precedence = updateDeeply({}, Precedence); + exports.browser = false; + exports.FORMAT_MINIFY = FORMAT_MINIFY; + exports.FORMAT_DEFAULTS = FORMAT_DEFAULTS; +}()); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/escodegen/package.json b/node_modules/escodegen/package.json new file mode 100644 index 0000000..e76ba1a --- /dev/null +++ b/node_modules/escodegen/package.json @@ -0,0 +1,63 @@ +{ + "name": "escodegen", + "description": "ECMAScript code generator", + "homepage": "http://github.com/estools/escodegen", + "main": "escodegen.js", + "bin": { + "esgenerate": "./bin/esgenerate.js", + "escodegen": "./bin/escodegen.js" + }, + "files": [ + "LICENSE.BSD", + "README.md", + "bin", + "escodegen.js", + "package.json" + ], + "version": "2.1.0", + "engines": { + "node": ">=6.0" + }, + "maintainers": [ + { + "name": "Yusuke Suzuki", + "email": "utatane.tea@gmail.com", + "web": "http://github.com/Constellation" + } + ], + "repository": { + "type": "git", + "url": "http://github.com/estools/escodegen.git" + }, + "dependencies": { + "estraverse": "^5.2.0", + "esutils": "^2.0.2", + "esprima": "^4.0.1" + }, + "optionalDependencies": { + "source-map": "~0.6.1" + }, + "devDependencies": { + "acorn": "^8.0.4", + "bluebird": "^3.4.7", + "bower-registry-client": "^1.0.0", + "chai": "^4.2.0", + "chai-exclude": "^2.0.2", + "commonjs-everywhere": "^0.9.7", + "gulp": "^4.0.2", + "gulp-eslint": "^6.0.0", + "gulp-mocha": "^7.0.2", + "minimist": "^1.2.5", + "optionator": "^0.9.1", + "semver": "^7.3.4" + }, + "license": "BSD-2-Clause", + "scripts": { + "test": "gulp travis", + "unit-test": "gulp test", + "lint": "gulp lint", + "release": "node tools/release.js", + "build-min": "./node_modules/.bin/cjsify -ma path: tools/entry-point.js > escodegen.browser.min.js", + "build": "./node_modules/.bin/cjsify -a path: tools/entry-point.js > escodegen.browser.js" + } +} diff --git a/node_modules/esprima/ChangeLog b/node_modules/esprima/ChangeLog new file mode 100644 index 0000000..fafe1c9 --- /dev/null +++ b/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/node_modules/esprima/LICENSE.BSD b/node_modules/esprima/LICENSE.BSD new file mode 100644 index 0000000..7a55160 --- /dev/null +++ b/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/node_modules/esprima/README.md b/node_modules/esprima/README.md new file mode 100644 index 0000000..8fb25e6 --- /dev/null +++ b/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/node_modules/esprima/bin/esparse.js b/node_modules/esprima/bin/esparse.js new file mode 100755 index 0000000..45d05fb --- /dev/null +++ b/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/node_modules/esprima/bin/esvalidate.js b/node_modules/esprima/bin/esvalidate.js new file mode 100755 index 0000000..d49a7e4 --- /dev/null +++ b/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/node_modules/esprima/dist/esprima.js b/node_modules/esprima/dist/esprima.js new file mode 100644 index 0000000..2af3eee --- /dev/null +++ b/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\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u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4\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-\u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\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\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; // `|$))/,_e=k("^ {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",U).replace("tag",v).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),ae=k(j).replace("hr",C).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[.)])[ \\t]").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",v).getRegex(),Me=k(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",ae).getRegex(),K={blockquote:Me,code:Oe,def:$e,fences:we,heading:ye,hr:C,html:_e,lheading:oe,list:Le,newline:Te,paragraph:ae,table:_,text:Se},re=k("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",C).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",v).getRegex(),ze={...K,lheading:Pe,table:re,paragraph:k(j).replace("hr",C).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",re).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",v).getRegex()},Ee={...K,html:k(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",U).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:_,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:k(j).replace("hr",C).replace("heading",` *#{1,6} *[^ +]`).replace("lheading",oe).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Ie=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Ae=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,le=/^( {2,}|\\)\n(?!\s*$)/,Ce=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\`+)[^`]+\k(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Re?"(?`+)[^`]+\k(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),pe=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,He=k(pe,"u").replace(/punct/g,E).getRegex(),Ze=k(pe,"u").replace(/punct/g,ue).getRegex(),ce="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Ge=k(ce,"gu").replace(/notPunctSpace/g,W).replace(/punctSpace/g,H).replace(/punct/g,E).getRegex(),Ne=k(ce,"gu").replace(/notPunctSpace/g,qe).replace(/punctSpace/g,De).replace(/punct/g,ue).getRegex(),Qe=k("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,W).replace(/punctSpace/g,H).replace(/punct/g,E).getRegex(),je=k(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,E).getRegex(),Fe="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Ue=k(Fe,"gu").replace(/notPunctSpace/g,W).replace(/punctSpace/g,H).replace(/punct/g,E).getRegex(),Ke=k(/\\(punct)/,"gu").replace(/punct/g,E).getRegex(),We=k(/^<(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(),Xe=k(U).replace("(?:-->|$)","-->").getRegex(),Je=k("^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment",Xe).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),q=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,Ve=k(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",q).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),he=k(/^!?\[(label)\]\[(ref)\]/).replace("label",q).replace("ref",F).getRegex(),ke=k(/^!?\[(ref)\](?:\[\])?/).replace("ref",F).getRegex(),Ye=k("reflink|nolink(?!\\()","g").replace("reflink",he).replace("nolink",ke).getRegex(),se=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,X={_backpedal:_,anyPunctuation:Ke,autolink:We,blockSkip:ve,br:le,code:Ae,del:_,delLDelim:_,delRDelim:_,emStrongLDelim:He,emStrongRDelimAst:Ge,emStrongRDelimUnd:Qe,escape:Ie,link:Ve,nolink:ke,punctuation:Be,reflink:he,reflinkSearch:Ye,tag:Je,text:Ce,url:_},et={...X,link:k(/^!?\[(label)\]\((.*?)\)/).replace("label",q).getRegex(),reflink:k(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",q).getRegex()},N={...X,emStrongRDelimAst:Ne,emStrongLDelim:Ze,delLDelim:je,delRDelim:Ue,url:k(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",se).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\S]|[^\s~\\]))\1(?=[^~]|$)/,text:k(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\":">",'"':""","'":"'"},de=u=>nt[u];function O(u,e){if(e){if(m.escapeTest.test(u))return u.replace(m.escapeReplace,de)}else if(m.escapeTestNoEncode.test(u))return u.replace(m.escapeReplaceNoEncode,de);return u}function J(u){try{u=encodeURI(u).replace(m.percentDecode,"%")}catch{return null}return u}function V(u,e){let t=u.replace(m.findPipe,(i,s,a)=>{let o=!1,l=s;for(;--l>=0&&a[l]==="\\";)o=!o;return o?"|":" |"}),n=t.split(m.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length=0&&!e[t].trim();)t--;return e.length-t<=2?u:e.slice(0,t+1).join(` +`)}function ge(u,e){if(u.indexOf(e[1])===-1)return-1;let t=0;for(let n=0;n0?-2:-1}function fe(u,e=0){let t=e,n="";for(let r of u)if(r===" "){let i=4-t%4;n+=" ".repeat(i),t+=i}else n+=r,t++;return n}function me(u,e,t,n,r){let i=e.href,s=e.title||null,a=u[1].replace(r.other.outputLinkReplace,"$1");n.state.inLink=!0;let o={type:u[0].charAt(0)==="!"?"image":"link",raw:t,href:i,title:s,text:a,tokens:n.inlineTokens(a)};return n.state.inLink=!1,o}function rt(u,e,t){let n=u.match(t.other.indentCodeCompensation);if(n===null)return e;let r=n[1];return e.split(` +`).map(i=>{let s=i.match(t.other.beginningSpace);if(s===null)return i;let[a]=s;return a.length>=r.length?i.slice(r.length):i}).join(` +`)}var w=class{options;rules;lexer;constructor(e){this.options=e||T}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=this.options.pedantic?t[0]:Y(t[0]),r=n.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:n,codeBlockStyle:"indented",text:r}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],r=rt(n,t[3]||"",this.rules);return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:r}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.rules.other.endingHash.test(n)){let r=$(n,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(n=r.trim())}return{type:"heading",raw:$(t[0],` +`),depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:$(t[0],` +`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=$(t[0],` +`).split(` +`),r="",i="",s=[];for(;n.length>0;){let a=!1,o=[],l;for(l=0;l1,i={type:"list",raw:"",ordered:r,start:r?+n.slice(0,-1):"",loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:"[*+-]");let s=this.rules.other.listItemRegex(n),a=!1;for(;e;){let l=!1,p="",c="";if(!(t=s.exec(e))||this.rules.block.hr.test(e))break;p=t[0],e=e.substring(p.length);let d=fe(t[2].split(` +`,1)[0],t[1].length),h=e.split(` +`,1)[0],R=!d.trim(),f=0;if(this.options.pedantic?(f=2,c=d.trimStart()):R?f=t[1].length+1:(f=d.search(this.rules.other.nonSpaceChar),f=f>4?1:f,c=d.slice(f),f+=t[1].length),R&&this.rules.other.blankLine.test(h)&&(p+=h+` +`,e=e.substring(h.length+1),l=!0),!l){let S=this.rules.other.nextBulletRegex(f),ee=this.rules.other.hrRegex(f),te=this.rules.other.fencesBeginRegex(f),ne=this.rules.other.headingBeginRegex(f),xe=this.rules.other.htmlBeginRegex(f),be=this.rules.other.blockquoteBeginRegex(f);for(;e;){let Z=e.split(` +`,1)[0],A;if(h=Z,this.options.pedantic?(h=h.replace(this.rules.other.listReplaceNesting," "),A=h):A=h.replace(this.rules.other.tabCharGlobal," "),te.test(h)||ne.test(h)||xe.test(h)||be.test(h)||S.test(h)||ee.test(h))break;if(A.search(this.rules.other.nonSpaceChar)>=f||!h.trim())c+=` +`+A.slice(f);else{if(R||d.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||te.test(d)||ne.test(d)||ee.test(d))break;c+=` +`+h}R=!h.trim(),p+=Z+` +`,e=e.substring(Z.length+1),d=A.slice(f)}}i.loose||(a?i.loose=!0:this.rules.other.doubleBlankLine.test(p)&&(a=!0)),i.items.push({type:"list_item",raw:p,task:!!this.options.gfm&&this.rules.other.listIsTask.test(c),loose:!1,text:c,tokens:[]}),i.raw+=p}let o=i.items.at(-1);if(o)o.raw=o.raw.trimEnd(),o.text=o.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let l of i.items){if(this.lexer.state.top=!1,l.tokens=this.lexer.blockTokens(l.text,[]),l.task){if(l.text=l.text.replace(this.rules.other.listReplaceTask,""),l.tokens[0]?.type==="text"||l.tokens[0]?.type==="paragraph"){l.tokens[0].raw=l.tokens[0].raw.replace(this.rules.other.listReplaceTask,""),l.tokens[0].text=l.tokens[0].text.replace(this.rules.other.listReplaceTask,"");for(let c=this.lexer.inlineQueue.length-1;c>=0;c--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[c].src)){this.lexer.inlineQueue[c].src=this.lexer.inlineQueue[c].src.replace(this.rules.other.listReplaceTask,"");break}}let p=this.rules.other.listTaskCheckbox.exec(l.raw);if(p){let c={type:"checkbox",raw:p[0]+" ",checked:p[0]!=="[ ]"};l.checked=c.checked,i.loose?l.tokens[0]&&["paragraph","text"].includes(l.tokens[0].type)&&"tokens"in l.tokens[0]&&l.tokens[0].tokens?(l.tokens[0].raw=c.raw+l.tokens[0].raw,l.tokens[0].text=c.raw+l.tokens[0].text,l.tokens[0].tokens.unshift(c)):l.tokens.unshift({type:"paragraph",raw:c.raw,text:c.raw,tokens:[c]}):l.tokens.unshift(c)}}if(!i.loose){let p=l.tokens.filter(d=>d.type==="space"),c=p.length>0&&p.some(d=>this.rules.other.anyLine.test(d.raw));i.loose=c}}if(i.loose)for(let l of i.items){l.loose=!0;for(let p of l.tokens)p.type==="text"&&(p.type="paragraph")}return i}}html(e){let t=this.rules.block.html.exec(e);if(t){let n=Y(t[0]);return{type:"html",block:!0,raw:n,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:n}}}def(e){let t=this.rules.block.def.exec(e);if(t){let n=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),r=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",i=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:n,raw:$(t[0],` +`),href:r,title:i}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=V(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(` +`):[],s={type:"table",raw:$(t[0],` +`),header:[],align:[],rows:[]};if(n.length===r.length){for(let a of r)this.rules.other.tableAlignRight.test(a)?s.align.push("right"):this.rules.other.tableAlignCenter.test(a)?s.align.push("center"):this.rules.other.tableAlignLeft.test(a)?s.align.push("left"):s.align.push(null);for(let a=0;a({text:o,tokens:this.lexer.inline(o),header:!1,align:s.align[l]})));return s}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let n=t[1].trim();return{type:"heading",raw:$(t[0],` +`),depth:t[2].charAt(0)==="="?1:2,text:n,tokens:this.lexer.inline(n)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===` +`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let 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){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.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){let t=this.rules.inline.link.exec(e);if(t){let n=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let s=$(n.slice(0,-1),"\\");if((n.length-s.length)%2===0)return}else{let s=ge(t[2],"()");if(s===-2)return;if(s>-1){let o=(t[0].indexOf("!")===0?5:4)+t[1].length+s;t[2]=t[2].substring(0,s),t[0]=t[0].substring(0,o).trim(),t[3]=""}}let r=t[2],i="";if(this.options.pedantic){let s=this.rules.other.pedanticHrefTitle.exec(r);s&&(r=s[1],i=s[3])}else i=t[3]?t[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?r=r.slice(1):r=r.slice(1,-1)),me(t,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:i&&i.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let r=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),i=t[r.toLowerCase()];if(!i){let s=n[0].charAt(0);return{type:"text",raw:s,text:s}}return me(n,i,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let r=this.rules.inline.emStrongLDelim.exec(e);if(!r||!r[1]&&!r[2]&&!r[3]&&!r[4]||r[4]&&n.match(this.rules.other.unicodeAlphaNumeric))return;if(!(r[1]||r[3]||"")||!n||this.rules.inline.punctuation.exec(n)){let s=[...r[0]].length-1,a,o,l=s,p=0,c=r[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,t=t.slice(-1*e.length+s);(r=c.exec(t))!==null;){if(a=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!a)continue;if(o=[...a].length,r[3]||r[4]){l+=o;continue}else if((r[5]||r[6])&&s%3&&!((s+o)%3)){p+=o;continue}if(l-=o,l>0)continue;o=Math.min(o,o+l+p);let d=[...r[0]][0].length,h=e.slice(0,s+r.index+d+o);if(Math.min(s,o)%2){let f=h.slice(1,-1);return{type:"em",raw:h,text:f,tokens:this.lexer.inlineTokens(f)}}let R=h.slice(2,-2);return{type:"strong",raw:h,text:R,tokens:this.lexer.inlineTokens(R)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),r=this.rules.other.nonSpaceChar.test(n),i=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return r&&i&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,n=""){let r=this.rules.inline.delLDelim.exec(e);if(!r)return;if(!(r[1]||"")||!n||this.rules.inline.punctuation.exec(n)){let s=[...r[0]].length-1,a,o,l=s,p=this.rules.inline.delRDelim;for(p.lastIndex=0,t=t.slice(-1*e.length+s);(r=p.exec(t))!==null;){if(a=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!a||(o=[...a].length,o!==s))continue;if(r[3]||r[4]){l+=o;continue}if(l-=o,l>0)continue;o=Math.min(o,o+l);let c=[...r[0]][0].length,d=e.slice(0,s+r.index+c+o),h=d.slice(s,-s);return{type:"del",raw:d,text:h,tokens:this.lexer.inlineTokens(h)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,r;return t[2]==="@"?(n=t[1],r="mailto:"+n):(n=t[1],r=n),{type:"link",raw:t[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let n,r;if(t[2]==="@")n=t[0],r="mailto:"+n;else{let i;do i=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(i!==t[0]);n=t[0],t[1]==="www."?r="http://"+t[0]:r=t[0]}return{type:"link",raw:t[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:n}}}};var x=class u{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||T,this.options.tokenizer=this.options.tokenizer||new w,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={other:m,block:B.normal,inline:I.normal};this.options.pedantic?(t.block=B.pedantic,t.inline=I.pedantic):this.options.gfm&&(t.block=B.gfm,this.options.breaks?t.inline=I.breaks:t.inline=I.gfm),this.tokenizer.rules=t}static get rules(){return{block:B,inline:I}}static lex(e,t){return new u(t).lex(e)}static lexInline(e,t){return new u(t).inlineTokens(e)}lex(e){e=e.replace(m.carriageReturn,` +`),this.blockTokens(e,this.tokens);for(let t=0;t(r=s.call({lexer:this},e,t))?(e=e.substring(r.raw.length),t.push(r),!0):!1))continue;if(r=this.tokenizer.space(e)){e=e.substring(r.raw.length);let s=t.at(-1);r.raw.length===1&&s!==void 0?s.raw+=` +`:t.push(r);continue}if(r=this.tokenizer.code(e)){e=e.substring(r.raw.length);let s=t.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(` +`)?"":` +`)+r.raw,s.text+=` +`+r.text,this.inlineQueue.at(-1).src=s.text):t.push(r);continue}if(r=this.tokenizer.fences(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.heading(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.hr(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.blockquote(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.list(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.html(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.def(e)){e=e.substring(r.raw.length);let s=t.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(` +`)?"":` +`)+r.raw,s.text+=` +`+r.raw,this.inlineQueue.at(-1).src=s.text):this.tokens.links[r.tag]||(this.tokens.links[r.tag]={href:r.href,title:r.title},t.push(r));continue}if(r=this.tokenizer.table(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.lheading(e)){e=e.substring(r.raw.length),t.push(r);continue}let i=e;if(this.options.extensions?.startBlock){let s=1/0,a=e.slice(1),o;this.options.extensions.startBlock.forEach(l=>{o=l.call({lexer:this},a),typeof o=="number"&&o>=0&&(s=Math.min(s,o))}),s<1/0&&s>=0&&(i=e.substring(0,s+1))}if(this.state.top&&(r=this.tokenizer.paragraph(i))){let s=t.at(-1);n&&s?.type==="paragraph"?(s.raw+=(s.raw.endsWith(` +`)?"":` +`)+r.raw,s.text+=` +`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):t.push(r),n=i.length!==e.length,e=e.substring(r.raw.length);continue}if(r=this.tokenizer.text(e)){e=e.substring(r.raw.length);let s=t.at(-1);s?.type==="text"?(s.raw+=(s.raw.endsWith(` +`)?"":` +`)+r.raw,s.text+=` +`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):t.push(r);continue}if(e){let s="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(s);break}else throw new Error(s)}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){this.tokenizer.lexer=this;let n=e,r=null;if(this.tokens.links){let o=Object.keys(this.tokens.links);if(o.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(n))!==null;)o.includes(r[0].slice(r[0].lastIndexOf("[")+1,-1))&&(n=n.slice(0,r.index)+"["+"a".repeat(r[0].length-2)+"]"+n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(n))!==null;)n=n.slice(0,r.index)+"++"+n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let i;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(n))!==null;)i=r[2]?r[2].length:0,n=n.slice(0,r.index+i)+"["+"a".repeat(r[0].length-i-2)+"]"+n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let s=!1,a="";for(;e;){s||(a=""),s=!1;let o;if(this.options.extensions?.inline?.some(p=>(o=p.call({lexer:this},e,t))?(e=e.substring(o.raw.length),t.push(o),!0):!1))continue;if(o=this.tokenizer.escape(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.tag(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.link(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(o.raw.length);let p=t.at(-1);o.type==="text"&&p?.type==="text"?(p.raw+=o.raw,p.text+=o.text):t.push(o);continue}if(o=this.tokenizer.emStrong(e,n,a)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.codespan(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.br(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.del(e,n,a)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.autolink(e)){e=e.substring(o.raw.length),t.push(o);continue}if(!this.state.inLink&&(o=this.tokenizer.url(e))){e=e.substring(o.raw.length),t.push(o);continue}let l=e;if(this.options.extensions?.startInline){let p=1/0,c=e.slice(1),d;this.options.extensions.startInline.forEach(h=>{d=h.call({lexer:this},c),typeof d=="number"&&d>=0&&(p=Math.min(p,d))}),p<1/0&&p>=0&&(l=e.substring(0,p+1))}if(o=this.tokenizer.inlineText(l)){e=e.substring(o.raw.length),o.raw.slice(-1)!=="_"&&(a=o.raw.slice(-1)),s=!0;let p=t.at(-1);p?.type==="text"?(p.raw+=o.raw,p.text+=o.text):t.push(o);continue}if(e){let p="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(p);break}else throw new Error(p)}}return t}};var y=class{options;parser;constructor(e){this.options=e||T}space(e){return""}code({text:e,lang:t,escaped:n}){let r=(t||"").match(m.notSpaceStart)?.[0],i=e.replace(m.endingNewline,"")+` +`;return r?'
    '+(n?i:O(i,!0))+`
    +`:"
    "+(n?i:O(i,!0))+`
    +`}blockquote({tokens:e}){return`
    +${this.parser.parse(e)}
    +`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`${this.parser.parseInline(e)} +`}hr(e){return`
    +`}list(e){let t=e.ordered,n=e.start,r="";for(let a=0;a +`+r+" +`}listitem(e){return`
  • ${this.parser.parse(e.tokens)}
  • +`}checkbox({checked:e}){return" '}paragraph({tokens:e}){return`

    ${this.parser.parseInline(e)}

    +`}table(e){let t="",n="";for(let i=0;i${r}`),` + +`+t+` +`+r+`
    +`}tablerow({text:e}){return` +${e} +`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+` +`}strong({tokens:e}){return`${this.parser.parseInline(e)}`}em({tokens:e}){return`${this.parser.parseInline(e)}`}codespan({text:e}){return`${O(e,!0)}`}br(e){return"
    "}del({tokens:e}){return`${this.parser.parseInline(e)}`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=J(e);if(i===null)return r;e=i;let s='
    ",s}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=J(e);if(i===null)return O(n);e=i;let s=`${O(n)}{let a=i[s].flat(1/0);n=n.concat(this.walkTokens(a,t))}):i.tokens&&(n=n.concat(this.walkTokens(i.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let r={...n};if(r.async=this.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(i=>{if(!i.name)throw new Error("extension name required");if("renderer"in i){let s=t.renderers[i.name];s?t.renderers[i.name]=function(...a){let o=i.renderer.apply(this,a);return o===!1&&(o=s.apply(this,a)),o}:t.renderers[i.name]=i.renderer}if("tokenizer"in i){if(!i.level||i.level!=="block"&&i.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let s=t[i.level];s?s.unshift(i.tokenizer):t[i.level]=[i.tokenizer],i.start&&(i.level==="block"?t.startBlock?t.startBlock.push(i.start):t.startBlock=[i.start]:i.level==="inline"&&(t.startInline?t.startInline.push(i.start):t.startInline=[i.start]))}"childTokens"in i&&i.childTokens&&(t.childTokens[i.name]=i.childTokens)}),r.extensions=t),n.renderer){let i=this.defaults.renderer||new y(this.defaults);for(let s in n.renderer){if(!(s in i))throw new Error(`renderer '${s}' does not exist`);if(["options","parser"].includes(s))continue;let a=s,o=n.renderer[a],l=i[a];i[a]=(...p)=>{let c=o.apply(i,p);return c===!1&&(c=l.apply(i,p)),c||""}}r.renderer=i}if(n.tokenizer){let i=this.defaults.tokenizer||new w(this.defaults);for(let s in n.tokenizer){if(!(s in i))throw new Error(`tokenizer '${s}' does not exist`);if(["options","rules","lexer"].includes(s))continue;let a=s,o=n.tokenizer[a],l=i[a];i[a]=(...p)=>{let c=o.apply(i,p);return c===!1&&(c=l.apply(i,p)),c}}r.tokenizer=i}if(n.hooks){let i=this.defaults.hooks||new P;for(let s in n.hooks){if(!(s in i))throw new Error(`hook '${s}' does not exist`);if(["options","block"].includes(s))continue;let a=s,o=n.hooks[a],l=i[a];P.passThroughHooks.has(s)?i[a]=p=>{if(this.defaults.async&&P.passThroughHooksRespectAsync.has(s))return(async()=>{let d=await o.call(i,p);return l.call(i,d)})();let c=o.call(i,p);return l.call(i,c)}:i[a]=(...p)=>{if(this.defaults.async)return(async()=>{let d=await o.apply(i,p);return d===!1&&(d=await l.apply(i,p)),d})();let c=o.apply(i,p);return c===!1&&(c=l.apply(i,p)),c}}r.hooks=i}if(n.walkTokens){let i=this.defaults.walkTokens,s=n.walkTokens;r.walkTokens=function(a){let o=[];return o.push(s.call(this,a)),i&&(o=o.concat(i.call(this,a))),o}}this.defaults={...this.defaults,...r}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return x.lex(e,t??this.defaults)}parser(e,t){return b.parse(e,t??this.defaults)}parseMarkdown(e){return(n,r)=>{let i={...r},s={...this.defaults,...i},a=this.onError(!!s.silent,!!s.async);if(this.defaults.async===!0&&i.async===!1)return a(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof n>"u"||n===null)return a(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return a(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(s.hooks&&(s.hooks.options=s,s.hooks.block=e),s.async)return(async()=>{let o=s.hooks?await s.hooks.preprocess(n):n,p=await(s.hooks?await s.hooks.provideLexer(e):e?x.lex:x.lexInline)(o,s),c=s.hooks?await s.hooks.processAllTokens(p):p;s.walkTokens&&await Promise.all(this.walkTokens(c,s.walkTokens));let h=await(s.hooks?await s.hooks.provideParser(e):e?b.parse:b.parseInline)(c,s);return s.hooks?await s.hooks.postprocess(h):h})().catch(a);try{s.hooks&&(n=s.hooks.preprocess(n));let l=(s.hooks?s.hooks.provideLexer(e):e?x.lex:x.lexInline)(n,s);s.hooks&&(l=s.hooks.processAllTokens(l)),s.walkTokens&&this.walkTokens(l,s.walkTokens);let c=(s.hooks?s.hooks.provideParser(e):e?b.parse:b.parseInline)(l,s);return s.hooks&&(c=s.hooks.postprocess(c)),c}catch(o){return a(o)}}}onError(e,t){return n=>{if(n.message+=` +Please report this to https://github.com/markedjs/marked.`,e){let r="

    An error occurred:

    "+O(n.message+"",!0)+"
    ";return t?Promise.resolve(r):r}if(t)return Promise.reject(n);throw n}}};var M=new D;function g(u,e){return M.parse(u,e)}g.options=g.setOptions=function(u){return M.setOptions(u),g.defaults=M.defaults,G(g.defaults),g};g.getDefaults=z;g.defaults=T;g.use=function(...u){return M.use(...u),g.defaults=M.defaults,G(g.defaults),g};g.walkTokens=function(u,e){return M.walkTokens(u,e)};g.parseInline=M.parseInline;g.Parser=b;g.parser=b.parse;g.Renderer=y;g.TextRenderer=L;g.Lexer=x;g.lexer=x.lex;g.Tokenizer=w;g.Hooks=P;g.parse=g;var jt=g.options,Ft=g.setOptions,Ut=g.use,Kt=g.walkTokens,Wt=g.parseInline,Xt=g,Jt=b.parse,Vt=x.lex;export{P as Hooks,x as Lexer,D as Marked,b as Parser,y as Renderer,L as TextRenderer,w as Tokenizer,T as defaults,z as getDefaults,Vt as lexer,g as marked,jt as options,Xt as parse,Wt as parseInline,Jt as parser,Ft as setOptions,Ut as use,Kt as walkTokens}; +//# sourceMappingURL=marked.esm.js.map diff --git a/node_modules/marked/lib/marked.esm.js.map b/node_modules/marked/lib/marked.esm.js.map new file mode 100644 index 0000000..23da301 --- /dev/null +++ b/node_modules/marked/lib/marked.esm.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../src/defaults.ts", "../src/rules.ts", "../src/helpers.ts", "../src/Tokenizer.ts", "../src/Lexer.ts", "../src/Renderer.ts", "../src/TextRenderer.ts", "../src/Parser.ts", "../src/Hooks.ts", "../src/Instance.ts", "../src/marked.ts"], + "sourcesContent": ["import type { MarkedOptions } from './MarkedOptions.ts';\n\n/**\n * Gets the original marked default options.\n */\nexport function _getDefaults(): MarkedOptions {\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}\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport let _defaults: MarkedOptions = _getDefaults();\n\nexport function changeDefaults(newDefaults: MarkedOptions) {\n _defaults = newDefaults;\n}\n", "const noopTest = { exec: () => null } as unknown as RegExp;\n\nfunction edit(regex: string | RegExp, opt = '') {\n let source = typeof regex === 'string' ? regex : regex.source;\n const obj = {\n replace: (name: string | RegExp, val: string | RegExp) => {\n let valSource = typeof val === 'string' ? val : val.source;\n valSource = valSource.replace(other.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}\n\nconst supportsLookbehind = (() => {\ntry {\n // eslint-disable-next-line prefer-regex-literals\n return !!new RegExp('(?<=1)(?/,\n blockquoteSetextReplace: /\\n {0,3}((?:=+|-+) *)(?=\\n|$)/g,\n blockquoteSetextReplace2: /^ {0,3}>[ \\t]?/gm,\n listReplaceNesting: /^ {1,4}(?=( {4})*[^ ])/g,\n listIsTask: /^\\[[ xX]\\] +\\S/,\n listReplaceTask: /^\\[[ xX]\\] +/,\n listTaskCheckbox: /\\[[ xX]\\]/,\n anyLine: /\\n.*\\n/,\n hrefBrackets: /^<(.*)>$/,\n tableDelimiter: /[:|]/,\n tableAlignChars: /^\\||\\| *$/g,\n tableRowBlankLine: /\\n[ \\t]*$/,\n tableAlignRight: /^ *-+: *$/,\n tableAlignCenter: /^ *:-+: *$/,\n tableAlignLeft: /^ *:-+ *$/,\n startATag: /^
    /i,\n startPreScriptTag: /^<(pre|code|kbd|script)(\\s|>)/i,\n endPreScriptTag: /^<\\/(pre|code|kbd|script)(\\s|>)/i,\n startAngleBracket: /^$/,\n pedanticHrefTitle: /^([^'\"]*[^\\s])\\s+(['\"])(.*)\\2/,\n unicodeAlphaNumeric: /[\\p{L}\\p{N}]/u,\n escapeTest: /[&<>\"']/,\n escapeReplace: /[&<>\"']/g,\n escapeTestNoEncode: /[<>\"']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/,\n escapeReplaceNoEncode: /[<>\"']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/g,\n caret: /(^|[^\\[])\\^/g,\n percentDecode: /%25/g,\n findPipe: /\\|/g,\n splitPipe: / \\|/,\n slashPipe: /\\\\\\|/g,\n carriageReturn: /\\r\\n|\\r/g,\n spaceLine: /^ +$/gm,\n notSpaceStart: /^\\S*/,\n endingNewline: /\\n$/,\n listItemRegex: (bull: string) => new RegExp(`^( {0,3}${bull})((?:[\\t ][^\\\\n]*)?(?:\\\\n|$))`),\n nextBulletRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\\\d{1,9}[.)])((?:[ \\t][^\\\\n]*)?(?:\\\\n|$))`),\n hrRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\\\* *){3,})(?:\\\\n+|$)`),\n fencesBeginRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\\`\\`\\`|~~~)`),\n headingBeginRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`),\n htmlBeginRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}<(?:[a-z].*>|!--)`, 'i'),\n blockquoteBeginRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}>`),\n};\n\n/**\n * Block-Level Grammar\n */\n\nconst newline = /^(?:[ \\t]*(?:\\n|$))+/;\nconst blockCode = /^((?: {4}| {0,3}\\t)[^\\n]+(?:\\n(?:[ \\t]*(?:\\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 = / {0,3}(?:[*+-]|\\d{1,9}[.)])/;\nconst lheadingCore = /^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\\n(?!\\s*?\\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/;\nconst lheading = edit(lheadingCore)\n .replace(/bull/g, bullet) // lists can interrupt\n .replace(/blockCode/g, /(?: {4}| {0,3}\\t)/) // 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 .replace(/\\|table/g, '') // table not in commonmark\n .getRegex();\nconst lheadingGfm = edit(lheadingCore)\n .replace(/bull/g, bullet) // lists can interrupt\n .replace(/blockCode/g, /(?: {4}| {0,3}\\t)/) // 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 .replace(/table/g, / {0,3}\\|?(?:[:\\- ]*\\|)+[\\:\\- ]*\\n/) // table can interrupt\n .getRegex();\nconst _paragraph = /^([^\\n]+(?:\\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\\n)[^\\n]+)*)/;\nconst blockText = /^[^\\n]+/;\nconst _blockLabel = /(?!\\s*\\])(?:\\\\[\\s\\S]|[^\\[\\]\\\\])+/;\nconst def = edit(/^ {0,3}\\[(label)\\]: *(?:\\n[ \\t]*)?([^<\\s][^\\s]*|<.*?>)(?:(?: +(?:\\n[ \\t]*)?| *\\n[ \\t]*)(title))? *(?:\\n+|$)/)\n .replace('label', _blockLabel)\n .replace('title', /(?:\"(?:\\\\\"?|[^\"\\\\])*\"|'[^'\\n]*(?:\\n[^'\\n]+)*\\n?'|\\([^()]*\\))/)\n .getRegex();\n\nconst list = edit(/^(bull)([ \\t][^\\n]+?)?(?:\\n|$)/)\n .replace(/bull/g, bullet)\n .getRegex();\n\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(\n '^ {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[ \\t]*)+\\\\n|$)' // (6)\n+ '|<(?!script|pre|style|textarea)([a-z][\\\\w-]*)(?:attribute)*? */?>(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n[ \\t]*)+\\\\n|$)' // (7) open tag\n+ '|(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n[ \\t]*)+\\\\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();\n\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[.)])[ \\\\t]') // 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\nconst blockquote = edit(/^( {0,3}> ?(paragraph|[^\\n]*)(?:\\n|$))+/)\n .replace('paragraph', paragraph)\n .getRegex();\n\n/**\n * Normal Block Grammar\n */\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\ntype BlockKeys = keyof typeof blockNormal;\n\n/**\n * GFM Block Grammar\n */\n\nconst gfmTable = edit(\n '^ *([^\\\\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}| {0,3}\\t)[^\\\\n]')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n')\n .replace('list', ' {0,3}(?:[*+-]|1[.)])[ \\\\t]') // 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();\n\nconst blockGfm: Record = {\n ...blockNormal,\n lheading: lheadingGfm,\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[.)])[ \\\\t]') // 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/**\n * Pedantic grammar (original John Gruber's loose markdown specification)\n */\n\nconst blockPedantic: Record = {\n ...blockNormal,\n html: edit(\n '^ *(?: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/**\n * Inline-Level Grammar\n */\n\nconst escape = /^\\\\([!\"#$%&'()*+,\\-./:;<=>?@\\[\\]\\\\^_`{|}~])/;\nconst inlineCode = /^(`+)([^`]|[^`][\\s\\S]*?[^`])\\1(?!`)/;\nconst br = /^( {2,}|\\\\)\\n(?!\\s*$)/;\nconst inlineText = /^(`+|[^`])(?:(?= {2,}\\n)|[\\s\\S]*?(?:(?=[\\\\\nconst blockSkip = edit(/link|precode-code|html/, 'g')\n .replace('link', /\\[(?:[^\\[\\]`]|(?`+)[^`]+\\k(?!`))*?\\]\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)]|\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)])*\\))*\\)/)\n .replace('precode-', supportsLookbehind ? '(?`+)[^`]+\\k(?!`)/)\n .replace('html', /<(?! )[^<>]*?>/)\n .getRegex();\n\nconst emStrongLDelimCore = /^(?:\\*+(?:((?!\\*)punct)|([^\\s*]))?)|^_+(?:((?!_)punct)|([^\\s_]))?/;\n\nconst emStrongLDelim = edit(emStrongLDelimCore, 'u')\n .replace(/punct/g, _punctuation)\n .getRegex();\n\nconst emStrongLDelimGfm = edit(emStrongLDelimCore, 'u')\n .replace(/punct/g, _punctuationGfmStrongEm)\n .getRegex();\n\nconst emStrongRDelimAstCore =\n '^[^_*]*?__[^_*]*?\\\\*[^_*]*?(?=__)' // Skip orphan inside strong\n+ '|[^*]+(?=[^*])' // Consume to delim\n+ '|(?!\\\\*)punct(\\\\*+)(?=[\\\\s]|$)' // (1) #*** can only be a Right Delimiter\n+ '|notPunctSpace(\\\\*+)(?!\\\\*)(?=punctSpace|$)' // (2) a***#, a*** can only be a Right Delimiter\n+ '|(?!\\\\*)punctSpace(\\\\*+)(?=notPunctSpace)' // (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+ '|notPunctSpace(\\\\*+)(?=notPunctSpace)'; // (6) a***a can be either Left or Right Delimiter\n\nconst emStrongRDelimAst = edit(emStrongRDelimAstCore, 'gu')\n .replace(/notPunctSpace/g, _notPunctuationOrSpace)\n .replace(/punctSpace/g, _punctuationOrSpace)\n .replace(/punct/g, _punctuation)\n .getRegex();\n\nconst emStrongRDelimAstGfm = edit(emStrongRDelimAstCore, 'gu')\n .replace(/notPunctSpace/g, _notPunctuationOrSpaceGfmStrongEm)\n .replace(/punctSpace/g, _punctuationOrSpaceGfmStrongEm)\n .replace(/punct/g, _punctuationGfmStrongEm)\n .getRegex();\n\n// (6) Not allowed for _\nconst emStrongRDelimUnd = edit(\n '^[^_*]*?\\\\*\\\\*[^_*]*?_[^_*]*?(?=\\\\*\\\\*)' // Skip orphan inside strong\n+ '|[^_]+(?=[^_])' // Consume to delim\n+ '|(?!_)punct(_+)(?=[\\\\s]|$)' // (1) #___ can only be a Right Delimiter\n+ '|notPunctSpace(_+)(?!_)(?=punctSpace|$)' // (2) a___#, a___ can only be a Right Delimiter\n+ '|(?!_)punctSpace(_+)(?=notPunctSpace)' // (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(/notPunctSpace/g, _notPunctuationOrSpace)\n .replace(/punctSpace/g, _punctuationOrSpace)\n .replace(/punct/g, _punctuation)\n .getRegex();\n\n// Tilde left delimiter for strikethrough (similar to emStrongLDelim for asterisk)\nconst delLDelim = edit(/^~~?(?:((?!~)punct)|[^\\s~])/, 'u')\n .replace(/punct/g, _punctuation)\n .getRegex();\n\n// Tilde delimiter patterns for strikethrough (similar to asterisk)\nconst delRDelimCore =\n '^[^~]+(?=[^~])' // Consume to delim\n+ '|(?!~)punct(~~?)(?=[\\\\s]|$)' // (1) #~~ can only be a Right Delimiter\n+ '|notPunctSpace(~~?)(?!~)(?=punctSpace|$)' // (2) a~~#, a~~ can only be a Right Delimiter\n+ '|(?!~)punctSpace(~~?)(?=notPunctSpace)' // (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+ '|notPunctSpace(~~?)(?=notPunctSpace)'; // (6) a~~a can be either Left or Right Delimiter\n\nconst delRDelim = edit(delRDelimCore, 'gu')\n .replace(/notPunctSpace/g, _notPunctuationOrSpace)\n .replace(/punctSpace/g, _punctuationOrSpace)\n .replace(/punct/g, _punctuation)\n .getRegex();\n\nconst anyPunctuation = edit(/\\\\(punct)/, 'gu')\n .replace(/punct/g, _punctuation)\n .getRegex();\n\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();\n\nconst _inlineComment = edit(_comment).replace('(?:-->|$)', '-->').getRegex();\nconst tag = edit(\n '^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();\n\nconst _inlineLabel = /(?:\\[(?:\\\\[\\s\\S]|[^\\[\\]\\\\])*\\]|\\\\[\\s\\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\\])|[^\\[\\]\\\\`])*?/;\n\nconst link = edit(/^!?\\[(label)\\]\\(\\s*(href)(?:(?:[ \\t]+(?:\\n[ \\t]*)?|\\n[ \\t]*)(title))?\\s*\\)/)\n .replace('label', _inlineLabel)\n .replace('href', /<(?:\\\\.|[^\\n<>\\\\])+>|[^ \\t\\n\\x00-\\x1f]*/)\n .replace('title', /\"(?:\\\\\"?|[^\"\\\\])*\"|'(?:\\\\'?|[^'\\\\])*'|\\((?:\\\\\\)?|[^)\\\\])*\\)/)\n .getRegex();\n\nconst reflink = edit(/^!?\\[(label)\\]\\[(ref)\\]/)\n .replace('label', _inlineLabel)\n .replace('ref', _blockLabel)\n .getRegex();\n\nconst nolink = edit(/^!?\\[(ref)\\](?:\\[\\])?/)\n .replace('ref', _blockLabel)\n .getRegex();\n\nconst reflinkSearch = edit('reflink|nolink(?!\\\\()', 'g')\n .replace('reflink', reflink)\n .replace('nolink', nolink)\n .getRegex();\n\nconst _caseInsensitiveProtocol = /[hH][tT][tT][pP][sS]?|[fF][tT][pP]/;\n\n/**\n * Normal Inline Grammar\n */\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 delLDelim: noopTest,\n delRDelim: 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\ntype InlineKeys = keyof typeof inlineNormal;\n\n/**\n * Pedantic Inline Grammar\n */\n\nconst inlinePedantic: Record = {\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/**\n * GFM Inline Grammar\n */\n\nconst inlineGfm: Record = {\n ...inlineNormal,\n emStrongRDelimAst: emStrongRDelimAstGfm,\n emStrongLDelim: emStrongLDelimGfm,\n delLDelim,\n delRDelim,\n url: edit(/^((?:protocol):\\/\\/|www\\.)(?:[a-zA-Z0-9\\-]+\\.?)+[^\\s<]*|^email/)\n .replace('protocol', _caseInsensitiveProtocol)\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\\S]|[^\\s~\\\\]))\\1(?=[^~]|$)/,\n text: edit(/^([`~]+|[^`~])(?:(?= {2,}\\n)|(?=[a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-]+@)|[\\s\\S]*?(?:(?=[\\\\ = {\n ...inlineGfm,\n br: edit(br).replace('{2,}', '*').getRegex(),\n text: edit(inlineGfm.text)\n .replace('\\\\b_', '\\\\b_| {2,}\\\\n')\n .replace(/\\{2,\\}/g, '*')\n .getRegex(),\n};\n\n/**\n * exports\n */\n\nexport const block = {\n normal: blockNormal,\n gfm: blockGfm,\n pedantic: blockPedantic,\n};\n\nexport const inline = {\n normal: inlineNormal,\n gfm: inlineGfm,\n breaks: inlineBreaks,\n pedantic: inlinePedantic,\n};\n\nexport interface Rules {\n other: typeof other\n block: Record\n inline: Record\n}\n", "import { other } from './rules.ts';\n\n/**\n * Helpers\n */\nconst escapeReplacements: { [index: string]: string } = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n};\nconst getEscapeReplacement = (ch: string) => escapeReplacements[ch];\n\nexport function escapeHtmlEntities(html: string, encode?: boolean) {\n if (encode) {\n if (other.escapeTest.test(html)) {\n return html.replace(other.escapeReplace, getEscapeReplacement);\n }\n } else {\n if (other.escapeTestNoEncode.test(html)) {\n return html.replace(other.escapeReplaceNoEncode, getEscapeReplacement);\n }\n }\n\n return html;\n}\n\nexport function cleanUrl(href: string) {\n try {\n href = encodeURI(href).replace(other.percentDecode, '%');\n } catch {\n return null;\n }\n return href;\n}\n\nexport function splitCells(tableRow: string, count?: number) {\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(other.findPipe, (match, offset, str) => {\n let escaped = false;\n let curr = offset;\n while (--curr >= 0 && str[curr] === '\\\\') escaped = !escaped;\n if (escaped) {\n // odd number of slashes means | is escaped\n // so we leave it alone\n return '|';\n } else {\n // add space before unescaped |\n return ' |';\n }\n }),\n cells = row.split(other.splitPipe);\n let i = 0;\n\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.at(-1)?.trim()) {\n cells.pop();\n }\n\n if (count) {\n if (cells.length > count) {\n cells.splice(count);\n } else {\n while (cells.length < count) cells.push('');\n }\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(other.slashPipe, '|');\n }\n return cells;\n}\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: string, c: string, invert?: boolean) {\n const l = str.length;\n if (l === 0) {\n return '';\n }\n\n // Length of suffix matching the invert condition.\n let suffLen = 0;\n\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 } else if (currChar !== c && invert) {\n suffLen++;\n } else {\n break;\n }\n }\n\n return str.slice(0, l - suffLen);\n}\n\nexport function trimTrailingBlankLines(str: string) {\n const lines = str.split('\\n');\n let end = lines.length - 1;\n while (end >= 0 && !lines[end].trim()) {\n end--;\n }\n if (lines.length - end <= 2) {\n // we want to keep single trailing blank lines\n return str;\n }\n\n return lines.slice(0, end + 1).join('\\n');\n}\n\nexport function findClosingBracket(str: string, b: string) {\n if (str.indexOf(b[1]) === -1) {\n return -1;\n }\n\n let level = 0;\n for (let i = 0; i < str.length; i++) {\n if (str[i] === '\\\\') {\n i++;\n } else if (str[i] === b[0]) {\n level++;\n } else if (str[i] === b[1]) {\n level--;\n if (level < 0) {\n return i;\n }\n }\n }\n if (level > 0) {\n return -2;\n }\n\n return -1;\n}\n\nexport function expandTabs(line: string, indent = 0) {\n let col = indent;\n let expanded = '';\n for (const char of line) {\n if (char === '\\t') {\n const added = 4 - (col % 4);\n expanded += ' '.repeat(added);\n col += added;\n } else {\n expanded += char;\n col++;\n }\n }\n\n return expanded;\n}\n", "import { _defaults } from './defaults.ts';\nimport {\n rtrim,\n splitCells,\n findClosingBracket,\n expandTabs,\n trimTrailingBlankLines,\n} from './helpers.ts';\nimport type { Rules } from './rules.ts';\nimport type { _Lexer } from './Lexer.ts';\nimport type { Links, Tokens, Token } from './Tokens.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\n\nfunction outputLink(cap: string[], link: Pick, raw: string, lexer: _Lexer, rules: Rules): Tokens.Link | Tokens.Image {\n const href = link.href;\n const title = link.title || null;\n const text = cap[1].replace(rules.other.outputLinkReplace, '$1');\n\n lexer.state.inLink = true;\n const token: Tokens.Link | Tokens.Image = {\n type: cap[0].charAt(0) === '!' ? 'image' : '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\nfunction indentCodeCompensation(raw: string, text: string, rules: Rules) {\n const matchIndentToCode = raw.match(rules.other.indentCodeCompensation);\n\n if (matchIndentToCode === null) {\n return text;\n }\n\n const indentToCode = matchIndentToCode[1];\n\n return text\n .split('\\n')\n .map(node => {\n const matchIndentInNode = node.match(rules.other.beginningSpace);\n if (matchIndentInNode === null) {\n return node;\n }\n\n const [indentInNode] = matchIndentInNode;\n\n if (indentInNode.length >= indentToCode.length) {\n return node.slice(indentToCode.length);\n }\n\n return node;\n })\n .join('\\n');\n}\n\n/**\n * Tokenizer\n */\nexport class _Tokenizer {\n options: MarkedOptions;\n rules!: Rules; // set by the lexer\n lexer!: _Lexer; // set by the lexer\n\n constructor(options?: MarkedOptions) {\n this.options = options || _defaults;\n }\n\n space(src: string): Tokens.Space | undefined {\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\n code(src: string): Tokens.Code | undefined {\n const cap = this.rules.block.code.exec(src);\n if (cap) {\n const raw = this.options.pedantic\n ? cap[0]\n : trimTrailingBlankLines(cap[0]);\n const text = raw.replace(this.rules.other.codeRemoveIndent, '');\n return {\n type: 'code',\n raw,\n codeBlockStyle: 'indented',\n text,\n };\n }\n }\n\n fences(src: string): Tokens.Code | undefined {\n const cap = this.rules.block.fences.exec(src);\n if (cap) {\n const raw = cap[0];\n const text = indentCodeCompensation(raw, cap[3] || '', this.rules);\n\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\n heading(src: string): Tokens.Heading | undefined {\n const cap = this.rules.block.heading.exec(src);\n if (cap) {\n let text = cap[2].trim();\n\n // remove trailing #s\n if (this.rules.other.endingHash.test(text)) {\n const trimmed = rtrim(text, '#');\n if (this.options.pedantic) {\n text = trimmed.trim();\n } else if (!trimmed || this.rules.other.endingSpaceChar.test(trimmed)) {\n // CommonMark requires space before trailing #s\n text = trimmed.trim();\n }\n }\n\n return {\n type: 'heading',\n raw: rtrim(cap[0], '\\n'),\n depth: cap[1].length,\n text,\n tokens: this.lexer.inline(text),\n };\n }\n }\n\n hr(src: string): Tokens.Hr | undefined {\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\n blockquote(src: string): Tokens.Blockquote | undefined {\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: Token[] = [];\n\n while (lines.length > 0) {\n let inBlockquote = false;\n const currentLines = [];\n\n let i;\n for (i = 0; i < lines.length; i++) {\n // get lines up to a continuation\n if (this.rules.other.blockquoteStart.test(lines[i])) {\n currentLines.push(lines[i]);\n inBlockquote = true;\n } else if (!inBlockquote) {\n currentLines.push(lines[i]);\n } else {\n break;\n }\n }\n lines = lines.slice(i);\n\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(this.rules.other.blockquoteSetextReplace, '\\n $1')\n .replace(this.rules.other.blockquoteSetextReplace2, '');\n raw = raw ? `${raw}\\n${currentRaw}` : currentRaw;\n text = text ? `${text}\\n${currentText}` : currentText;\n\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\n // if there is no continuation then we are done\n if (lines.length === 0) {\n break;\n }\n\n const lastToken = tokens.at(-1);\n\n if (lastToken?.type === 'code') {\n // blockquote continuation cannot be preceded by a code block\n break;\n } else if (lastToken?.type === 'blockquote') {\n // include continuation in nested blockquote\n const oldToken = lastToken as Tokens.Blockquote;\n const newText = oldToken.raw + '\\n' + lines.join('\\n');\n const newToken = this.blockquote(newText)!;\n tokens[tokens.length - 1] = newToken;\n\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 } else if (lastToken?.type === 'list') {\n // include continuation in nested list\n const oldToken = lastToken as Tokens.List;\n const newText = oldToken.raw + '\\n' + lines.join('\\n');\n const newToken = this.list(newText)!;\n tokens[tokens.length - 1] = newToken;\n\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.at(-1)!.raw.length).split('\\n');\n continue;\n }\n }\n\n return {\n type: 'blockquote',\n raw,\n tokens,\n text,\n };\n }\n }\n\n list(src: string): Tokens.List | undefined {\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\n const list: Tokens.List = {\n type: 'list',\n raw: '',\n ordered: isordered,\n start: isordered ? +bull.slice(0, -1) : '',\n loose: false,\n items: [],\n };\n\n bull = isordered ? `\\\\d{1,9}\\\\${bull.slice(-1)}` : `\\\\${bull}`;\n\n if (this.options.pedantic) {\n bull = isordered ? bull : '[*+-]';\n }\n\n // Get next list item\n const itemRegex = this.rules.other.listItemRegex(bull);\n let endsWithBlankLine = false;\n // Check if current bullet point can start a new List Item\n while (src) {\n let endEarly = false;\n let raw = '';\n let itemContents = '';\n if (!(cap = itemRegex.exec(src))) {\n break;\n }\n\n if (this.rules.block.hr.test(src)) { // End list if bullet was actually HR (possibly move into itemRegex?)\n break;\n }\n\n raw = cap[0];\n src = src.substring(raw.length);\n\n let line = expandTabs(cap[2].split('\\n', 1)[0], cap[1].length);\n let nextLine = src.split('\\n', 1)[0];\n let blankLine = !line.trim();\n\n let indent = 0;\n if (this.options.pedantic) {\n indent = 2;\n itemContents = line.trimStart();\n } else if (blankLine) {\n indent = cap[1].length + 1;\n } else {\n indent = line.search(this.rules.other.nonSpaceChar); // 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\n if (blankLine && this.rules.other.blankLine.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\n if (!endEarly) {\n const nextBulletRegex = this.rules.other.nextBulletRegex(indent);\n const hrRegex = this.rules.other.hrRegex(indent);\n const fencesBeginRegex = this.rules.other.fencesBeginRegex(indent);\n const headingBeginRegex = this.rules.other.headingBeginRegex(indent);\n const htmlBeginRegex = this.rules.other.htmlBeginRegex(indent);\n const blockquoteBeginRegex = this.rules.other.blockquoteBeginRegex(indent);\n\n // Check if following lines should be included in List Item\n while (src) {\n const rawLine = src.split('\\n', 1)[0];\n let nextLineWithoutTabs;\n nextLine = rawLine;\n\n // Re-align to follow commonmark nesting rules\n if (this.options.pedantic) {\n nextLine = nextLine.replace(this.rules.other.listReplaceNesting, ' ');\n nextLineWithoutTabs = nextLine;\n } else {\n nextLineWithoutTabs = nextLine.replace(this.rules.other.tabCharGlobal, ' ');\n }\n\n // End list item if found code fences\n if (fencesBeginRegex.test(nextLine)) {\n break;\n }\n\n // End list item if found start of new heading\n if (headingBeginRegex.test(nextLine)) {\n break;\n }\n\n // End list item if found start of html block\n if (htmlBeginRegex.test(nextLine)) {\n break;\n }\n\n // End list item if found start of blockquote\n if (blockquoteBeginRegex.test(nextLine)) {\n break;\n }\n\n // End list item if found start of new bullet\n if (nextBulletRegex.test(nextLine)) {\n break;\n }\n\n // Horizontal rule found\n if (hrRegex.test(nextLine)) {\n break;\n }\n\n if (nextLineWithoutTabs.search(this.rules.other.nonSpaceChar) >= indent || !nextLine.trim()) { // Dedent if possible\n itemContents += '\\n' + nextLineWithoutTabs.slice(indent);\n } else {\n // not enough indentation\n if (blankLine) {\n break;\n }\n\n // paragraph continuation unless last line was a different block level element\n if (line.replace(this.rules.other.tabCharGlobal, ' ').search(this.rules.other.nonSpaceChar) >= 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\n itemContents += '\\n' + nextLine;\n }\n\n blankLine = !nextLine.trim();\n\n raw += rawLine + '\\n';\n src = src.substring(rawLine.length + 1);\n line = nextLineWithoutTabs.slice(indent);\n }\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 } else if (this.rules.other.doubleBlankLine.test(raw)) {\n endsWithBlankLine = true;\n }\n }\n\n list.items.push({\n type: 'list_item',\n raw,\n task: !!this.options.gfm && this.rules.other.listIsTask.test(itemContents),\n loose: false,\n text: itemContents,\n tokens: [],\n });\n\n list.raw += raw;\n }\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 const lastItem = list.items.at(-1);\n if (lastItem) {\n lastItem.raw = lastItem.raw.trimEnd();\n lastItem.text = lastItem.text.trimEnd();\n } else {\n // not a list since there were no items\n return;\n }\n list.raw = list.raw.trimEnd();\n\n // Item child tokens handled here at end because we needed to have the final item to trim it first\n for (const item of list.items) {\n this.lexer.state.top = false;\n item.tokens = this.lexer.blockTokens(item.text, []);\n if (item.task) {\n // Remove checkbox markdown from item tokens\n item.text = item.text.replace(this.rules.other.listReplaceTask, '');\n if (item.tokens[0]?.type === 'text' || item.tokens[0]?.type === 'paragraph') {\n item.tokens[0].raw = item.tokens[0].raw.replace(this.rules.other.listReplaceTask, '');\n item.tokens[0].text = item.tokens[0].text.replace(this.rules.other.listReplaceTask, '');\n for (let i = this.lexer.inlineQueue.length - 1; i >= 0; i--) {\n if (this.rules.other.listIsTask.test(this.lexer.inlineQueue[i].src)) {\n this.lexer.inlineQueue[i].src = this.lexer.inlineQueue[i].src.replace(this.rules.other.listReplaceTask, '');\n break;\n }\n }\n }\n\n const taskRaw = this.rules.other.listTaskCheckbox.exec(item.raw);\n if (taskRaw) {\n const checkboxToken: Tokens.Checkbox = {\n type: 'checkbox',\n raw: taskRaw[0] + ' ',\n checked: taskRaw[0] !== '[ ]',\n };\n item.checked = checkboxToken.checked;\n if (list.loose) {\n if (item.tokens[0] && ['paragraph', 'text'].includes(item.tokens[0].type) && 'tokens' in item.tokens[0] && item.tokens[0].tokens) {\n item.tokens[0].raw = checkboxToken.raw + item.tokens[0].raw;\n item.tokens[0].text = checkboxToken.raw + item.tokens[0].text;\n item.tokens[0].tokens.unshift(checkboxToken);\n } else {\n item.tokens.unshift({\n type: 'paragraph',\n raw: checkboxToken.raw,\n text: checkboxToken.raw,\n tokens: [checkboxToken],\n });\n }\n } else {\n item.tokens.unshift(checkboxToken);\n }\n }\n }\n\n if (!list.loose) {\n // Check if list should be loose\n const spacers = item.tokens.filter(t => t.type === 'space');\n const hasMultipleLineBreaks = spacers.length > 0 && spacers.some(t => this.rules.other.anyLine.test(t.raw));\n\n list.loose = hasMultipleLineBreaks;\n }\n }\n\n // Set all items to loose if list is loose\n if (list.loose) {\n for (const item of list.items) {\n item.loose = true;\n for (const token of item.tokens) {\n if (token.type === 'text') {\n token.type = 'paragraph';\n }\n }\n }\n }\n\n return list;\n }\n }\n\n html(src: string): Tokens.HTML | undefined {\n const cap = this.rules.block.html.exec(src);\n if (cap) {\n const raw = trimTrailingBlankLines(cap[0]);\n const token: Tokens.HTML = {\n type: 'html',\n block: true,\n raw,\n pre: cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style',\n text: raw,\n };\n return token;\n }\n }\n\n def(src: string): Tokens.Def | undefined {\n const cap = this.rules.block.def.exec(src);\n if (cap) {\n const tag = cap[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal, ' ');\n const href = cap[2] ? cap[2].replace(this.rules.other.hrefBrackets, '$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: rtrim(cap[0], '\\n'),\n href,\n title,\n };\n }\n }\n\n table(src: string): Tokens.Table | undefined {\n const cap = this.rules.block.table.exec(src);\n if (!cap) {\n return;\n }\n\n if (!this.rules.other.tableDelimiter.test(cap[2])) {\n // delimiter row must have a pipe (|) or colon (:) otherwise it is a setext heading\n return;\n }\n\n const headers = splitCells(cap[1]);\n const aligns = cap[2].replace(this.rules.other.tableAlignChars, '').split('|');\n const rows = cap[3]?.trim() ? cap[3].replace(this.rules.other.tableRowBlankLine, '').split('\\n') : [];\n\n const item: Tokens.Table = {\n type: 'table',\n raw: rtrim(cap[0], '\\n'),\n header: [],\n align: [],\n rows: [],\n };\n\n if (headers.length !== aligns.length) {\n // header and align columns must be equal, rows can be different.\n return;\n }\n\n for (const align of aligns) {\n if (this.rules.other.tableAlignRight.test(align)) {\n item.align.push('right');\n } else if (this.rules.other.tableAlignCenter.test(align)) {\n item.align.push('center');\n } else if (this.rules.other.tableAlignLeft.test(align)) {\n item.align.push('left');\n } else {\n item.align.push(null);\n }\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\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\n return item;\n }\n\n lheading(src: string): Tokens.Heading | undefined {\n const cap = this.rules.block.lheading.exec(src);\n if (cap) {\n const text = cap[1].trim();\n return {\n type: 'heading',\n raw: rtrim(cap[0], '\\n'),\n depth: cap[2].charAt(0) === '=' ? 1 : 2,\n text,\n tokens: this.lexer.inline(text),\n };\n }\n }\n\n paragraph(src: string): Tokens.Paragraph | undefined {\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\n text(src: string): Tokens.Text | undefined {\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\n escape(src: string): Tokens.Escape | undefined {\n const cap = this.rules.inline.escape.exec(src);\n if (cap) {\n return {\n type: 'escape',\n raw: cap[0],\n text: cap[1],\n };\n }\n }\n\n tag(src: string): Tokens.Tag | undefined {\n const cap = this.rules.inline.tag.exec(src);\n if (cap) {\n if (!this.lexer.state.inLink && this.rules.other.startATag.test(cap[0])) {\n this.lexer.state.inLink = true;\n } else if (this.lexer.state.inLink && this.rules.other.endATag.test(cap[0])) {\n this.lexer.state.inLink = false;\n }\n if (!this.lexer.state.inRawBlock && this.rules.other.startPreScriptTag.test(cap[0])) {\n this.lexer.state.inRawBlock = true;\n } else if (this.lexer.state.inRawBlock && this.rules.other.endPreScriptTag.test(cap[0])) {\n this.lexer.state.inRawBlock = false;\n }\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\n link(src: string): Tokens.Link | Tokens.Image | undefined {\n const cap = this.rules.inline.link.exec(src);\n if (cap) {\n const trimmedUrl = cap[2].trim();\n if (!this.options.pedantic && this.rules.other.startAngleBracket.test(trimmedUrl)) {\n // commonmark requires matching angle brackets\n if (!(this.rules.other.endAngleBracket.test(trimmedUrl))) {\n return;\n }\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 } else {\n // find closing parenthesis\n const lastParenIndex = findClosingBracket(cap[2], '()');\n if (lastParenIndex === -2) {\n // more open parens than closed\n return;\n }\n\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 = this.rules.other.pedanticHrefTitle.exec(href);\n\n if (link) {\n href = link[1];\n title = link[3];\n }\n } else {\n title = cap[3] ? cap[3].slice(1, -1) : '';\n }\n\n href = href.trim();\n if (this.rules.other.startAngleBracket.test(href)) {\n if (this.options.pedantic && !(this.rules.other.endAngleBracket.test(trimmedUrl))) {\n // pedantic allows starting angle bracket without ending angle bracket\n href = href.slice(1);\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, this.rules);\n }\n }\n\n reflink(src: string, links: Links): Tokens.Link | Tokens.Image | Tokens.Text | undefined {\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(this.rules.other.multipleSpaceGlobal, ' ');\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, this.rules);\n }\n }\n\n emStrong(src: string, maskedSrc: string, prevChar = ''): Tokens.Em | Tokens.Strong | undefined {\n let match = this.rules.inline.emStrongLDelim.exec(src);\n if (!match) return;\n if (!match[1] && !match[2] && !match[3] && !match[4]) return;\n\n // _ can't be between two alphanumerics. \\p{L}\\p{N} includes non-english alphabet/numbers as well\n if (match[4] && prevChar.match(this.rules.other.unicodeAlphaNumeric)) return;\n\n const nextChar = match[1] || match[3] || '';\n\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\n const endReg = match[0][0] === '*' ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;\n endReg.lastIndex = 0;\n\n // Clip maskedSrc to same section of string as src (move to lexer?)\n maskedSrc = maskedSrc.slice(-1 * src.length + lLength);\n\n while ((match = endReg.exec(maskedSrc)) !== null) {\n rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6];\n\n if (!rDelim) continue; // skip single * in __abc*abc__\n\n rLength = [...rDelim].length;\n\n if (match[3] || match[4]) { // found another Left Delim\n delimTotal += rLength;\n continue;\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\n delimTotal -= rLength;\n\n if (delimTotal > 0) continue; // Haven't found enough closing delimiters\n\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\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\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\n codespan(src: string): Tokens.Codespan | undefined {\n const cap = this.rules.inline.code.exec(src);\n if (cap) {\n let text = cap[2].replace(this.rules.other.newLineCharGlobal, ' ');\n const hasNonSpaceChars = this.rules.other.nonSpaceChar.test(text);\n const hasSpaceCharsOnBothEnds = this.rules.other.startingSpaceChar.test(text) && this.rules.other.endingSpaceChar.test(text);\n if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {\n text = text.substring(1, text.length - 1);\n }\n return {\n type: 'codespan',\n raw: cap[0],\n text,\n };\n }\n }\n\n br(src: string): Tokens.Br | undefined {\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\n del(src: string, maskedSrc: string, prevChar = ''): Tokens.Del | undefined {\n let match = this.rules.inline.delLDelim.exec(src);\n if (!match) return;\n\n const nextChar = match[1] || '';\n\n if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) {\n // unicode Regex counts emoji as 1 char; spread into array for proper count\n const lLength = [...match[0]].length - 1;\n let rDelim, rLength, delimTotal = lLength;\n\n const endReg = this.rules.inline.delRDelim;\n endReg.lastIndex = 0;\n\n // Clip maskedSrc to same section of string as src\n maskedSrc = maskedSrc.slice(-1 * src.length + lLength);\n\n while ((match = endReg.exec(maskedSrc)) !== null) {\n rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6];\n\n if (!rDelim) continue;\n\n rLength = [...rDelim].length;\n\n if (rLength !== lLength) continue;\n\n if (match[3] || match[4]) { // found another Left Delim\n delimTotal += rLength;\n continue;\n }\n\n delimTotal -= rLength;\n\n if (delimTotal > 0) continue; // Haven't found enough closing delimiters\n\n // Remove extra characters\n rLength = Math.min(rLength, rLength + delimTotal);\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\n // Create del token - only single ~ or double ~~ supported\n const text = raw.slice(lLength, -lLength);\n return {\n type: 'del',\n raw,\n text,\n tokens: this.lexer.inlineTokens(text),\n };\n }\n }\n }\n\n autolink(src: string): Tokens.Link | undefined {\n const cap = this.rules.inline.autolink.exec(src);\n if (cap) {\n let text, href;\n if (cap[2] === '@') {\n text = cap[1];\n href = 'mailto:' + text;\n } else {\n text = cap[1];\n href = text;\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\n url(src: string): Tokens.Link | undefined {\n let cap;\n if (cap = this.rules.inline.url.exec(src)) {\n let text, href;\n if (cap[2] === '@') {\n text = cap[0];\n href = 'mailto:' + text;\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 = cap[0];\n if (cap[1] === 'www.') {\n href = 'http://' + cap[0];\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\n inlineText(src: string): Tokens.Text | undefined {\n const cap = this.rules.inline.text.exec(src);\n if (cap) {\n const escaped = this.lexer.state.inRawBlock;\n return {\n type: 'text',\n raw: cap[0],\n text: cap[0],\n escaped,\n };\n }\n }\n}\n", "import { _Tokenizer } from './Tokenizer.ts';\nimport { _defaults } from './defaults.ts';\nimport { other, block, inline } from './rules.ts';\nimport type { Token, TokensList, Tokens } from './Tokens.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\n\n/**\n * Block Lexer\n */\nexport class _Lexer {\n tokens: TokensList;\n options: MarkedOptions;\n state: {\n inLink: boolean;\n inRawBlock: boolean;\n top: boolean;\n };\n\n public inlineQueue: { src: string, tokens: Token[] }[];\n\n private tokenizer: _Tokenizer;\n\n constructor(options?: MarkedOptions) {\n // TokenList cannot be created in one go\n this.tokens = [] as unknown as TokensList;\n this.tokens.links = Object.create(null);\n this.options = options || _defaults;\n this.options.tokenizer = this.options.tokenizer || new _Tokenizer();\n this.tokenizer = this.options.tokenizer;\n this.tokenizer.options = this.options;\n this.tokenizer.lexer = this;\n this.inlineQueue = [];\n this.state = {\n inLink: false,\n inRawBlock: false,\n top: true,\n };\n\n const rules = {\n other,\n block: block.normal,\n inline: inline.normal,\n };\n\n if (this.options.pedantic) {\n rules.block = block.pedantic;\n rules.inline = inline.pedantic;\n } else if (this.options.gfm) {\n rules.block = block.gfm;\n if (this.options.breaks) {\n rules.inline = inline.breaks;\n } else {\n rules.inline = inline.gfm;\n }\n }\n this.tokenizer.rules = rules;\n }\n\n /**\n * Expose Rules\n */\n static get rules() {\n return {\n block,\n inline,\n };\n }\n\n /**\n * Static Lex Method\n */\n static lex(src: string, options?: MarkedOptions) {\n const lexer = new _Lexer(options);\n return lexer.lex(src);\n }\n\n /**\n * Static Lex Inline Method\n */\n static lexInline(src: string, options?: MarkedOptions) {\n const lexer = new _Lexer(options);\n return lexer.inlineTokens(src);\n }\n\n /**\n * Preprocessing\n */\n lex(src: string) {\n src = src.replace(other.carriageReturn, '\\n');\n\n this.blockTokens(src, this.tokens);\n\n for (let i = 0; i < this.inlineQueue.length; i++) {\n const next = this.inlineQueue[i];\n this.inlineTokens(next.src, next.tokens);\n }\n this.inlineQueue = [];\n\n return this.tokens;\n }\n\n /**\n * Lexing\n */\n blockTokens(src: string, tokens?: Token[], lastParagraphClipped?: boolean): Token[];\n blockTokens(src: string, tokens?: TokensList, lastParagraphClipped?: boolean): TokensList;\n blockTokens(src: string, tokens: Token[] = [], lastParagraphClipped = false) {\n this.tokenizer.lexer = this;\n if (this.options.pedantic) {\n src = src.replace(other.tabCharGlobal, ' ').replace(other.spaceLine, '');\n }\n\n while (src) {\n let token: Tokens.Generic | undefined;\n\n if (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\n // newline\n if (token = this.tokenizer.space(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (token.raw.length === 1 && lastToken !== undefined) {\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 lastToken.raw += '\\n';\n } else {\n tokens.push(token);\n }\n continue;\n }\n\n // code\n if (token = this.tokenizer.code(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n // An indented code block cannot interrupt a paragraph.\n if (lastToken?.type === 'paragraph' || lastToken?.type === 'text') {\n lastToken.raw += (lastToken.raw.endsWith('\\n') ? '' : '\\n') + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.at(-1)!.src = lastToken.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\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\n // heading\n if (token = this.tokenizer.heading(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\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\n // blockquote\n if (token = this.tokenizer.blockquote(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\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\n // html\n if (token = this.tokenizer.html(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // def\n if (token = this.tokenizer.def(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (lastToken?.type === 'paragraph' || lastToken?.type === 'text') {\n lastToken.raw += (lastToken.raw.endsWith('\\n') ? '' : '\\n') + token.raw;\n lastToken.text += '\\n' + token.raw;\n this.inlineQueue.at(-1)!.src = lastToken.text;\n } else if (!this.tokens.links[token.tag]) {\n this.tokens.links[token.tag] = {\n href: token.href,\n title: token.title,\n };\n tokens.push(token);\n }\n continue;\n }\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\n // lheading\n if (token = this.tokenizer.lheading(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // top-level paragraph\n // prevent paragraph consuming extensions by clipping 'src' to extension start\n let cutSrc = src;\n if (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 const lastToken = tokens.at(-1);\n if (lastParagraphClipped && lastToken?.type === 'paragraph') {\n lastToken.raw += (lastToken.raw.endsWith('\\n') ? '' : '\\n') + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.pop();\n this.inlineQueue.at(-1)!.src = lastToken.text;\n } else {\n tokens.push(token);\n }\n lastParagraphClipped = cutSrc.length !== src.length;\n src = src.substring(token.raw.length);\n continue;\n }\n\n // text\n if (token = this.tokenizer.text(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (lastToken?.type === 'text') {\n lastToken.raw += (lastToken.raw.endsWith('\\n') ? '' : '\\n') + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.pop();\n this.inlineQueue.at(-1)!.src = lastToken.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\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 } else {\n throw new Error(errMsg);\n }\n }\n }\n\n this.state.top = true;\n return tokens;\n }\n\n inline(src: string, tokens: Token[] = []) {\n this.inlineQueue.push({ src, tokens });\n return tokens;\n }\n\n /**\n * Lexing/Compiling\n */\n inlineTokens(src: string, tokens: Token[] = []): Token[] {\n this.tokenizer.lexer = this;\n // String with links masked to avoid interference with em and strong\n let maskedSrc = src;\n let match: RegExpExecArray | null = null;\n\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)\n + '[' + 'a'.repeat(match[0].length - 2) + ']'\n + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex);\n }\n }\n }\n }\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\n // Mask out other blocks\n let offset;\n while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) !== null) {\n offset = match[2] ? match[2].length : 0;\n maskedSrc = maskedSrc.slice(0, match.index + offset) + '[' + 'a'.repeat(match[0].length - offset - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);\n }\n\n // Mask out blocks from extensions\n maskedSrc = this.options.hooks?.emStrongMask?.call({ lexer: this }, maskedSrc) ?? maskedSrc;\n\n let keepPrevChar = false;\n let prevChar = '';\n while (src) {\n if (!keepPrevChar) {\n prevChar = '';\n }\n keepPrevChar = false;\n\n let token: Tokens.Generic | undefined;\n\n // extensions\n if (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\n // escape\n if (token = this.tokenizer.escape(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // tag\n if (token = this.tokenizer.tag(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\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\n // reflink, nolink\n if (token = this.tokenizer.reflink(src, this.tokens.links)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (token.type === 'text' && lastToken?.type === 'text') {\n lastToken.raw += token.raw;\n lastToken.text += token.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\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\n // code\n if (token = this.tokenizer.codespan(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\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\n // del (gfm)\n if (token = this.tokenizer.del(src, maskedSrc, prevChar)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\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\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\n // text\n // prevent inlineText consuming extensions by clipping 'src' to extension start\n let cutSrc = src;\n if (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 const lastToken = tokens.at(-1);\n if (lastToken?.type === 'text') {\n lastToken.raw += token.raw;\n lastToken.text += token.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\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 } else {\n throw new Error(errMsg);\n }\n }\n }\n\n return tokens;\n }\n}\n", "import { _defaults } from './defaults.ts';\nimport {\n cleanUrl,\n escapeHtmlEntities,\n} from './helpers.ts';\nimport { other } from './rules.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\nimport type { Tokens } from './Tokens.ts';\nimport type { _Parser } from './Parser.ts';\n\n/**\n * Renderer\n */\nexport class _Renderer {\n options: MarkedOptions;\n parser!: _Parser; // set by the parser\n constructor(options?: MarkedOptions) {\n this.options = options || _defaults;\n }\n\n space(token: Tokens.Space): RendererOutput {\n return '' as RendererOutput;\n }\n\n code({ text, lang, escaped }: Tokens.Code): RendererOutput {\n const langString = (lang || '').match(other.notSpaceStart)?.[0];\n\n const code = text.replace(other.endingNewline, '') + '\\n';\n\n if (!langString) {\n return '
    '\n        + (escaped ? code : escapeHtmlEntities(code, true))\n        + '
    \\n' as RendererOutput;\n }\n\n return '
    '\n      + (escaped ? code : escapeHtmlEntities(code, true))\n      + '
    \\n' as RendererOutput;\n }\n\n blockquote({ tokens }: Tokens.Blockquote): RendererOutput {\n const body = this.parser.parse(tokens);\n return `
    \\n${body}
    \\n` as RendererOutput;\n }\n\n html({ text }: Tokens.HTML | Tokens.Tag): RendererOutput {\n return text as RendererOutput;\n }\n\n def(token: Tokens.Def): RendererOutput {\n return '' as RendererOutput;\n }\n\n heading({ tokens, depth }: Tokens.Heading): RendererOutput {\n return `${this.parser.parseInline(tokens)}\\n` as RendererOutput;\n }\n\n hr(token: Tokens.Hr): RendererOutput {\n return '
    \\n' as RendererOutput;\n }\n\n list(token: Tokens.List): RendererOutput {\n const ordered = token.ordered;\n const start = token.start;\n\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\n const type = ordered ? 'ol' : 'ul';\n const startAttr = (ordered && start !== 1) ? (' start=\"' + start + '\"') : '';\n return '<' + type + startAttr + '>\\n' + body + '\\n' as RendererOutput;\n }\n\n listitem(item: Tokens.ListItem): RendererOutput {\n return `
  • ${this.parser.parse(item.tokens)}
  • \\n` as RendererOutput;\n }\n\n checkbox({ checked }: Tokens.Checkbox): RendererOutput {\n return ' ' as RendererOutput;\n }\n\n paragraph({ tokens }: Tokens.Paragraph): RendererOutput {\n return `

    ${this.parser.parseInline(tokens)}

    \\n` as RendererOutput;\n }\n\n table(token: Tokens.Table): RendererOutput {\n let header = '';\n\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 as ParserOutput });\n\n let body = '';\n for (let j = 0; j < token.rows.length; j++) {\n const row = token.rows[j];\n\n cell = '';\n for (let k = 0; k < row.length; k++) {\n cell += this.tablecell(row[k]);\n }\n\n body += this.tablerow({ text: cell as ParserOutput });\n }\n if (body) body = `${body}`;\n\n return '\\n'\n + '\\n'\n + header\n + '\\n'\n + body\n + '
    \\n' as RendererOutput;\n }\n\n tablerow({ text }: Tokens.TableRow): RendererOutput {\n return `\\n${text}\\n` as RendererOutput;\n }\n\n tablecell(token: Tokens.TableCell): RendererOutput {\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` as RendererOutput;\n }\n\n /**\n * span level renderer\n */\n strong({ tokens }: Tokens.Strong): RendererOutput {\n return `${this.parser.parseInline(tokens)}` as RendererOutput;\n }\n\n em({ tokens }: Tokens.Em): RendererOutput {\n return `${this.parser.parseInline(tokens)}` as RendererOutput;\n }\n\n codespan({ text }: Tokens.Codespan): RendererOutput {\n return `${escapeHtmlEntities(text, true)}` as RendererOutput;\n }\n\n br(token: Tokens.Br): RendererOutput {\n return '
    ' as RendererOutput;\n }\n\n del({ tokens }: Tokens.Del): RendererOutput {\n return `${this.parser.parseInline(tokens)}` as RendererOutput;\n }\n\n link({ href, title, tokens }: Tokens.Link): RendererOutput {\n const text = this.parser.parseInline(tokens) as string;\n const cleanHref = cleanUrl(href);\n if (cleanHref === null) {\n return text as RendererOutput;\n }\n href = cleanHref;\n let out = '
    ';\n return out as RendererOutput;\n }\n\n image({ href, title, text, tokens }: Tokens.Image): RendererOutput {\n if (tokens) {\n text = this.parser.parseInline(tokens, this.parser.textRenderer) as string;\n }\n const cleanHref = cleanUrl(href);\n if (cleanHref === null) {\n return escapeHtmlEntities(text) as RendererOutput;\n }\n href = cleanHref;\n\n let out = `\"${escapeHtmlEntities(text)}\"`;\n {\n // no need for block level renderers\n strong({ text }: Tokens.Strong): RendererOutput {\n return text as RendererOutput;\n }\n\n em({ text }: Tokens.Em): RendererOutput {\n return text as RendererOutput;\n }\n\n codespan({ text }: Tokens.Codespan): RendererOutput {\n return text as RendererOutput;\n }\n\n del({ text }: Tokens.Del): RendererOutput {\n return text as RendererOutput;\n }\n\n html({ text }: Tokens.HTML | Tokens.Tag): RendererOutput {\n return text as RendererOutput;\n }\n\n text({ text }: Tokens.Text | Tokens.Escape | Tokens.Tag): RendererOutput {\n return text as RendererOutput;\n }\n\n link({ text }: Tokens.Link): RendererOutput {\n return '' + text as RendererOutput;\n }\n\n image({ text }: Tokens.Image): RendererOutput {\n return '' + text as RendererOutput;\n }\n\n br(): RendererOutput {\n return '' as RendererOutput;\n }\n\n checkbox({ raw }: Tokens.Checkbox): RendererOutput {\n return raw as RendererOutput;\n }\n}\n", "import { _Renderer } from './Renderer.ts';\nimport { _TextRenderer } from './TextRenderer.ts';\nimport { _defaults } from './defaults.ts';\nimport type { MarkedToken, Token, Tokens } from './Tokens.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\n\n/**\n * Parsing & Compiling\n */\nexport class _Parser {\n options: MarkedOptions;\n renderer: _Renderer;\n textRenderer: _TextRenderer;\n constructor(options?: MarkedOptions) {\n this.options = options || _defaults;\n this.options.renderer = this.options.renderer || new _Renderer();\n this.renderer = this.options.renderer;\n this.renderer.options = this.options;\n this.renderer.parser = this;\n this.textRenderer = new _TextRenderer();\n }\n\n /**\n * Static Parse Method\n */\n static parse(tokens: Token[], options?: MarkedOptions) {\n const parser = new _Parser(options);\n return parser.parse(tokens);\n }\n\n /**\n * Static Parse Inline Method\n */\n static parseInline(tokens: Token[], options?: MarkedOptions) {\n const parser = new _Parser(options);\n return parser.parseInline(tokens);\n }\n\n /**\n * Parse Loop\n */\n parse(tokens: Token[]): ParserOutput {\n this.renderer.parser = this;\n let out = '';\n\n for (let i = 0; i < tokens.length; i++) {\n const anyToken = tokens[i];\n\n // Run any renderer extensions\n if (this.options.extensions?.renderers?.[anyToken.type]) {\n const genericToken = anyToken as Tokens.Generic;\n const ret = this.options.extensions.renderers[genericToken.type].call({ parser: this }, genericToken);\n if (ret !== false || !['space', 'hr', 'heading', 'code', 'table', 'blockquote', 'list', 'html', 'def', 'paragraph', 'text'].includes(genericToken.type)) {\n out += ret || '';\n continue;\n }\n }\n\n const token = anyToken as MarkedToken;\n\n switch (token.type) {\n case 'space': {\n out += this.renderer.space(token);\n break;\n }\n case 'hr': {\n out += this.renderer.hr(token);\n break;\n }\n case 'heading': {\n out += this.renderer.heading(token);\n break;\n }\n case 'code': {\n out += this.renderer.code(token);\n break;\n }\n case 'table': {\n out += this.renderer.table(token);\n break;\n }\n case 'blockquote': {\n out += this.renderer.blockquote(token);\n break;\n }\n case 'list': {\n out += this.renderer.list(token);\n break;\n }\n case 'checkbox': {\n out += this.renderer.checkbox(token);\n break;\n }\n case 'html': {\n out += this.renderer.html(token);\n break;\n }\n case 'def': {\n out += this.renderer.def(token);\n break;\n }\n case 'paragraph': {\n out += this.renderer.paragraph(token);\n break;\n }\n case 'text': {\n out += this.renderer.text(token);\n break;\n }\n\n default: {\n const errMsg = 'Token with \"' + token.type + '\" type was not found.';\n if (this.options.silent) {\n console.error(errMsg);\n return '' as ParserOutput;\n } else {\n throw new Error(errMsg);\n }\n }\n }\n }\n\n return out as ParserOutput;\n }\n\n /**\n * Parse Inline Tokens\n */\n parseInline(tokens: Token[], renderer: _Renderer | _TextRenderer = this.renderer): ParserOutput {\n this.renderer.parser = this;\n let out = '';\n\n for (let i = 0; i < tokens.length; i++) {\n const anyToken = tokens[i];\n\n // Run any renderer extensions\n if (this.options.extensions?.renderers?.[anyToken.type]) {\n const ret = this.options.extensions.renderers[anyToken.type].call({ parser: this }, anyToken);\n if (ret !== false || !['escape', 'html', 'link', 'image', 'strong', 'em', 'codespan', 'br', 'del', 'text'].includes(anyToken.type)) {\n out += ret || '';\n continue;\n }\n }\n\n const token = anyToken as MarkedToken;\n\n switch (token.type) {\n case 'escape': {\n out += renderer.text(token);\n break;\n }\n case 'html': {\n out += renderer.html(token);\n break;\n }\n case 'link': {\n out += renderer.link(token);\n break;\n }\n case 'image': {\n out += renderer.image(token);\n break;\n }\n case 'checkbox': {\n out += renderer.checkbox(token);\n break;\n }\n case 'strong': {\n out += renderer.strong(token);\n break;\n }\n case 'em': {\n out += renderer.em(token);\n break;\n }\n case 'codespan': {\n out += renderer.codespan(token);\n break;\n }\n case 'br': {\n out += renderer.br(token);\n break;\n }\n case 'del': {\n out += renderer.del(token);\n break;\n }\n case 'text': {\n out += renderer.text(token);\n break;\n }\n default: {\n const errMsg = 'Token with \"' + token.type + '\" type was not found.';\n if (this.options.silent) {\n console.error(errMsg);\n return '' as ParserOutput;\n } else {\n throw new Error(errMsg);\n }\n }\n }\n }\n return out as ParserOutput;\n }\n}\n", "import { _defaults } from './defaults.ts';\nimport { _Lexer } from './Lexer.ts';\nimport { _Parser } from './Parser.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\nimport type { Token, TokensList } from './Tokens.ts';\n\nexport class _Hooks {\n options: MarkedOptions;\n block?: boolean;\n\n constructor(options?: MarkedOptions) {\n this.options = options || _defaults;\n }\n\n static passThroughHooks = new Set([\n 'preprocess',\n 'postprocess',\n 'processAllTokens',\n 'emStrongMask',\n ]);\n\n static passThroughHooksRespectAsync = new Set([\n 'preprocess',\n 'postprocess',\n 'processAllTokens',\n ]);\n\n /**\n * Process markdown before marked\n */\n preprocess(markdown: string) {\n return markdown;\n }\n\n /**\n * Process HTML after marked is finished\n */\n postprocess(html: ParserOutput) {\n return html;\n }\n\n /**\n * Process all tokens before walk tokens\n */\n processAllTokens(tokens: Token[] | TokensList) {\n return tokens;\n }\n\n /**\n * Mask contents that should not be interpreted as em/strong delimiters\n */\n emStrongMask(src: string) {\n return src;\n }\n\n /**\n * Provide function to tokenize markdown\n */\n provideLexer(block = this.block) {\n return block ? _Lexer.lex : _Lexer.lexInline;\n }\n\n /**\n * Provide function to parse tokens\n */\n provideParser(block = this.block) {\n return block ? _Parser.parse : _Parser.parseInline;\n }\n}\n", "import { _getDefaults } from './defaults.ts';\nimport { _Lexer } from './Lexer.ts';\nimport { _Parser } from './Parser.ts';\nimport { _Hooks } from './Hooks.ts';\nimport { _Renderer } from './Renderer.ts';\nimport { _Tokenizer } from './Tokenizer.ts';\nimport { _TextRenderer } from './TextRenderer.ts';\nimport { escapeHtmlEntities } from './helpers.ts';\nimport type { MarkedExtension, MarkedOptions } from './MarkedOptions.ts';\nimport type { Token, Tokens, TokensList } from './Tokens.ts';\n\nexport type MaybePromise = void | Promise;\n\ntype UnknownFunction = (...args: unknown[]) => unknown;\ntype GenericRendererFunction = (...args: unknown[]) => string | false;\n\nexport class Marked {\n defaults = _getDefaults();\n options = this.setOptions;\n\n parse = this.parseMarkdown(true);\n parseInline = this.parseMarkdown(false);\n\n Parser = _Parser;\n Renderer = _Renderer;\n TextRenderer = _TextRenderer;\n Lexer = _Lexer;\n Tokenizer = _Tokenizer;\n Hooks = _Hooks;\n\n constructor(...args: MarkedExtension[]) {\n this.use(...args);\n }\n\n /**\n * Run callback for every token\n */\n walkTokens(tokens: Token[] | TokensList, callback: (token: Token) => MaybePromise | MaybePromise[]) {\n let values: MaybePromise[] = [];\n for (const token of tokens) {\n values = values.concat(callback.call(this, token));\n switch (token.type) {\n case 'table': {\n const tableToken = token as Tokens.Table;\n for (const cell of tableToken.header) {\n values = values.concat(this.walkTokens(cell.tokens, callback));\n }\n for (const row of tableToken.rows) {\n for (const cell of row) {\n values = values.concat(this.walkTokens(cell.tokens, callback));\n }\n }\n break;\n }\n case 'list': {\n const listToken = token as Tokens.List;\n values = values.concat(this.walkTokens(listToken.items, callback));\n break;\n }\n default: {\n const genericToken = token as Tokens.Generic;\n if (this.defaults.extensions?.childTokens?.[genericToken.type]) {\n this.defaults.extensions.childTokens[genericToken.type].forEach((childTokens) => {\n const tokens = genericToken[childTokens].flat(Infinity) as Token[] | TokensList;\n values = values.concat(this.walkTokens(tokens, callback));\n });\n } else if (genericToken.tokens) {\n values = values.concat(this.walkTokens(genericToken.tokens, callback));\n }\n }\n }\n }\n return values;\n }\n\n use(...args: MarkedExtension[]) {\n const extensions: MarkedOptions['extensions'] = this.defaults.extensions || { renderers: {}, childTokens: {} };\n\n args.forEach((pack) => {\n // copy options to new object\n const opts = { ...pack } as MarkedOptions;\n\n // set async to true if it was set to true before\n opts.async = this.defaults.async || opts.async || false;\n\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 } 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 } 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 } else {\n extensions.startBlock = [ext.start];\n }\n } else if (ext.level === 'inline') {\n if (extensions.startInline) {\n extensions.startInline.push(ext.start);\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\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 as Exclude, 'options' | 'parser'>;\n const rendererFunc = pack.renderer[rendererProp] as GenericRendererFunction;\n const prevRenderer = renderer[rendererProp] as GenericRendererFunction;\n // Replace renderer with func to run extension, but fall back if false\n renderer[rendererProp] = (...args: unknown[]) => {\n let ret = rendererFunc.apply(renderer, args);\n if (ret === false) {\n ret = prevRenderer.apply(renderer, args);\n }\n return (ret || '') as RendererOutput;\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 as Exclude, 'options' | 'rules' | 'lexer'>;\n const tokenizerFunc = pack.tokenizer[tokenizerProp] as UnknownFunction;\n const prevTokenizer = tokenizer[tokenizerProp] as UnknownFunction;\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: unknown[]) => {\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\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 (['options', 'block'].includes(prop)) {\n // ignore options and block properties\n continue;\n }\n const hooksProp = prop as Exclude, 'options' | 'block'>;\n const hooksFunc = pack.hooks[hooksProp] as UnknownFunction;\n const prevHook = hooks[hooksProp] as UnknownFunction;\n if (_Hooks.passThroughHooks.has(prop)) {\n // @ts-expect-error cannot type hook function dynamically\n hooks[hooksProp] = (arg: unknown) => {\n if (this.defaults.async && _Hooks.passThroughHooksRespectAsync.has(prop)) {\n return (async() => {\n const ret = await hooksFunc.call(hooks, arg);\n return prevHook.call(hooks, ret);\n })();\n }\n\n const ret = hooksFunc.call(hooks, arg);\n return prevHook.call(hooks, ret);\n };\n } else {\n // @ts-expect-error cannot type hook function dynamically\n hooks[hooksProp] = (...args: unknown[]) => {\n if (this.defaults.async) {\n return (async() => {\n let ret = await hooksFunc.apply(hooks, args);\n if (ret === false) {\n ret = await prevHook.apply(hooks, args);\n }\n return ret;\n })();\n }\n\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\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: MaybePromise[] = [];\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\n this.defaults = { ...this.defaults, ...opts };\n });\n\n return this;\n }\n\n setOptions(opt: MarkedOptions) {\n this.defaults = { ...this.defaults, ...opt };\n return this;\n }\n\n lexer(src: string, options?: MarkedOptions) {\n return _Lexer.lex(src, options ?? this.defaults);\n }\n\n parser(tokens: Token[], options?: MarkedOptions) {\n return _Parser.parse(tokens, options ?? this.defaults);\n }\n\n private parseMarkdown(blockType: boolean) {\n type overloadedParse = {\n (src: string, options: MarkedOptions & { async: true }): Promise;\n (src: string, options: MarkedOptions & { async: false }): ParserOutput;\n (src: string, options?: MarkedOptions | null): ParserOutput | Promise;\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const parse: overloadedParse = (src: string, options?: MarkedOptions | null): any => {\n const origOpt = { ...options };\n const opt = { ...this.defaults, ...origOpt };\n\n const throwError = this.onError(!!opt.silent, !!opt.async);\n\n // throw error if an extension set async to true but parse was called with async: false\n if (this.defaults.async === true && origOpt.async === false) {\n return throwError(new Error('marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.'));\n }\n\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\n if (opt.hooks) {\n opt.hooks.options = opt;\n opt.hooks.block = blockType;\n }\n\n if (opt.async) {\n return (async() => {\n const processedSrc = opt.hooks ? await opt.hooks.preprocess(src) : src;\n const lexer = opt.hooks ? await opt.hooks.provideLexer(blockType) : (blockType ? _Lexer.lex : _Lexer.lexInline);\n const tokens = await lexer(processedSrc, opt);\n const processedTokens = opt.hooks ? await opt.hooks.processAllTokens(tokens) : tokens;\n if (opt.walkTokens) {\n await Promise.all(this.walkTokens(processedTokens, opt.walkTokens));\n }\n const parser = opt.hooks ? await opt.hooks.provideParser(blockType) : (blockType ? _Parser.parse : _Parser.parseInline);\n const html = await parser(processedTokens, opt);\n return opt.hooks ? await opt.hooks.postprocess(html) : html;\n })().catch(throwError);\n }\n\n try {\n if (opt.hooks) {\n src = opt.hooks.preprocess(src) as string;\n }\n const lexer = opt.hooks ? opt.hooks.provideLexer(blockType) : (blockType ? _Lexer.lex : _Lexer.lexInline);\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 const parser = opt.hooks ? opt.hooks.provideParser(blockType) : (blockType ? _Parser.parse : _Parser.parseInline);\n let html = parser(tokens, opt);\n if (opt.hooks) {\n html = opt.hooks.postprocess(html);\n }\n return html;\n } catch(e) {\n return throwError(e as Error);\n }\n };\n\n return parse;\n }\n\n private onError(silent: boolean, async: boolean) {\n return (e: Error): string | Promise => {\n e.message += '\\nPlease report this to https://github.com/markedjs/marked.';\n\n if (silent) {\n const msg = '

    An error occurred:

    '\n          + escapeHtmlEntities(e.message + '', true)\n          + '
    ';\n if (async) {\n return Promise.resolve(msg);\n }\n return msg;\n }\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 {\n _getDefaults,\n changeDefaults,\n _defaults,\n} from './defaults.ts';\nimport type { MarkedExtension, MarkedOptions } from './MarkedOptions.ts';\nimport type { Token, TokensList } from './Tokens.ts';\nimport type { MaybePromise } from './Instance.ts';\n\nconst markedInstance = new Marked();\n\n/**\n * Compiles markdown to HTML asynchronously.\n *\n * @param src String of markdown source to be compiled\n * @param options Hash of options, having async: true\n * @return Promise of string of compiled HTML\n */\nexport function marked(src: string, options: MarkedOptions & { async: true }): Promise;\n\n/**\n * Compiles markdown to HTML.\n *\n * @param src String of markdown source to be compiled\n * @param options Optional hash of options\n * @return String of compiled HTML. Will be a Promise of string if async is set to true by any extensions.\n */\nexport function marked(src: string, options: MarkedOptions & { async: false }): string;\nexport function marked(src: string, options: MarkedOptions & { async: true }): Promise;\nexport function marked(src: string, options?: MarkedOptions | null): string | Promise;\nexport function marked(src: string, opt?: MarkedOptions | null): string | Promise {\n return markedInstance.parse(src, opt);\n}\n\n/**\n * Sets the default options.\n *\n * @param options Hash of options\n */\nmarked.options =\n marked.setOptions = function(options: MarkedOptions) {\n markedInstance.setOptions(options);\n marked.defaults = markedInstance.defaults;\n changeDefaults(marked.defaults);\n return marked;\n };\n\n/**\n * Gets the original marked default options.\n */\nmarked.getDefaults = _getDefaults;\n\nmarked.defaults = _defaults;\n\n/**\n * Use Extension\n */\n\nmarked.use = function(...args: MarkedExtension[]) {\n markedInstance.use(...args);\n marked.defaults = markedInstance.defaults;\n changeDefaults(marked.defaults);\n return marked;\n};\n\n/**\n * Run callback for every token\n */\n\nmarked.walkTokens = function(tokens: Token[] | TokensList, callback: (token: Token) => MaybePromise | MaybePromise[]) {\n return markedInstance.walkTokens(tokens, callback);\n};\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/**\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;\n\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';\nexport type * from './MarkedOptions.ts';\nexport type * from './Tokens.ts';\n"], + "mappings": ";;;;;;;;;;;;AAKO,SAASA,GAA4G,CAC1H,MAAO,CACL,MAAO,GACP,OAAQ,GACR,WAAY,KACZ,IAAK,GACL,MAAO,KACP,SAAU,GACV,SAAU,KACV,OAAQ,GACR,UAAW,KACX,WAAY,IACd,CACF,CAEO,IAAIC,EAAqCD,EAAa,EAEtD,SAASE,EAA+DC,EAA0D,CACvIF,EAAYE,CACd,CCxBA,IAAMC,EAAW,CAAE,KAAM,IAAM,IAAK,EAEpC,SAASC,EAAKC,EAAwBC,EAAM,GAAI,CAC9C,IAAIC,EAAS,OAAOF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,EAAeJ,EAAO,QAAQ,EACvBA,CACT,EAMAA,EAAO,WAAa,SAASQ,EAA8BC,EAA2D,CACpH,OAAOX,EAAe,WAAWU,EAAQC,CAAQ,CACnD,EASAT,EAAO,YAAcF,EAAe,YAKpCE,EAAO,OAASU,EAChBV,EAAO,OAASU,EAAQ,MACxBV,EAAO,SAAWW,EAClBX,EAAO,aAAeY,EACtBZ,EAAO,MAAQa,EACfb,EAAO,MAAQa,EAAO,IACtBb,EAAO,UAAYc,EACnBd,EAAO,MAAQe,EACff,EAAO,MAAQA,EAER,IAAMG,GAAUH,EAAO,QACjBgB,GAAahB,EAAO,WACpBiB,GAAMjB,EAAO,IACbkB,GAAalB,EAAO,WACpBmB,GAAcnB,EAAO,YACrBoB,GAAQpB,EACRqB,GAASX,EAAQ,MACjBY,GAAQT,EAAO", + "names": ["_getDefaults", "_defaults", "changeDefaults", "newDefaults", "noopTest", "edit", "regex", "opt", "source", "obj", "name", "val", "valSource", "other", "supportsLookbehind", "bull", "indent", "newline", "blockCode", "fences", "hr", "heading", "bullet", "lheadingCore", "lheading", "lheadingGfm", "_paragraph", "blockText", "_blockLabel", "def", "list", "_tag", "_comment", "html", "paragraph", "blockquote", "blockNormal", "gfmTable", "blockGfm", "blockPedantic", "escape", "inlineCode", "br", "inlineText", "_punctuation", "_punctuationOrSpace", "_notPunctuationOrSpace", "punctuation", "_punctuationGfmStrongEm", "_punctuationOrSpaceGfmStrongEm", "_notPunctuationOrSpaceGfmStrongEm", "blockSkip", "emStrongLDelimCore", "emStrongLDelim", "emStrongLDelimGfm", "emStrongRDelimAstCore", "emStrongRDelimAst", "emStrongRDelimAstGfm", "emStrongRDelimUnd", "delLDelim", "delRDelimCore", "delRDelim", "anyPunctuation", "autolink", "_inlineComment", "tag", "_inlineLabel", "link", "reflink", "nolink", "reflinkSearch", "_caseInsensitiveProtocol", "inlineNormal", "inlinePedantic", "inlineGfm", "inlineBreaks", "block", "inline", "escapeReplacements", "getEscapeReplacement", "ch", "escapeHtmlEntities", "html", "encode", "other", "cleanUrl", "href", "splitCells", "tableRow", "count", "row", "match", "offset", "str", "escaped", "curr", "cells", "i", "rtrim", "c", "invert", "l", "suffLen", "currChar", "trimTrailingBlankLines", "lines", "end", "findClosingBracket", "b", "level", "expandTabs", "line", "indent", "col", "expanded", "char", "added", "outputLink", "cap", "link", "raw", "lexer", "rules", "href", "title", "text", "token", "indentCodeCompensation", "matchIndentToCode", "indentToCode", "node", "matchIndentInNode", "indentInNode", "_Tokenizer", "options", "_defaults", "src", "trimTrailingBlankLines", "trimmed", "rtrim", "lines", "tokens", "inBlockquote", "currentLines", "i", "currentRaw", "currentText", "top", "lastToken", "oldToken", "newText", "newToken", "bull", "isordered", "list", "itemRegex", "endsWithBlankLine", "endEarly", "itemContents", "line", "expandTabs", "nextLine", "blankLine", "indent", "nextBulletRegex", "hrRegex", "fencesBeginRegex", "headingBeginRegex", "htmlBeginRegex", "blockquoteBeginRegex", "rawLine", "nextLineWithoutTabs", "lastItem", "item", "taskRaw", "checkboxToken", "spacers", "t", "hasMultipleLineBreaks", "tag", "headers", "splitCells", "aligns", "rows", "align", "row", "cell", "trimmedUrl", "rtrimSlash", "lastParenIndex", "findClosingBracket", "linkLen", "links", "linkString", "maskedSrc", "prevChar", "match", "lLength", "rDelim", "rLength", "delimTotal", "midDelimTotal", "endReg", "lastCharLength", "hasNonSpaceChars", "hasSpaceCharsOnBothEnds", "prevCapZero", "escaped", "_Lexer", "__Lexer", "options", "_defaults", "_Tokenizer", "rules", "other", "block", "inline", "src", "i", "next", "tokens", "lastParagraphClipped", "token", "extTokenizer", "lastToken", "cutSrc", "startIndex", "tempSrc", "tempStart", "getStartIndex", "errMsg", "maskedSrc", "match", "links", "offset", "keepPrevChar", "prevChar", "_Renderer", "options", "_defaults", "token", "text", "lang", "escaped", "langString", "other", "code", "escapeHtmlEntities", "tokens", "depth", "ordered", "start", "body", "j", "item", "type", "startAttr", "checked", "header", "cell", "row", "k", "content", "href", "title", "cleanHref", "cleanUrl", "out", "_TextRenderer", "text", "raw", "_Parser", "__Parser", "options", "_defaults", "_Renderer", "_TextRenderer", "tokens", "out", "i", "anyToken", "genericToken", "ret", "token", "errMsg", "renderer", "_Hooks", "options", "_defaults", "markdown", "html", "tokens", "src", "block", "_Lexer", "_Parser", "Marked", "_getDefaults", "_Parser", "_Renderer", "_TextRenderer", "_Lexer", "_Tokenizer", "_Hooks", "args", "tokens", "callback", "values", "token", "tableToken", "cell", "row", "listToken", "genericToken", "childTokens", "extensions", "pack", "opts", "ext", "prevRenderer", "ret", "extLevel", "renderer", "prop", "rendererProp", "rendererFunc", "tokenizer", "tokenizerProp", "tokenizerFunc", "prevTokenizer", "hooks", "hooksProp", "hooksFunc", "prevHook", "arg", "walkTokens", "packWalktokens", "opt", "src", "options", "blockType", "origOpt", "throwError", "processedSrc", "processedTokens", "html", "e", "silent", "async", "msg", "escapeHtmlEntities", "markedInstance", "Marked", "marked", "src", "opt", "options", "changeDefaults", "_getDefaults", "_defaults", "args", "tokens", "callback", "_Parser", "_Renderer", "_TextRenderer", "_Lexer", "_Tokenizer", "_Hooks", "setOptions", "use", "walkTokens", "parseInline", "parse", "parser", "lexer"] +} diff --git a/node_modules/marked/lib/marked.umd.js b/node_modules/marked/lib/marked.umd.js new file mode 100644 index 0000000..f3dd360 --- /dev/null +++ b/node_modules/marked/lib/marked.umd.js @@ -0,0 +1,79 @@ +/** + * marked v18.0.0 - a markdown parser + * Copyright (c) 2018-2026, MarkedJS. (MIT License) + * Copyright (c) 2011-2018, Christopher Jeffrey. (MIT License) + * https://github.com/markedjs/marked + */ + +/** + * DO NOT EDIT THIS FILE + * The code in this file is generated from files in ./src/ + */ +(function(g,f){if(typeof exports=="object"&&typeof module<"u"){module.exports=f()}else if("function"==typeof define && define.amd){define("marked",f)}else {g["marked"]=f()}}(typeof globalThis < "u" ? globalThis : typeof self < "u" ? self : this,function(){var exports={};var __exports=exports;var module={exports}; +"use strict";var G=Object.defineProperty;var Te=Object.getOwnPropertyDescriptor;var Oe=Object.getOwnPropertyNames;var we=Object.prototype.hasOwnProperty;var ye=(l,e)=>{for(var t in e)G(l,t,{get:e[t],enumerable:!0})},Pe=(l,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Oe(e))!we.call(l,r)&&r!==t&&G(l,r,{get:()=>e[r],enumerable:!(n=Te(e,r))||n.enumerable});return l};var Se=l=>Pe(G({},"__esModule",{value:!0}),l);var bt={};ye(bt,{Hooks:()=>P,Lexer:()=>x,Marked:()=>A,Parser:()=>b,Renderer:()=>y,TextRenderer:()=>S,Tokenizer:()=>w,defaults:()=>R,getDefaults:()=>_,lexer:()=>xt,marked:()=>g,options:()=>ct,parse:()=>ft,parseInline:()=>gt,parser:()=>mt,setOptions:()=>ht,use:()=>kt,walkTokens:()=>dt});module.exports=Se(bt);function _(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var R=_();function N(l){R=l}var M={exec:()=>null};function k(l,e=""){let t=typeof l=="string"?l:l.source,n={replace:(r,i)=>{let s=typeof i=="string"?i:i.source;return s=s.replace(m.caret,"$1"),t=t.replace(r,s),n},getRegex:()=>new RegExp(t,e)};return n}var $e=(()=>{try{return!!new RegExp("(?<=1)(?/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^
    /i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:l=>new RegExp(`^( {0,3}${l})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:l=>new RegExp(`^ {0,${Math.min(3,l-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:l=>new RegExp(`^ {0,${Math.min(3,l-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:l=>new RegExp(`^ {0,${Math.min(3,l-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:l=>new RegExp(`^ {0,${Math.min(3,l-1)}}#`),htmlBeginRegex:l=>new RegExp(`^ {0,${Math.min(3,l-1)}}<(?:[a-z].*>|!--)`,"i"),blockquoteBeginRegex:l=>new RegExp(`^ {0,${Math.min(3,l-1)}}>`)},Le=/^(?:[ \t]*(?:\n|$))+/,_e=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Me=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,B=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,ze=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,j=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,oe=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ae=k(oe).replace(/bull/g,j).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).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/).replace(/\|table/g,"").getRegex(),Ee=k(oe).replace(/bull/g,j).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).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/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),F=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Ie=/^[^\n]+/,U=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Ae=k(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",U).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Ce=k(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,j).getRegex(),v="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",K=/|$))/,Be=k("^ {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",K).replace("tag",v).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),le=k(F).replace("hr",B).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[.)])[ \\t]").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",v).getRegex(),De=k(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",le).getRegex(),W={blockquote:De,code:_e,def:Ae,fences:Me,heading:ze,hr:B,html:Be,lheading:ae,list:Ce,newline:Le,paragraph:le,table:M,text:Ie},se=k("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",B).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",v).getRegex(),qe={...W,lheading:Ee,table:se,paragraph:k(F).replace("hr",B).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",se).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",v).getRegex()},ve={...W,html:k(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",K).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:M,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:k(F).replace("hr",B).replace("heading",` *#{1,6} *[^ +]`).replace("lheading",ae).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},He=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Ze=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,ue=/^( {2,}|\\)\n(?!\s*$)/,Ge=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\`+)[^`]+\k(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",$e?"(?`+)[^`]+\k(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),ce=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Ue=k(ce,"u").replace(/punct/g,E).getRegex(),Ke=k(ce,"u").replace(/punct/g,pe).getRegex(),he="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",We=k(he,"gu").replace(/notPunctSpace/g,X).replace(/punctSpace/g,H).replace(/punct/g,E).getRegex(),Xe=k(he,"gu").replace(/notPunctSpace/g,je).replace(/punctSpace/g,Qe).replace(/punct/g,pe).getRegex(),Je=k("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,X).replace(/punctSpace/g,H).replace(/punct/g,E).getRegex(),Ve=k(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,E).getRegex(),Ye="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",et=k(Ye,"gu").replace(/notPunctSpace/g,X).replace(/punctSpace/g,H).replace(/punct/g,E).getRegex(),tt=k(/\\(punct)/,"gu").replace(/punct/g,E).getRegex(),nt=k(/^<(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(),rt=k(K).replace("(?:-->|$)","-->").getRegex(),st=k("^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment",rt).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),q=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,it=k(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",q).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),ke=k(/^!?\[(label)\]\[(ref)\]/).replace("label",q).replace("ref",U).getRegex(),de=k(/^!?\[(ref)\](?:\[\])?/).replace("ref",U).getRegex(),ot=k("reflink|nolink(?!\\()","g").replace("reflink",ke).replace("nolink",de).getRegex(),ie=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,J={_backpedal:M,anyPunctuation:tt,autolink:nt,blockSkip:Fe,br:ue,code:Ze,del:M,delLDelim:M,delRDelim:M,emStrongLDelim:Ue,emStrongRDelimAst:We,emStrongRDelimUnd:Je,escape:He,link:it,nolink:de,punctuation:Ne,reflink:ke,reflinkSearch:ot,tag:st,text:Ge,url:M},at={...J,link:k(/^!?\[(label)\]\((.*?)\)/).replace("label",q).getRegex(),reflink:k(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",q).getRegex()},Q={...J,emStrongRDelimAst:Xe,emStrongLDelim:Ke,delLDelim:Ve,delRDelim:et,url:k(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",ie).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\S]|[^\s~\\]))\1(?=[^~]|$)/,text:k(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\":">",'"':""","'":"'"},ge=l=>ut[l];function O(l,e){if(e){if(m.escapeTest.test(l))return l.replace(m.escapeReplace,ge)}else if(m.escapeTestNoEncode.test(l))return l.replace(m.escapeReplaceNoEncode,ge);return l}function V(l){try{l=encodeURI(l).replace(m.percentDecode,"%")}catch{return null}return l}function Y(l,e){let t=l.replace(m.findPipe,(i,s,a)=>{let o=!1,u=s;for(;--u>=0&&a[u]==="\\";)o=!o;return o?"|":" |"}),n=t.split(m.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length=0&&!e[t].trim();)t--;return e.length-t<=2?l:e.slice(0,t+1).join(` +`)}function fe(l,e){if(l.indexOf(e[1])===-1)return-1;let t=0;for(let n=0;n0?-2:-1}function me(l,e=0){let t=e,n="";for(let r of l)if(r===" "){let i=4-t%4;n+=" ".repeat(i),t+=i}else n+=r,t++;return n}function xe(l,e,t,n,r){let i=e.href,s=e.title||null,a=l[1].replace(r.other.outputLinkReplace,"$1");n.state.inLink=!0;let o={type:l[0].charAt(0)==="!"?"image":"link",raw:t,href:i,title:s,text:a,tokens:n.inlineTokens(a)};return n.state.inLink=!1,o}function pt(l,e,t){let n=l.match(t.other.indentCodeCompensation);if(n===null)return e;let r=n[1];return e.split(` +`).map(i=>{let s=i.match(t.other.beginningSpace);if(s===null)return i;let[a]=s;return a.length>=r.length?i.slice(r.length):i}).join(` +`)}var w=class{options;rules;lexer;constructor(e){this.options=e||R}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=this.options.pedantic?t[0]:ee(t[0]),r=n.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:n,codeBlockStyle:"indented",text:r}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],r=pt(n,t[3]||"",this.rules);return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:r}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.rules.other.endingHash.test(n)){let r=L(n,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(n=r.trim())}return{type:"heading",raw:L(t[0],` +`),depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:L(t[0],` +`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=L(t[0],` +`).split(` +`),r="",i="",s=[];for(;n.length>0;){let a=!1,o=[],u;for(u=0;u1,i={type:"list",raw:"",ordered:r,start:r?+n.slice(0,-1):"",loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:"[*+-]");let s=this.rules.other.listItemRegex(n),a=!1;for(;e;){let u=!1,p="",c="";if(!(t=s.exec(e))||this.rules.block.hr.test(e))break;p=t[0],e=e.substring(p.length);let d=me(t[2].split(` +`,1)[0],t[1].length),h=e.split(` +`,1)[0],T=!d.trim(),f=0;if(this.options.pedantic?(f=2,c=d.trimStart()):T?f=t[1].length+1:(f=d.search(this.rules.other.nonSpaceChar),f=f>4?1:f,c=d.slice(f),f+=t[1].length),T&&this.rules.other.blankLine.test(h)&&(p+=h+` +`,e=e.substring(h.length+1),u=!0),!u){let $=this.rules.other.nextBulletRegex(f),te=this.rules.other.hrRegex(f),ne=this.rules.other.fencesBeginRegex(f),re=this.rules.other.headingBeginRegex(f),be=this.rules.other.htmlBeginRegex(f),Re=this.rules.other.blockquoteBeginRegex(f);for(;e;){let Z=e.split(` +`,1)[0],C;if(h=Z,this.options.pedantic?(h=h.replace(this.rules.other.listReplaceNesting," "),C=h):C=h.replace(this.rules.other.tabCharGlobal," "),ne.test(h)||re.test(h)||be.test(h)||Re.test(h)||$.test(h)||te.test(h))break;if(C.search(this.rules.other.nonSpaceChar)>=f||!h.trim())c+=` +`+C.slice(f);else{if(T||d.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||ne.test(d)||re.test(d)||te.test(d))break;c+=` +`+h}T=!h.trim(),p+=Z+` +`,e=e.substring(Z.length+1),d=C.slice(f)}}i.loose||(a?i.loose=!0:this.rules.other.doubleBlankLine.test(p)&&(a=!0)),i.items.push({type:"list_item",raw:p,task:!!this.options.gfm&&this.rules.other.listIsTask.test(c),loose:!1,text:c,tokens:[]}),i.raw+=p}let o=i.items.at(-1);if(o)o.raw=o.raw.trimEnd(),o.text=o.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let u of i.items){if(this.lexer.state.top=!1,u.tokens=this.lexer.blockTokens(u.text,[]),u.task){if(u.text=u.text.replace(this.rules.other.listReplaceTask,""),u.tokens[0]?.type==="text"||u.tokens[0]?.type==="paragraph"){u.tokens[0].raw=u.tokens[0].raw.replace(this.rules.other.listReplaceTask,""),u.tokens[0].text=u.tokens[0].text.replace(this.rules.other.listReplaceTask,"");for(let c=this.lexer.inlineQueue.length-1;c>=0;c--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[c].src)){this.lexer.inlineQueue[c].src=this.lexer.inlineQueue[c].src.replace(this.rules.other.listReplaceTask,"");break}}let p=this.rules.other.listTaskCheckbox.exec(u.raw);if(p){let c={type:"checkbox",raw:p[0]+" ",checked:p[0]!=="[ ]"};u.checked=c.checked,i.loose?u.tokens[0]&&["paragraph","text"].includes(u.tokens[0].type)&&"tokens"in u.tokens[0]&&u.tokens[0].tokens?(u.tokens[0].raw=c.raw+u.tokens[0].raw,u.tokens[0].text=c.raw+u.tokens[0].text,u.tokens[0].tokens.unshift(c)):u.tokens.unshift({type:"paragraph",raw:c.raw,text:c.raw,tokens:[c]}):u.tokens.unshift(c)}}if(!i.loose){let p=u.tokens.filter(d=>d.type==="space"),c=p.length>0&&p.some(d=>this.rules.other.anyLine.test(d.raw));i.loose=c}}if(i.loose)for(let u of i.items){u.loose=!0;for(let p of u.tokens)p.type==="text"&&(p.type="paragraph")}return i}}html(e){let t=this.rules.block.html.exec(e);if(t){let n=ee(t[0]);return{type:"html",block:!0,raw:n,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:n}}}def(e){let t=this.rules.block.def.exec(e);if(t){let n=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),r=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",i=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:n,raw:L(t[0],` +`),href:r,title:i}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=Y(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(` +`):[],s={type:"table",raw:L(t[0],` +`),header:[],align:[],rows:[]};if(n.length===r.length){for(let a of r)this.rules.other.tableAlignRight.test(a)?s.align.push("right"):this.rules.other.tableAlignCenter.test(a)?s.align.push("center"):this.rules.other.tableAlignLeft.test(a)?s.align.push("left"):s.align.push(null);for(let a=0;a({text:o,tokens:this.lexer.inline(o),header:!1,align:s.align[u]})));return s}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let n=t[1].trim();return{type:"heading",raw:L(t[0],` +`),depth:t[2].charAt(0)==="="?1:2,text:n,tokens:this.lexer.inline(n)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===` +`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let 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){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.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){let t=this.rules.inline.link.exec(e);if(t){let n=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let s=L(n.slice(0,-1),"\\");if((n.length-s.length)%2===0)return}else{let s=fe(t[2],"()");if(s===-2)return;if(s>-1){let o=(t[0].indexOf("!")===0?5:4)+t[1].length+s;t[2]=t[2].substring(0,s),t[0]=t[0].substring(0,o).trim(),t[3]=""}}let r=t[2],i="";if(this.options.pedantic){let s=this.rules.other.pedanticHrefTitle.exec(r);s&&(r=s[1],i=s[3])}else i=t[3]?t[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?r=r.slice(1):r=r.slice(1,-1)),xe(t,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:i&&i.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let r=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),i=t[r.toLowerCase()];if(!i){let s=n[0].charAt(0);return{type:"text",raw:s,text:s}}return xe(n,i,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let r=this.rules.inline.emStrongLDelim.exec(e);if(!r||!r[1]&&!r[2]&&!r[3]&&!r[4]||r[4]&&n.match(this.rules.other.unicodeAlphaNumeric))return;if(!(r[1]||r[3]||"")||!n||this.rules.inline.punctuation.exec(n)){let s=[...r[0]].length-1,a,o,u=s,p=0,c=r[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,t=t.slice(-1*e.length+s);(r=c.exec(t))!==null;){if(a=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!a)continue;if(o=[...a].length,r[3]||r[4]){u+=o;continue}else if((r[5]||r[6])&&s%3&&!((s+o)%3)){p+=o;continue}if(u-=o,u>0)continue;o=Math.min(o,o+u+p);let d=[...r[0]][0].length,h=e.slice(0,s+r.index+d+o);if(Math.min(s,o)%2){let f=h.slice(1,-1);return{type:"em",raw:h,text:f,tokens:this.lexer.inlineTokens(f)}}let T=h.slice(2,-2);return{type:"strong",raw:h,text:T,tokens:this.lexer.inlineTokens(T)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),r=this.rules.other.nonSpaceChar.test(n),i=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return r&&i&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,n=""){let r=this.rules.inline.delLDelim.exec(e);if(!r)return;if(!(r[1]||"")||!n||this.rules.inline.punctuation.exec(n)){let s=[...r[0]].length-1,a,o,u=s,p=this.rules.inline.delRDelim;for(p.lastIndex=0,t=t.slice(-1*e.length+s);(r=p.exec(t))!==null;){if(a=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!a||(o=[...a].length,o!==s))continue;if(r[3]||r[4]){u+=o;continue}if(u-=o,u>0)continue;o=Math.min(o,o+u);let c=[...r[0]][0].length,d=e.slice(0,s+r.index+c+o),h=d.slice(s,-s);return{type:"del",raw:d,text:h,tokens:this.lexer.inlineTokens(h)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,r;return t[2]==="@"?(n=t[1],r="mailto:"+n):(n=t[1],r=n),{type:"link",raw:t[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let n,r;if(t[2]==="@")n=t[0],r="mailto:"+n;else{let i;do i=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(i!==t[0]);n=t[0],t[1]==="www."?r="http://"+t[0]:r=t[0]}return{type:"link",raw:t[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:n}}}};var x=class l{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||R,this.options.tokenizer=this.options.tokenizer||new w,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={other:m,block:D.normal,inline:I.normal};this.options.pedantic?(t.block=D.pedantic,t.inline=I.pedantic):this.options.gfm&&(t.block=D.gfm,this.options.breaks?t.inline=I.breaks:t.inline=I.gfm),this.tokenizer.rules=t}static get rules(){return{block:D,inline:I}}static lex(e,t){return new l(t).lex(e)}static lexInline(e,t){return new l(t).inlineTokens(e)}lex(e){e=e.replace(m.carriageReturn,` +`),this.blockTokens(e,this.tokens);for(let t=0;t(r=s.call({lexer:this},e,t))?(e=e.substring(r.raw.length),t.push(r),!0):!1))continue;if(r=this.tokenizer.space(e)){e=e.substring(r.raw.length);let s=t.at(-1);r.raw.length===1&&s!==void 0?s.raw+=` +`:t.push(r);continue}if(r=this.tokenizer.code(e)){e=e.substring(r.raw.length);let s=t.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(` +`)?"":` +`)+r.raw,s.text+=` +`+r.text,this.inlineQueue.at(-1).src=s.text):t.push(r);continue}if(r=this.tokenizer.fences(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.heading(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.hr(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.blockquote(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.list(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.html(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.def(e)){e=e.substring(r.raw.length);let s=t.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(` +`)?"":` +`)+r.raw,s.text+=` +`+r.raw,this.inlineQueue.at(-1).src=s.text):this.tokens.links[r.tag]||(this.tokens.links[r.tag]={href:r.href,title:r.title},t.push(r));continue}if(r=this.tokenizer.table(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.lheading(e)){e=e.substring(r.raw.length),t.push(r);continue}let i=e;if(this.options.extensions?.startBlock){let s=1/0,a=e.slice(1),o;this.options.extensions.startBlock.forEach(u=>{o=u.call({lexer:this},a),typeof o=="number"&&o>=0&&(s=Math.min(s,o))}),s<1/0&&s>=0&&(i=e.substring(0,s+1))}if(this.state.top&&(r=this.tokenizer.paragraph(i))){let s=t.at(-1);n&&s?.type==="paragraph"?(s.raw+=(s.raw.endsWith(` +`)?"":` +`)+r.raw,s.text+=` +`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):t.push(r),n=i.length!==e.length,e=e.substring(r.raw.length);continue}if(r=this.tokenizer.text(e)){e=e.substring(r.raw.length);let s=t.at(-1);s?.type==="text"?(s.raw+=(s.raw.endsWith(` +`)?"":` +`)+r.raw,s.text+=` +`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):t.push(r);continue}if(e){let s="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(s);break}else throw new Error(s)}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){this.tokenizer.lexer=this;let n=e,r=null;if(this.tokens.links){let o=Object.keys(this.tokens.links);if(o.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(n))!==null;)o.includes(r[0].slice(r[0].lastIndexOf("[")+1,-1))&&(n=n.slice(0,r.index)+"["+"a".repeat(r[0].length-2)+"]"+n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(n))!==null;)n=n.slice(0,r.index)+"++"+n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let i;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(n))!==null;)i=r[2]?r[2].length:0,n=n.slice(0,r.index+i)+"["+"a".repeat(r[0].length-i-2)+"]"+n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let s=!1,a="";for(;e;){s||(a=""),s=!1;let o;if(this.options.extensions?.inline?.some(p=>(o=p.call({lexer:this},e,t))?(e=e.substring(o.raw.length),t.push(o),!0):!1))continue;if(o=this.tokenizer.escape(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.tag(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.link(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(o.raw.length);let p=t.at(-1);o.type==="text"&&p?.type==="text"?(p.raw+=o.raw,p.text+=o.text):t.push(o);continue}if(o=this.tokenizer.emStrong(e,n,a)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.codespan(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.br(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.del(e,n,a)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.autolink(e)){e=e.substring(o.raw.length),t.push(o);continue}if(!this.state.inLink&&(o=this.tokenizer.url(e))){e=e.substring(o.raw.length),t.push(o);continue}let u=e;if(this.options.extensions?.startInline){let p=1/0,c=e.slice(1),d;this.options.extensions.startInline.forEach(h=>{d=h.call({lexer:this},c),typeof d=="number"&&d>=0&&(p=Math.min(p,d))}),p<1/0&&p>=0&&(u=e.substring(0,p+1))}if(o=this.tokenizer.inlineText(u)){e=e.substring(o.raw.length),o.raw.slice(-1)!=="_"&&(a=o.raw.slice(-1)),s=!0;let p=t.at(-1);p?.type==="text"?(p.raw+=o.raw,p.text+=o.text):t.push(o);continue}if(e){let p="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(p);break}else throw new Error(p)}}return t}};var y=class{options;parser;constructor(e){this.options=e||R}space(e){return""}code({text:e,lang:t,escaped:n}){let r=(t||"").match(m.notSpaceStart)?.[0],i=e.replace(m.endingNewline,"")+` +`;return r?'
    '+(n?i:O(i,!0))+`
    +`:"
    "+(n?i:O(i,!0))+`
    +`}blockquote({tokens:e}){return`
    +${this.parser.parse(e)}
    +`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`${this.parser.parseInline(e)} +`}hr(e){return`
    +`}list(e){let t=e.ordered,n=e.start,r="";for(let a=0;a +`+r+" +`}listitem(e){return`
  • ${this.parser.parse(e.tokens)}
  • +`}checkbox({checked:e}){return" '}paragraph({tokens:e}){return`

    ${this.parser.parseInline(e)}

    +`}table(e){let t="",n="";for(let i=0;i${r}`),` + +`+t+` +`+r+`
    +`}tablerow({text:e}){return` +${e} +`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+` +`}strong({tokens:e}){return`${this.parser.parseInline(e)}`}em({tokens:e}){return`${this.parser.parseInline(e)}`}codespan({text:e}){return`${O(e,!0)}`}br(e){return"
    "}del({tokens:e}){return`${this.parser.parseInline(e)}`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=V(e);if(i===null)return r;e=i;let s='
    ",s}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=V(e);if(i===null)return O(n);e=i;let s=`${O(n)}{let a=i[s].flat(1/0);n=n.concat(this.walkTokens(a,t))}):i.tokens&&(n=n.concat(this.walkTokens(i.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let r={...n};if(r.async=this.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(i=>{if(!i.name)throw new Error("extension name required");if("renderer"in i){let s=t.renderers[i.name];s?t.renderers[i.name]=function(...a){let o=i.renderer.apply(this,a);return o===!1&&(o=s.apply(this,a)),o}:t.renderers[i.name]=i.renderer}if("tokenizer"in i){if(!i.level||i.level!=="block"&&i.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let s=t[i.level];s?s.unshift(i.tokenizer):t[i.level]=[i.tokenizer],i.start&&(i.level==="block"?t.startBlock?t.startBlock.push(i.start):t.startBlock=[i.start]:i.level==="inline"&&(t.startInline?t.startInline.push(i.start):t.startInline=[i.start]))}"childTokens"in i&&i.childTokens&&(t.childTokens[i.name]=i.childTokens)}),r.extensions=t),n.renderer){let i=this.defaults.renderer||new y(this.defaults);for(let s in n.renderer){if(!(s in i))throw new Error(`renderer '${s}' does not exist`);if(["options","parser"].includes(s))continue;let a=s,o=n.renderer[a],u=i[a];i[a]=(...p)=>{let c=o.apply(i,p);return c===!1&&(c=u.apply(i,p)),c||""}}r.renderer=i}if(n.tokenizer){let i=this.defaults.tokenizer||new w(this.defaults);for(let s in n.tokenizer){if(!(s in i))throw new Error(`tokenizer '${s}' does not exist`);if(["options","rules","lexer"].includes(s))continue;let a=s,o=n.tokenizer[a],u=i[a];i[a]=(...p)=>{let c=o.apply(i,p);return c===!1&&(c=u.apply(i,p)),c}}r.tokenizer=i}if(n.hooks){let i=this.defaults.hooks||new P;for(let s in n.hooks){if(!(s in i))throw new Error(`hook '${s}' does not exist`);if(["options","block"].includes(s))continue;let a=s,o=n.hooks[a],u=i[a];P.passThroughHooks.has(s)?i[a]=p=>{if(this.defaults.async&&P.passThroughHooksRespectAsync.has(s))return(async()=>{let d=await o.call(i,p);return u.call(i,d)})();let c=o.call(i,p);return u.call(i,c)}:i[a]=(...p)=>{if(this.defaults.async)return(async()=>{let d=await o.apply(i,p);return d===!1&&(d=await u.apply(i,p)),d})();let c=o.apply(i,p);return c===!1&&(c=u.apply(i,p)),c}}r.hooks=i}if(n.walkTokens){let i=this.defaults.walkTokens,s=n.walkTokens;r.walkTokens=function(a){let o=[];return o.push(s.call(this,a)),i&&(o=o.concat(i.call(this,a))),o}}this.defaults={...this.defaults,...r}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return x.lex(e,t??this.defaults)}parser(e,t){return b.parse(e,t??this.defaults)}parseMarkdown(e){return(n,r)=>{let i={...r},s={...this.defaults,...i},a=this.onError(!!s.silent,!!s.async);if(this.defaults.async===!0&&i.async===!1)return a(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof n>"u"||n===null)return a(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return a(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(s.hooks&&(s.hooks.options=s,s.hooks.block=e),s.async)return(async()=>{let o=s.hooks?await s.hooks.preprocess(n):n,p=await(s.hooks?await s.hooks.provideLexer(e):e?x.lex:x.lexInline)(o,s),c=s.hooks?await s.hooks.processAllTokens(p):p;s.walkTokens&&await Promise.all(this.walkTokens(c,s.walkTokens));let h=await(s.hooks?await s.hooks.provideParser(e):e?b.parse:b.parseInline)(c,s);return s.hooks?await s.hooks.postprocess(h):h})().catch(a);try{s.hooks&&(n=s.hooks.preprocess(n));let u=(s.hooks?s.hooks.provideLexer(e):e?x.lex:x.lexInline)(n,s);s.hooks&&(u=s.hooks.processAllTokens(u)),s.walkTokens&&this.walkTokens(u,s.walkTokens);let c=(s.hooks?s.hooks.provideParser(e):e?b.parse:b.parseInline)(u,s);return s.hooks&&(c=s.hooks.postprocess(c)),c}catch(o){return a(o)}}}onError(e,t){return n=>{if(n.message+=` +Please report this to https://github.com/markedjs/marked.`,e){let r="

    An error occurred:

    "+O(n.message+"",!0)+"
    ";return t?Promise.resolve(r):r}if(t)return Promise.reject(n);throw n}}};var z=new A;function g(l,e){return z.parse(l,e)}g.options=g.setOptions=function(l){return z.setOptions(l),g.defaults=z.defaults,N(g.defaults),g};g.getDefaults=_;g.defaults=R;g.use=function(...l){return z.use(...l),g.defaults=z.defaults,N(g.defaults),g};g.walkTokens=function(l,e){return z.walkTokens(l,e)};g.parseInline=z.parseInline;g.Parser=b;g.parser=b.parse;g.Renderer=y;g.TextRenderer=S;g.Lexer=x;g.lexer=x.lex;g.Tokenizer=w;g.Hooks=P;g.parse=g;var ct=g.options,ht=g.setOptions,kt=g.use,dt=g.walkTokens,gt=g.parseInline,ft=g,mt=b.parse,xt=x.lex; + +if(__exports != exports)module.exports = exports;return module.exports})); +//# sourceMappingURL=marked.umd.js.map diff --git a/node_modules/marked/lib/marked.umd.js.map b/node_modules/marked/lib/marked.umd.js.map new file mode 100644 index 0000000..d9c71bb --- /dev/null +++ b/node_modules/marked/lib/marked.umd.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../src/marked.ts", "../src/defaults.ts", "../src/rules.ts", "../src/helpers.ts", "../src/Tokenizer.ts", "../src/Lexer.ts", "../src/Renderer.ts", "../src/TextRenderer.ts", "../src/Parser.ts", "../src/Hooks.ts", "../src/Instance.ts"], + "sourcesContent": ["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 {\n _getDefaults,\n changeDefaults,\n _defaults,\n} from './defaults.ts';\nimport type { MarkedExtension, MarkedOptions } from './MarkedOptions.ts';\nimport type { Token, TokensList } from './Tokens.ts';\nimport type { MaybePromise } from './Instance.ts';\n\nconst markedInstance = new Marked();\n\n/**\n * Compiles markdown to HTML asynchronously.\n *\n * @param src String of markdown source to be compiled\n * @param options Hash of options, having async: true\n * @return Promise of string of compiled HTML\n */\nexport function marked(src: string, options: MarkedOptions & { async: true }): Promise;\n\n/**\n * Compiles markdown to HTML.\n *\n * @param src String of markdown source to be compiled\n * @param options Optional hash of options\n * @return String of compiled HTML. Will be a Promise of string if async is set to true by any extensions.\n */\nexport function marked(src: string, options: MarkedOptions & { async: false }): string;\nexport function marked(src: string, options: MarkedOptions & { async: true }): Promise;\nexport function marked(src: string, options?: MarkedOptions | null): string | Promise;\nexport function marked(src: string, opt?: MarkedOptions | null): string | Promise {\n return markedInstance.parse(src, opt);\n}\n\n/**\n * Sets the default options.\n *\n * @param options Hash of options\n */\nmarked.options =\n marked.setOptions = function(options: MarkedOptions) {\n markedInstance.setOptions(options);\n marked.defaults = markedInstance.defaults;\n changeDefaults(marked.defaults);\n return marked;\n };\n\n/**\n * Gets the original marked default options.\n */\nmarked.getDefaults = _getDefaults;\n\nmarked.defaults = _defaults;\n\n/**\n * Use Extension\n */\n\nmarked.use = function(...args: MarkedExtension[]) {\n markedInstance.use(...args);\n marked.defaults = markedInstance.defaults;\n changeDefaults(marked.defaults);\n return marked;\n};\n\n/**\n * Run callback for every token\n */\n\nmarked.walkTokens = function(tokens: Token[] | TokensList, callback: (token: Token) => MaybePromise | MaybePromise[]) {\n return markedInstance.walkTokens(tokens, callback);\n};\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/**\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;\n\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';\nexport type * from './MarkedOptions.ts';\nexport type * from './Tokens.ts';\n", "import type { MarkedOptions } from './MarkedOptions.ts';\n\n/**\n * Gets the original marked default options.\n */\nexport function _getDefaults(): MarkedOptions {\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}\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport let _defaults: MarkedOptions = _getDefaults();\n\nexport function changeDefaults(newDefaults: MarkedOptions) {\n _defaults = newDefaults;\n}\n", "const noopTest = { exec: () => null } as unknown as RegExp;\n\nfunction edit(regex: string | RegExp, opt = '') {\n let source = typeof regex === 'string' ? regex : regex.source;\n const obj = {\n replace: (name: string | RegExp, val: string | RegExp) => {\n let valSource = typeof val === 'string' ? val : val.source;\n valSource = valSource.replace(other.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}\n\nconst supportsLookbehind = (() => {\ntry {\n // eslint-disable-next-line prefer-regex-literals\n return !!new RegExp('(?<=1)(?/,\n blockquoteSetextReplace: /\\n {0,3}((?:=+|-+) *)(?=\\n|$)/g,\n blockquoteSetextReplace2: /^ {0,3}>[ \\t]?/gm,\n listReplaceNesting: /^ {1,4}(?=( {4})*[^ ])/g,\n listIsTask: /^\\[[ xX]\\] +\\S/,\n listReplaceTask: /^\\[[ xX]\\] +/,\n listTaskCheckbox: /\\[[ xX]\\]/,\n anyLine: /\\n.*\\n/,\n hrefBrackets: /^<(.*)>$/,\n tableDelimiter: /[:|]/,\n tableAlignChars: /^\\||\\| *$/g,\n tableRowBlankLine: /\\n[ \\t]*$/,\n tableAlignRight: /^ *-+: *$/,\n tableAlignCenter: /^ *:-+: *$/,\n tableAlignLeft: /^ *:-+ *$/,\n startATag: /^
    /i,\n startPreScriptTag: /^<(pre|code|kbd|script)(\\s|>)/i,\n endPreScriptTag: /^<\\/(pre|code|kbd|script)(\\s|>)/i,\n startAngleBracket: /^$/,\n pedanticHrefTitle: /^([^'\"]*[^\\s])\\s+(['\"])(.*)\\2/,\n unicodeAlphaNumeric: /[\\p{L}\\p{N}]/u,\n escapeTest: /[&<>\"']/,\n escapeReplace: /[&<>\"']/g,\n escapeTestNoEncode: /[<>\"']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/,\n escapeReplaceNoEncode: /[<>\"']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/g,\n caret: /(^|[^\\[])\\^/g,\n percentDecode: /%25/g,\n findPipe: /\\|/g,\n splitPipe: / \\|/,\n slashPipe: /\\\\\\|/g,\n carriageReturn: /\\r\\n|\\r/g,\n spaceLine: /^ +$/gm,\n notSpaceStart: /^\\S*/,\n endingNewline: /\\n$/,\n listItemRegex: (bull: string) => new RegExp(`^( {0,3}${bull})((?:[\\t ][^\\\\n]*)?(?:\\\\n|$))`),\n nextBulletRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\\\d{1,9}[.)])((?:[ \\t][^\\\\n]*)?(?:\\\\n|$))`),\n hrRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\\\* *){3,})(?:\\\\n+|$)`),\n fencesBeginRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\\`\\`\\`|~~~)`),\n headingBeginRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`),\n htmlBeginRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}<(?:[a-z].*>|!--)`, 'i'),\n blockquoteBeginRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}>`),\n};\n\n/**\n * Block-Level Grammar\n */\n\nconst newline = /^(?:[ \\t]*(?:\\n|$))+/;\nconst blockCode = /^((?: {4}| {0,3}\\t)[^\\n]+(?:\\n(?:[ \\t]*(?:\\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 = / {0,3}(?:[*+-]|\\d{1,9}[.)])/;\nconst lheadingCore = /^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\\n(?!\\s*?\\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/;\nconst lheading = edit(lheadingCore)\n .replace(/bull/g, bullet) // lists can interrupt\n .replace(/blockCode/g, /(?: {4}| {0,3}\\t)/) // 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 .replace(/\\|table/g, '') // table not in commonmark\n .getRegex();\nconst lheadingGfm = edit(lheadingCore)\n .replace(/bull/g, bullet) // lists can interrupt\n .replace(/blockCode/g, /(?: {4}| {0,3}\\t)/) // 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 .replace(/table/g, / {0,3}\\|?(?:[:\\- ]*\\|)+[\\:\\- ]*\\n/) // table can interrupt\n .getRegex();\nconst _paragraph = /^([^\\n]+(?:\\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\\n)[^\\n]+)*)/;\nconst blockText = /^[^\\n]+/;\nconst _blockLabel = /(?!\\s*\\])(?:\\\\[\\s\\S]|[^\\[\\]\\\\])+/;\nconst def = edit(/^ {0,3}\\[(label)\\]: *(?:\\n[ \\t]*)?([^<\\s][^\\s]*|<.*?>)(?:(?: +(?:\\n[ \\t]*)?| *\\n[ \\t]*)(title))? *(?:\\n+|$)/)\n .replace('label', _blockLabel)\n .replace('title', /(?:\"(?:\\\\\"?|[^\"\\\\])*\"|'[^'\\n]*(?:\\n[^'\\n]+)*\\n?'|\\([^()]*\\))/)\n .getRegex();\n\nconst list = edit(/^(bull)([ \\t][^\\n]+?)?(?:\\n|$)/)\n .replace(/bull/g, bullet)\n .getRegex();\n\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(\n '^ {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[ \\t]*)+\\\\n|$)' // (6)\n+ '|<(?!script|pre|style|textarea)([a-z][\\\\w-]*)(?:attribute)*? */?>(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n[ \\t]*)+\\\\n|$)' // (7) open tag\n+ '|(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n[ \\t]*)+\\\\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();\n\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[.)])[ \\\\t]') // 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\nconst blockquote = edit(/^( {0,3}> ?(paragraph|[^\\n]*)(?:\\n|$))+/)\n .replace('paragraph', paragraph)\n .getRegex();\n\n/**\n * Normal Block Grammar\n */\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\ntype BlockKeys = keyof typeof blockNormal;\n\n/**\n * GFM Block Grammar\n */\n\nconst gfmTable = edit(\n '^ *([^\\\\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}| {0,3}\\t)[^\\\\n]')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n')\n .replace('list', ' {0,3}(?:[*+-]|1[.)])[ \\\\t]') // 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();\n\nconst blockGfm: Record = {\n ...blockNormal,\n lheading: lheadingGfm,\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[.)])[ \\\\t]') // 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/**\n * Pedantic grammar (original John Gruber's loose markdown specification)\n */\n\nconst blockPedantic: Record = {\n ...blockNormal,\n html: edit(\n '^ *(?: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/**\n * Inline-Level Grammar\n */\n\nconst escape = /^\\\\([!\"#$%&'()*+,\\-./:;<=>?@\\[\\]\\\\^_`{|}~])/;\nconst inlineCode = /^(`+)([^`]|[^`][\\s\\S]*?[^`])\\1(?!`)/;\nconst br = /^( {2,}|\\\\)\\n(?!\\s*$)/;\nconst inlineText = /^(`+|[^`])(?:(?= {2,}\\n)|[\\s\\S]*?(?:(?=[\\\\\nconst blockSkip = edit(/link|precode-code|html/, 'g')\n .replace('link', /\\[(?:[^\\[\\]`]|(?`+)[^`]+\\k(?!`))*?\\]\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)]|\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)])*\\))*\\)/)\n .replace('precode-', supportsLookbehind ? '(?`+)[^`]+\\k(?!`)/)\n .replace('html', /<(?! )[^<>]*?>/)\n .getRegex();\n\nconst emStrongLDelimCore = /^(?:\\*+(?:((?!\\*)punct)|([^\\s*]))?)|^_+(?:((?!_)punct)|([^\\s_]))?/;\n\nconst emStrongLDelim = edit(emStrongLDelimCore, 'u')\n .replace(/punct/g, _punctuation)\n .getRegex();\n\nconst emStrongLDelimGfm = edit(emStrongLDelimCore, 'u')\n .replace(/punct/g, _punctuationGfmStrongEm)\n .getRegex();\n\nconst emStrongRDelimAstCore =\n '^[^_*]*?__[^_*]*?\\\\*[^_*]*?(?=__)' // Skip orphan inside strong\n+ '|[^*]+(?=[^*])' // Consume to delim\n+ '|(?!\\\\*)punct(\\\\*+)(?=[\\\\s]|$)' // (1) #*** can only be a Right Delimiter\n+ '|notPunctSpace(\\\\*+)(?!\\\\*)(?=punctSpace|$)' // (2) a***#, a*** can only be a Right Delimiter\n+ '|(?!\\\\*)punctSpace(\\\\*+)(?=notPunctSpace)' // (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+ '|notPunctSpace(\\\\*+)(?=notPunctSpace)'; // (6) a***a can be either Left or Right Delimiter\n\nconst emStrongRDelimAst = edit(emStrongRDelimAstCore, 'gu')\n .replace(/notPunctSpace/g, _notPunctuationOrSpace)\n .replace(/punctSpace/g, _punctuationOrSpace)\n .replace(/punct/g, _punctuation)\n .getRegex();\n\nconst emStrongRDelimAstGfm = edit(emStrongRDelimAstCore, 'gu')\n .replace(/notPunctSpace/g, _notPunctuationOrSpaceGfmStrongEm)\n .replace(/punctSpace/g, _punctuationOrSpaceGfmStrongEm)\n .replace(/punct/g, _punctuationGfmStrongEm)\n .getRegex();\n\n// (6) Not allowed for _\nconst emStrongRDelimUnd = edit(\n '^[^_*]*?\\\\*\\\\*[^_*]*?_[^_*]*?(?=\\\\*\\\\*)' // Skip orphan inside strong\n+ '|[^_]+(?=[^_])' // Consume to delim\n+ '|(?!_)punct(_+)(?=[\\\\s]|$)' // (1) #___ can only be a Right Delimiter\n+ '|notPunctSpace(_+)(?!_)(?=punctSpace|$)' // (2) a___#, a___ can only be a Right Delimiter\n+ '|(?!_)punctSpace(_+)(?=notPunctSpace)' // (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(/notPunctSpace/g, _notPunctuationOrSpace)\n .replace(/punctSpace/g, _punctuationOrSpace)\n .replace(/punct/g, _punctuation)\n .getRegex();\n\n// Tilde left delimiter for strikethrough (similar to emStrongLDelim for asterisk)\nconst delLDelim = edit(/^~~?(?:((?!~)punct)|[^\\s~])/, 'u')\n .replace(/punct/g, _punctuation)\n .getRegex();\n\n// Tilde delimiter patterns for strikethrough (similar to asterisk)\nconst delRDelimCore =\n '^[^~]+(?=[^~])' // Consume to delim\n+ '|(?!~)punct(~~?)(?=[\\\\s]|$)' // (1) #~~ can only be a Right Delimiter\n+ '|notPunctSpace(~~?)(?!~)(?=punctSpace|$)' // (2) a~~#, a~~ can only be a Right Delimiter\n+ '|(?!~)punctSpace(~~?)(?=notPunctSpace)' // (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+ '|notPunctSpace(~~?)(?=notPunctSpace)'; // (6) a~~a can be either Left or Right Delimiter\n\nconst delRDelim = edit(delRDelimCore, 'gu')\n .replace(/notPunctSpace/g, _notPunctuationOrSpace)\n .replace(/punctSpace/g, _punctuationOrSpace)\n .replace(/punct/g, _punctuation)\n .getRegex();\n\nconst anyPunctuation = edit(/\\\\(punct)/, 'gu')\n .replace(/punct/g, _punctuation)\n .getRegex();\n\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();\n\nconst _inlineComment = edit(_comment).replace('(?:-->|$)', '-->').getRegex();\nconst tag = edit(\n '^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();\n\nconst _inlineLabel = /(?:\\[(?:\\\\[\\s\\S]|[^\\[\\]\\\\])*\\]|\\\\[\\s\\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\\])|[^\\[\\]\\\\`])*?/;\n\nconst link = edit(/^!?\\[(label)\\]\\(\\s*(href)(?:(?:[ \\t]+(?:\\n[ \\t]*)?|\\n[ \\t]*)(title))?\\s*\\)/)\n .replace('label', _inlineLabel)\n .replace('href', /<(?:\\\\.|[^\\n<>\\\\])+>|[^ \\t\\n\\x00-\\x1f]*/)\n .replace('title', /\"(?:\\\\\"?|[^\"\\\\])*\"|'(?:\\\\'?|[^'\\\\])*'|\\((?:\\\\\\)?|[^)\\\\])*\\)/)\n .getRegex();\n\nconst reflink = edit(/^!?\\[(label)\\]\\[(ref)\\]/)\n .replace('label', _inlineLabel)\n .replace('ref', _blockLabel)\n .getRegex();\n\nconst nolink = edit(/^!?\\[(ref)\\](?:\\[\\])?/)\n .replace('ref', _blockLabel)\n .getRegex();\n\nconst reflinkSearch = edit('reflink|nolink(?!\\\\()', 'g')\n .replace('reflink', reflink)\n .replace('nolink', nolink)\n .getRegex();\n\nconst _caseInsensitiveProtocol = /[hH][tT][tT][pP][sS]?|[fF][tT][pP]/;\n\n/**\n * Normal Inline Grammar\n */\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 delLDelim: noopTest,\n delRDelim: 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\ntype InlineKeys = keyof typeof inlineNormal;\n\n/**\n * Pedantic Inline Grammar\n */\n\nconst inlinePedantic: Record = {\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/**\n * GFM Inline Grammar\n */\n\nconst inlineGfm: Record = {\n ...inlineNormal,\n emStrongRDelimAst: emStrongRDelimAstGfm,\n emStrongLDelim: emStrongLDelimGfm,\n delLDelim,\n delRDelim,\n url: edit(/^((?:protocol):\\/\\/|www\\.)(?:[a-zA-Z0-9\\-]+\\.?)+[^\\s<]*|^email/)\n .replace('protocol', _caseInsensitiveProtocol)\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\\S]|[^\\s~\\\\]))\\1(?=[^~]|$)/,\n text: edit(/^([`~]+|[^`~])(?:(?= {2,}\\n)|(?=[a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-]+@)|[\\s\\S]*?(?:(?=[\\\\ = {\n ...inlineGfm,\n br: edit(br).replace('{2,}', '*').getRegex(),\n text: edit(inlineGfm.text)\n .replace('\\\\b_', '\\\\b_| {2,}\\\\n')\n .replace(/\\{2,\\}/g, '*')\n .getRegex(),\n};\n\n/**\n * exports\n */\n\nexport const block = {\n normal: blockNormal,\n gfm: blockGfm,\n pedantic: blockPedantic,\n};\n\nexport const inline = {\n normal: inlineNormal,\n gfm: inlineGfm,\n breaks: inlineBreaks,\n pedantic: inlinePedantic,\n};\n\nexport interface Rules {\n other: typeof other\n block: Record\n inline: Record\n}\n", "import { other } from './rules.ts';\n\n/**\n * Helpers\n */\nconst escapeReplacements: { [index: string]: string } = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n};\nconst getEscapeReplacement = (ch: string) => escapeReplacements[ch];\n\nexport function escapeHtmlEntities(html: string, encode?: boolean) {\n if (encode) {\n if (other.escapeTest.test(html)) {\n return html.replace(other.escapeReplace, getEscapeReplacement);\n }\n } else {\n if (other.escapeTestNoEncode.test(html)) {\n return html.replace(other.escapeReplaceNoEncode, getEscapeReplacement);\n }\n }\n\n return html;\n}\n\nexport function cleanUrl(href: string) {\n try {\n href = encodeURI(href).replace(other.percentDecode, '%');\n } catch {\n return null;\n }\n return href;\n}\n\nexport function splitCells(tableRow: string, count?: number) {\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(other.findPipe, (match, offset, str) => {\n let escaped = false;\n let curr = offset;\n while (--curr >= 0 && str[curr] === '\\\\') escaped = !escaped;\n if (escaped) {\n // odd number of slashes means | is escaped\n // so we leave it alone\n return '|';\n } else {\n // add space before unescaped |\n return ' |';\n }\n }),\n cells = row.split(other.splitPipe);\n let i = 0;\n\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.at(-1)?.trim()) {\n cells.pop();\n }\n\n if (count) {\n if (cells.length > count) {\n cells.splice(count);\n } else {\n while (cells.length < count) cells.push('');\n }\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(other.slashPipe, '|');\n }\n return cells;\n}\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: string, c: string, invert?: boolean) {\n const l = str.length;\n if (l === 0) {\n return '';\n }\n\n // Length of suffix matching the invert condition.\n let suffLen = 0;\n\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 } else if (currChar !== c && invert) {\n suffLen++;\n } else {\n break;\n }\n }\n\n return str.slice(0, l - suffLen);\n}\n\nexport function trimTrailingBlankLines(str: string) {\n const lines = str.split('\\n');\n let end = lines.length - 1;\n while (end >= 0 && !lines[end].trim()) {\n end--;\n }\n if (lines.length - end <= 2) {\n // we want to keep single trailing blank lines\n return str;\n }\n\n return lines.slice(0, end + 1).join('\\n');\n}\n\nexport function findClosingBracket(str: string, b: string) {\n if (str.indexOf(b[1]) === -1) {\n return -1;\n }\n\n let level = 0;\n for (let i = 0; i < str.length; i++) {\n if (str[i] === '\\\\') {\n i++;\n } else if (str[i] === b[0]) {\n level++;\n } else if (str[i] === b[1]) {\n level--;\n if (level < 0) {\n return i;\n }\n }\n }\n if (level > 0) {\n return -2;\n }\n\n return -1;\n}\n\nexport function expandTabs(line: string, indent = 0) {\n let col = indent;\n let expanded = '';\n for (const char of line) {\n if (char === '\\t') {\n const added = 4 - (col % 4);\n expanded += ' '.repeat(added);\n col += added;\n } else {\n expanded += char;\n col++;\n }\n }\n\n return expanded;\n}\n", "import { _defaults } from './defaults.ts';\nimport {\n rtrim,\n splitCells,\n findClosingBracket,\n expandTabs,\n trimTrailingBlankLines,\n} from './helpers.ts';\nimport type { Rules } from './rules.ts';\nimport type { _Lexer } from './Lexer.ts';\nimport type { Links, Tokens, Token } from './Tokens.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\n\nfunction outputLink(cap: string[], link: Pick, raw: string, lexer: _Lexer, rules: Rules): Tokens.Link | Tokens.Image {\n const href = link.href;\n const title = link.title || null;\n const text = cap[1].replace(rules.other.outputLinkReplace, '$1');\n\n lexer.state.inLink = true;\n const token: Tokens.Link | Tokens.Image = {\n type: cap[0].charAt(0) === '!' ? 'image' : '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\nfunction indentCodeCompensation(raw: string, text: string, rules: Rules) {\n const matchIndentToCode = raw.match(rules.other.indentCodeCompensation);\n\n if (matchIndentToCode === null) {\n return text;\n }\n\n const indentToCode = matchIndentToCode[1];\n\n return text\n .split('\\n')\n .map(node => {\n const matchIndentInNode = node.match(rules.other.beginningSpace);\n if (matchIndentInNode === null) {\n return node;\n }\n\n const [indentInNode] = matchIndentInNode;\n\n if (indentInNode.length >= indentToCode.length) {\n return node.slice(indentToCode.length);\n }\n\n return node;\n })\n .join('\\n');\n}\n\n/**\n * Tokenizer\n */\nexport class _Tokenizer {\n options: MarkedOptions;\n rules!: Rules; // set by the lexer\n lexer!: _Lexer; // set by the lexer\n\n constructor(options?: MarkedOptions) {\n this.options = options || _defaults;\n }\n\n space(src: string): Tokens.Space | undefined {\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\n code(src: string): Tokens.Code | undefined {\n const cap = this.rules.block.code.exec(src);\n if (cap) {\n const raw = this.options.pedantic\n ? cap[0]\n : trimTrailingBlankLines(cap[0]);\n const text = raw.replace(this.rules.other.codeRemoveIndent, '');\n return {\n type: 'code',\n raw,\n codeBlockStyle: 'indented',\n text,\n };\n }\n }\n\n fences(src: string): Tokens.Code | undefined {\n const cap = this.rules.block.fences.exec(src);\n if (cap) {\n const raw = cap[0];\n const text = indentCodeCompensation(raw, cap[3] || '', this.rules);\n\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\n heading(src: string): Tokens.Heading | undefined {\n const cap = this.rules.block.heading.exec(src);\n if (cap) {\n let text = cap[2].trim();\n\n // remove trailing #s\n if (this.rules.other.endingHash.test(text)) {\n const trimmed = rtrim(text, '#');\n if (this.options.pedantic) {\n text = trimmed.trim();\n } else if (!trimmed || this.rules.other.endingSpaceChar.test(trimmed)) {\n // CommonMark requires space before trailing #s\n text = trimmed.trim();\n }\n }\n\n return {\n type: 'heading',\n raw: rtrim(cap[0], '\\n'),\n depth: cap[1].length,\n text,\n tokens: this.lexer.inline(text),\n };\n }\n }\n\n hr(src: string): Tokens.Hr | undefined {\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\n blockquote(src: string): Tokens.Blockquote | undefined {\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: Token[] = [];\n\n while (lines.length > 0) {\n let inBlockquote = false;\n const currentLines = [];\n\n let i;\n for (i = 0; i < lines.length; i++) {\n // get lines up to a continuation\n if (this.rules.other.blockquoteStart.test(lines[i])) {\n currentLines.push(lines[i]);\n inBlockquote = true;\n } else if (!inBlockquote) {\n currentLines.push(lines[i]);\n } else {\n break;\n }\n }\n lines = lines.slice(i);\n\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(this.rules.other.blockquoteSetextReplace, '\\n $1')\n .replace(this.rules.other.blockquoteSetextReplace2, '');\n raw = raw ? `${raw}\\n${currentRaw}` : currentRaw;\n text = text ? `${text}\\n${currentText}` : currentText;\n\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\n // if there is no continuation then we are done\n if (lines.length === 0) {\n break;\n }\n\n const lastToken = tokens.at(-1);\n\n if (lastToken?.type === 'code') {\n // blockquote continuation cannot be preceded by a code block\n break;\n } else if (lastToken?.type === 'blockquote') {\n // include continuation in nested blockquote\n const oldToken = lastToken as Tokens.Blockquote;\n const newText = oldToken.raw + '\\n' + lines.join('\\n');\n const newToken = this.blockquote(newText)!;\n tokens[tokens.length - 1] = newToken;\n\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 } else if (lastToken?.type === 'list') {\n // include continuation in nested list\n const oldToken = lastToken as Tokens.List;\n const newText = oldToken.raw + '\\n' + lines.join('\\n');\n const newToken = this.list(newText)!;\n tokens[tokens.length - 1] = newToken;\n\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.at(-1)!.raw.length).split('\\n');\n continue;\n }\n }\n\n return {\n type: 'blockquote',\n raw,\n tokens,\n text,\n };\n }\n }\n\n list(src: string): Tokens.List | undefined {\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\n const list: Tokens.List = {\n type: 'list',\n raw: '',\n ordered: isordered,\n start: isordered ? +bull.slice(0, -1) : '',\n loose: false,\n items: [],\n };\n\n bull = isordered ? `\\\\d{1,9}\\\\${bull.slice(-1)}` : `\\\\${bull}`;\n\n if (this.options.pedantic) {\n bull = isordered ? bull : '[*+-]';\n }\n\n // Get next list item\n const itemRegex = this.rules.other.listItemRegex(bull);\n let endsWithBlankLine = false;\n // Check if current bullet point can start a new List Item\n while (src) {\n let endEarly = false;\n let raw = '';\n let itemContents = '';\n if (!(cap = itemRegex.exec(src))) {\n break;\n }\n\n if (this.rules.block.hr.test(src)) { // End list if bullet was actually HR (possibly move into itemRegex?)\n break;\n }\n\n raw = cap[0];\n src = src.substring(raw.length);\n\n let line = expandTabs(cap[2].split('\\n', 1)[0], cap[1].length);\n let nextLine = src.split('\\n', 1)[0];\n let blankLine = !line.trim();\n\n let indent = 0;\n if (this.options.pedantic) {\n indent = 2;\n itemContents = line.trimStart();\n } else if (blankLine) {\n indent = cap[1].length + 1;\n } else {\n indent = line.search(this.rules.other.nonSpaceChar); // 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\n if (blankLine && this.rules.other.blankLine.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\n if (!endEarly) {\n const nextBulletRegex = this.rules.other.nextBulletRegex(indent);\n const hrRegex = this.rules.other.hrRegex(indent);\n const fencesBeginRegex = this.rules.other.fencesBeginRegex(indent);\n const headingBeginRegex = this.rules.other.headingBeginRegex(indent);\n const htmlBeginRegex = this.rules.other.htmlBeginRegex(indent);\n const blockquoteBeginRegex = this.rules.other.blockquoteBeginRegex(indent);\n\n // Check if following lines should be included in List Item\n while (src) {\n const rawLine = src.split('\\n', 1)[0];\n let nextLineWithoutTabs;\n nextLine = rawLine;\n\n // Re-align to follow commonmark nesting rules\n if (this.options.pedantic) {\n nextLine = nextLine.replace(this.rules.other.listReplaceNesting, ' ');\n nextLineWithoutTabs = nextLine;\n } else {\n nextLineWithoutTabs = nextLine.replace(this.rules.other.tabCharGlobal, ' ');\n }\n\n // End list item if found code fences\n if (fencesBeginRegex.test(nextLine)) {\n break;\n }\n\n // End list item if found start of new heading\n if (headingBeginRegex.test(nextLine)) {\n break;\n }\n\n // End list item if found start of html block\n if (htmlBeginRegex.test(nextLine)) {\n break;\n }\n\n // End list item if found start of blockquote\n if (blockquoteBeginRegex.test(nextLine)) {\n break;\n }\n\n // End list item if found start of new bullet\n if (nextBulletRegex.test(nextLine)) {\n break;\n }\n\n // Horizontal rule found\n if (hrRegex.test(nextLine)) {\n break;\n }\n\n if (nextLineWithoutTabs.search(this.rules.other.nonSpaceChar) >= indent || !nextLine.trim()) { // Dedent if possible\n itemContents += '\\n' + nextLineWithoutTabs.slice(indent);\n } else {\n // not enough indentation\n if (blankLine) {\n break;\n }\n\n // paragraph continuation unless last line was a different block level element\n if (line.replace(this.rules.other.tabCharGlobal, ' ').search(this.rules.other.nonSpaceChar) >= 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\n itemContents += '\\n' + nextLine;\n }\n\n blankLine = !nextLine.trim();\n\n raw += rawLine + '\\n';\n src = src.substring(rawLine.length + 1);\n line = nextLineWithoutTabs.slice(indent);\n }\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 } else if (this.rules.other.doubleBlankLine.test(raw)) {\n endsWithBlankLine = true;\n }\n }\n\n list.items.push({\n type: 'list_item',\n raw,\n task: !!this.options.gfm && this.rules.other.listIsTask.test(itemContents),\n loose: false,\n text: itemContents,\n tokens: [],\n });\n\n list.raw += raw;\n }\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 const lastItem = list.items.at(-1);\n if (lastItem) {\n lastItem.raw = lastItem.raw.trimEnd();\n lastItem.text = lastItem.text.trimEnd();\n } else {\n // not a list since there were no items\n return;\n }\n list.raw = list.raw.trimEnd();\n\n // Item child tokens handled here at end because we needed to have the final item to trim it first\n for (const item of list.items) {\n this.lexer.state.top = false;\n item.tokens = this.lexer.blockTokens(item.text, []);\n if (item.task) {\n // Remove checkbox markdown from item tokens\n item.text = item.text.replace(this.rules.other.listReplaceTask, '');\n if (item.tokens[0]?.type === 'text' || item.tokens[0]?.type === 'paragraph') {\n item.tokens[0].raw = item.tokens[0].raw.replace(this.rules.other.listReplaceTask, '');\n item.tokens[0].text = item.tokens[0].text.replace(this.rules.other.listReplaceTask, '');\n for (let i = this.lexer.inlineQueue.length - 1; i >= 0; i--) {\n if (this.rules.other.listIsTask.test(this.lexer.inlineQueue[i].src)) {\n this.lexer.inlineQueue[i].src = this.lexer.inlineQueue[i].src.replace(this.rules.other.listReplaceTask, '');\n break;\n }\n }\n }\n\n const taskRaw = this.rules.other.listTaskCheckbox.exec(item.raw);\n if (taskRaw) {\n const checkboxToken: Tokens.Checkbox = {\n type: 'checkbox',\n raw: taskRaw[0] + ' ',\n checked: taskRaw[0] !== '[ ]',\n };\n item.checked = checkboxToken.checked;\n if (list.loose) {\n if (item.tokens[0] && ['paragraph', 'text'].includes(item.tokens[0].type) && 'tokens' in item.tokens[0] && item.tokens[0].tokens) {\n item.tokens[0].raw = checkboxToken.raw + item.tokens[0].raw;\n item.tokens[0].text = checkboxToken.raw + item.tokens[0].text;\n item.tokens[0].tokens.unshift(checkboxToken);\n } else {\n item.tokens.unshift({\n type: 'paragraph',\n raw: checkboxToken.raw,\n text: checkboxToken.raw,\n tokens: [checkboxToken],\n });\n }\n } else {\n item.tokens.unshift(checkboxToken);\n }\n }\n }\n\n if (!list.loose) {\n // Check if list should be loose\n const spacers = item.tokens.filter(t => t.type === 'space');\n const hasMultipleLineBreaks = spacers.length > 0 && spacers.some(t => this.rules.other.anyLine.test(t.raw));\n\n list.loose = hasMultipleLineBreaks;\n }\n }\n\n // Set all items to loose if list is loose\n if (list.loose) {\n for (const item of list.items) {\n item.loose = true;\n for (const token of item.tokens) {\n if (token.type === 'text') {\n token.type = 'paragraph';\n }\n }\n }\n }\n\n return list;\n }\n }\n\n html(src: string): Tokens.HTML | undefined {\n const cap = this.rules.block.html.exec(src);\n if (cap) {\n const raw = trimTrailingBlankLines(cap[0]);\n const token: Tokens.HTML = {\n type: 'html',\n block: true,\n raw,\n pre: cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style',\n text: raw,\n };\n return token;\n }\n }\n\n def(src: string): Tokens.Def | undefined {\n const cap = this.rules.block.def.exec(src);\n if (cap) {\n const tag = cap[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal, ' ');\n const href = cap[2] ? cap[2].replace(this.rules.other.hrefBrackets, '$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: rtrim(cap[0], '\\n'),\n href,\n title,\n };\n }\n }\n\n table(src: string): Tokens.Table | undefined {\n const cap = this.rules.block.table.exec(src);\n if (!cap) {\n return;\n }\n\n if (!this.rules.other.tableDelimiter.test(cap[2])) {\n // delimiter row must have a pipe (|) or colon (:) otherwise it is a setext heading\n return;\n }\n\n const headers = splitCells(cap[1]);\n const aligns = cap[2].replace(this.rules.other.tableAlignChars, '').split('|');\n const rows = cap[3]?.trim() ? cap[3].replace(this.rules.other.tableRowBlankLine, '').split('\\n') : [];\n\n const item: Tokens.Table = {\n type: 'table',\n raw: rtrim(cap[0], '\\n'),\n header: [],\n align: [],\n rows: [],\n };\n\n if (headers.length !== aligns.length) {\n // header and align columns must be equal, rows can be different.\n return;\n }\n\n for (const align of aligns) {\n if (this.rules.other.tableAlignRight.test(align)) {\n item.align.push('right');\n } else if (this.rules.other.tableAlignCenter.test(align)) {\n item.align.push('center');\n } else if (this.rules.other.tableAlignLeft.test(align)) {\n item.align.push('left');\n } else {\n item.align.push(null);\n }\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\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\n return item;\n }\n\n lheading(src: string): Tokens.Heading | undefined {\n const cap = this.rules.block.lheading.exec(src);\n if (cap) {\n const text = cap[1].trim();\n return {\n type: 'heading',\n raw: rtrim(cap[0], '\\n'),\n depth: cap[2].charAt(0) === '=' ? 1 : 2,\n text,\n tokens: this.lexer.inline(text),\n };\n }\n }\n\n paragraph(src: string): Tokens.Paragraph | undefined {\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\n text(src: string): Tokens.Text | undefined {\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\n escape(src: string): Tokens.Escape | undefined {\n const cap = this.rules.inline.escape.exec(src);\n if (cap) {\n return {\n type: 'escape',\n raw: cap[0],\n text: cap[1],\n };\n }\n }\n\n tag(src: string): Tokens.Tag | undefined {\n const cap = this.rules.inline.tag.exec(src);\n if (cap) {\n if (!this.lexer.state.inLink && this.rules.other.startATag.test(cap[0])) {\n this.lexer.state.inLink = true;\n } else if (this.lexer.state.inLink && this.rules.other.endATag.test(cap[0])) {\n this.lexer.state.inLink = false;\n }\n if (!this.lexer.state.inRawBlock && this.rules.other.startPreScriptTag.test(cap[0])) {\n this.lexer.state.inRawBlock = true;\n } else if (this.lexer.state.inRawBlock && this.rules.other.endPreScriptTag.test(cap[0])) {\n this.lexer.state.inRawBlock = false;\n }\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\n link(src: string): Tokens.Link | Tokens.Image | undefined {\n const cap = this.rules.inline.link.exec(src);\n if (cap) {\n const trimmedUrl = cap[2].trim();\n if (!this.options.pedantic && this.rules.other.startAngleBracket.test(trimmedUrl)) {\n // commonmark requires matching angle brackets\n if (!(this.rules.other.endAngleBracket.test(trimmedUrl))) {\n return;\n }\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 } else {\n // find closing parenthesis\n const lastParenIndex = findClosingBracket(cap[2], '()');\n if (lastParenIndex === -2) {\n // more open parens than closed\n return;\n }\n\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 = this.rules.other.pedanticHrefTitle.exec(href);\n\n if (link) {\n href = link[1];\n title = link[3];\n }\n } else {\n title = cap[3] ? cap[3].slice(1, -1) : '';\n }\n\n href = href.trim();\n if (this.rules.other.startAngleBracket.test(href)) {\n if (this.options.pedantic && !(this.rules.other.endAngleBracket.test(trimmedUrl))) {\n // pedantic allows starting angle bracket without ending angle bracket\n href = href.slice(1);\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, this.rules);\n }\n }\n\n reflink(src: string, links: Links): Tokens.Link | Tokens.Image | Tokens.Text | undefined {\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(this.rules.other.multipleSpaceGlobal, ' ');\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, this.rules);\n }\n }\n\n emStrong(src: string, maskedSrc: string, prevChar = ''): Tokens.Em | Tokens.Strong | undefined {\n let match = this.rules.inline.emStrongLDelim.exec(src);\n if (!match) return;\n if (!match[1] && !match[2] && !match[3] && !match[4]) return;\n\n // _ can't be between two alphanumerics. \\p{L}\\p{N} includes non-english alphabet/numbers as well\n if (match[4] && prevChar.match(this.rules.other.unicodeAlphaNumeric)) return;\n\n const nextChar = match[1] || match[3] || '';\n\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\n const endReg = match[0][0] === '*' ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;\n endReg.lastIndex = 0;\n\n // Clip maskedSrc to same section of string as src (move to lexer?)\n maskedSrc = maskedSrc.slice(-1 * src.length + lLength);\n\n while ((match = endReg.exec(maskedSrc)) !== null) {\n rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6];\n\n if (!rDelim) continue; // skip single * in __abc*abc__\n\n rLength = [...rDelim].length;\n\n if (match[3] || match[4]) { // found another Left Delim\n delimTotal += rLength;\n continue;\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\n delimTotal -= rLength;\n\n if (delimTotal > 0) continue; // Haven't found enough closing delimiters\n\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\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\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\n codespan(src: string): Tokens.Codespan | undefined {\n const cap = this.rules.inline.code.exec(src);\n if (cap) {\n let text = cap[2].replace(this.rules.other.newLineCharGlobal, ' ');\n const hasNonSpaceChars = this.rules.other.nonSpaceChar.test(text);\n const hasSpaceCharsOnBothEnds = this.rules.other.startingSpaceChar.test(text) && this.rules.other.endingSpaceChar.test(text);\n if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {\n text = text.substring(1, text.length - 1);\n }\n return {\n type: 'codespan',\n raw: cap[0],\n text,\n };\n }\n }\n\n br(src: string): Tokens.Br | undefined {\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\n del(src: string, maskedSrc: string, prevChar = ''): Tokens.Del | undefined {\n let match = this.rules.inline.delLDelim.exec(src);\n if (!match) return;\n\n const nextChar = match[1] || '';\n\n if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) {\n // unicode Regex counts emoji as 1 char; spread into array for proper count\n const lLength = [...match[0]].length - 1;\n let rDelim, rLength, delimTotal = lLength;\n\n const endReg = this.rules.inline.delRDelim;\n endReg.lastIndex = 0;\n\n // Clip maskedSrc to same section of string as src\n maskedSrc = maskedSrc.slice(-1 * src.length + lLength);\n\n while ((match = endReg.exec(maskedSrc)) !== null) {\n rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6];\n\n if (!rDelim) continue;\n\n rLength = [...rDelim].length;\n\n if (rLength !== lLength) continue;\n\n if (match[3] || match[4]) { // found another Left Delim\n delimTotal += rLength;\n continue;\n }\n\n delimTotal -= rLength;\n\n if (delimTotal > 0) continue; // Haven't found enough closing delimiters\n\n // Remove extra characters\n rLength = Math.min(rLength, rLength + delimTotal);\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\n // Create del token - only single ~ or double ~~ supported\n const text = raw.slice(lLength, -lLength);\n return {\n type: 'del',\n raw,\n text,\n tokens: this.lexer.inlineTokens(text),\n };\n }\n }\n }\n\n autolink(src: string): Tokens.Link | undefined {\n const cap = this.rules.inline.autolink.exec(src);\n if (cap) {\n let text, href;\n if (cap[2] === '@') {\n text = cap[1];\n href = 'mailto:' + text;\n } else {\n text = cap[1];\n href = text;\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\n url(src: string): Tokens.Link | undefined {\n let cap;\n if (cap = this.rules.inline.url.exec(src)) {\n let text, href;\n if (cap[2] === '@') {\n text = cap[0];\n href = 'mailto:' + text;\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 = cap[0];\n if (cap[1] === 'www.') {\n href = 'http://' + cap[0];\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\n inlineText(src: string): Tokens.Text | undefined {\n const cap = this.rules.inline.text.exec(src);\n if (cap) {\n const escaped = this.lexer.state.inRawBlock;\n return {\n type: 'text',\n raw: cap[0],\n text: cap[0],\n escaped,\n };\n }\n }\n}\n", "import { _Tokenizer } from './Tokenizer.ts';\nimport { _defaults } from './defaults.ts';\nimport { other, block, inline } from './rules.ts';\nimport type { Token, TokensList, Tokens } from './Tokens.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\n\n/**\n * Block Lexer\n */\nexport class _Lexer {\n tokens: TokensList;\n options: MarkedOptions;\n state: {\n inLink: boolean;\n inRawBlock: boolean;\n top: boolean;\n };\n\n public inlineQueue: { src: string, tokens: Token[] }[];\n\n private tokenizer: _Tokenizer;\n\n constructor(options?: MarkedOptions) {\n // TokenList cannot be created in one go\n this.tokens = [] as unknown as TokensList;\n this.tokens.links = Object.create(null);\n this.options = options || _defaults;\n this.options.tokenizer = this.options.tokenizer || new _Tokenizer();\n this.tokenizer = this.options.tokenizer;\n this.tokenizer.options = this.options;\n this.tokenizer.lexer = this;\n this.inlineQueue = [];\n this.state = {\n inLink: false,\n inRawBlock: false,\n top: true,\n };\n\n const rules = {\n other,\n block: block.normal,\n inline: inline.normal,\n };\n\n if (this.options.pedantic) {\n rules.block = block.pedantic;\n rules.inline = inline.pedantic;\n } else if (this.options.gfm) {\n rules.block = block.gfm;\n if (this.options.breaks) {\n rules.inline = inline.breaks;\n } else {\n rules.inline = inline.gfm;\n }\n }\n this.tokenizer.rules = rules;\n }\n\n /**\n * Expose Rules\n */\n static get rules() {\n return {\n block,\n inline,\n };\n }\n\n /**\n * Static Lex Method\n */\n static lex(src: string, options?: MarkedOptions) {\n const lexer = new _Lexer(options);\n return lexer.lex(src);\n }\n\n /**\n * Static Lex Inline Method\n */\n static lexInline(src: string, options?: MarkedOptions) {\n const lexer = new _Lexer(options);\n return lexer.inlineTokens(src);\n }\n\n /**\n * Preprocessing\n */\n lex(src: string) {\n src = src.replace(other.carriageReturn, '\\n');\n\n this.blockTokens(src, this.tokens);\n\n for (let i = 0; i < this.inlineQueue.length; i++) {\n const next = this.inlineQueue[i];\n this.inlineTokens(next.src, next.tokens);\n }\n this.inlineQueue = [];\n\n return this.tokens;\n }\n\n /**\n * Lexing\n */\n blockTokens(src: string, tokens?: Token[], lastParagraphClipped?: boolean): Token[];\n blockTokens(src: string, tokens?: TokensList, lastParagraphClipped?: boolean): TokensList;\n blockTokens(src: string, tokens: Token[] = [], lastParagraphClipped = false) {\n this.tokenizer.lexer = this;\n if (this.options.pedantic) {\n src = src.replace(other.tabCharGlobal, ' ').replace(other.spaceLine, '');\n }\n\n while (src) {\n let token: Tokens.Generic | undefined;\n\n if (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\n // newline\n if (token = this.tokenizer.space(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (token.raw.length === 1 && lastToken !== undefined) {\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 lastToken.raw += '\\n';\n } else {\n tokens.push(token);\n }\n continue;\n }\n\n // code\n if (token = this.tokenizer.code(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n // An indented code block cannot interrupt a paragraph.\n if (lastToken?.type === 'paragraph' || lastToken?.type === 'text') {\n lastToken.raw += (lastToken.raw.endsWith('\\n') ? '' : '\\n') + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.at(-1)!.src = lastToken.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\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\n // heading\n if (token = this.tokenizer.heading(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\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\n // blockquote\n if (token = this.tokenizer.blockquote(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\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\n // html\n if (token = this.tokenizer.html(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // def\n if (token = this.tokenizer.def(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (lastToken?.type === 'paragraph' || lastToken?.type === 'text') {\n lastToken.raw += (lastToken.raw.endsWith('\\n') ? '' : '\\n') + token.raw;\n lastToken.text += '\\n' + token.raw;\n this.inlineQueue.at(-1)!.src = lastToken.text;\n } else if (!this.tokens.links[token.tag]) {\n this.tokens.links[token.tag] = {\n href: token.href,\n title: token.title,\n };\n tokens.push(token);\n }\n continue;\n }\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\n // lheading\n if (token = this.tokenizer.lheading(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // top-level paragraph\n // prevent paragraph consuming extensions by clipping 'src' to extension start\n let cutSrc = src;\n if (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 const lastToken = tokens.at(-1);\n if (lastParagraphClipped && lastToken?.type === 'paragraph') {\n lastToken.raw += (lastToken.raw.endsWith('\\n') ? '' : '\\n') + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.pop();\n this.inlineQueue.at(-1)!.src = lastToken.text;\n } else {\n tokens.push(token);\n }\n lastParagraphClipped = cutSrc.length !== src.length;\n src = src.substring(token.raw.length);\n continue;\n }\n\n // text\n if (token = this.tokenizer.text(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (lastToken?.type === 'text') {\n lastToken.raw += (lastToken.raw.endsWith('\\n') ? '' : '\\n') + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.pop();\n this.inlineQueue.at(-1)!.src = lastToken.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\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 } else {\n throw new Error(errMsg);\n }\n }\n }\n\n this.state.top = true;\n return tokens;\n }\n\n inline(src: string, tokens: Token[] = []) {\n this.inlineQueue.push({ src, tokens });\n return tokens;\n }\n\n /**\n * Lexing/Compiling\n */\n inlineTokens(src: string, tokens: Token[] = []): Token[] {\n this.tokenizer.lexer = this;\n // String with links masked to avoid interference with em and strong\n let maskedSrc = src;\n let match: RegExpExecArray | null = null;\n\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)\n + '[' + 'a'.repeat(match[0].length - 2) + ']'\n + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex);\n }\n }\n }\n }\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\n // Mask out other blocks\n let offset;\n while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) !== null) {\n offset = match[2] ? match[2].length : 0;\n maskedSrc = maskedSrc.slice(0, match.index + offset) + '[' + 'a'.repeat(match[0].length - offset - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);\n }\n\n // Mask out blocks from extensions\n maskedSrc = this.options.hooks?.emStrongMask?.call({ lexer: this }, maskedSrc) ?? maskedSrc;\n\n let keepPrevChar = false;\n let prevChar = '';\n while (src) {\n if (!keepPrevChar) {\n prevChar = '';\n }\n keepPrevChar = false;\n\n let token: Tokens.Generic | undefined;\n\n // extensions\n if (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\n // escape\n if (token = this.tokenizer.escape(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // tag\n if (token = this.tokenizer.tag(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\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\n // reflink, nolink\n if (token = this.tokenizer.reflink(src, this.tokens.links)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (token.type === 'text' && lastToken?.type === 'text') {\n lastToken.raw += token.raw;\n lastToken.text += token.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\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\n // code\n if (token = this.tokenizer.codespan(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\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\n // del (gfm)\n if (token = this.tokenizer.del(src, maskedSrc, prevChar)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\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\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\n // text\n // prevent inlineText consuming extensions by clipping 'src' to extension start\n let cutSrc = src;\n if (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 const lastToken = tokens.at(-1);\n if (lastToken?.type === 'text') {\n lastToken.raw += token.raw;\n lastToken.text += token.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\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 } else {\n throw new Error(errMsg);\n }\n }\n }\n\n return tokens;\n }\n}\n", "import { _defaults } from './defaults.ts';\nimport {\n cleanUrl,\n escapeHtmlEntities,\n} from './helpers.ts';\nimport { other } from './rules.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\nimport type { Tokens } from './Tokens.ts';\nimport type { _Parser } from './Parser.ts';\n\n/**\n * Renderer\n */\nexport class _Renderer {\n options: MarkedOptions;\n parser!: _Parser; // set by the parser\n constructor(options?: MarkedOptions) {\n this.options = options || _defaults;\n }\n\n space(token: Tokens.Space): RendererOutput {\n return '' as RendererOutput;\n }\n\n code({ text, lang, escaped }: Tokens.Code): RendererOutput {\n const langString = (lang || '').match(other.notSpaceStart)?.[0];\n\n const code = text.replace(other.endingNewline, '') + '\\n';\n\n if (!langString) {\n return '
    '\n        + (escaped ? code : escapeHtmlEntities(code, true))\n        + '
    \\n' as RendererOutput;\n }\n\n return '
    '\n      + (escaped ? code : escapeHtmlEntities(code, true))\n      + '
    \\n' as RendererOutput;\n }\n\n blockquote({ tokens }: Tokens.Blockquote): RendererOutput {\n const body = this.parser.parse(tokens);\n return `
    \\n${body}
    \\n` as RendererOutput;\n }\n\n html({ text }: Tokens.HTML | Tokens.Tag): RendererOutput {\n return text as RendererOutput;\n }\n\n def(token: Tokens.Def): RendererOutput {\n return '' as RendererOutput;\n }\n\n heading({ tokens, depth }: Tokens.Heading): RendererOutput {\n return `${this.parser.parseInline(tokens)}\\n` as RendererOutput;\n }\n\n hr(token: Tokens.Hr): RendererOutput {\n return '
    \\n' as RendererOutput;\n }\n\n list(token: Tokens.List): RendererOutput {\n const ordered = token.ordered;\n const start = token.start;\n\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\n const type = ordered ? 'ol' : 'ul';\n const startAttr = (ordered && start !== 1) ? (' start=\"' + start + '\"') : '';\n return '<' + type + startAttr + '>\\n' + body + '\\n' as RendererOutput;\n }\n\n listitem(item: Tokens.ListItem): RendererOutput {\n return `
  • ${this.parser.parse(item.tokens)}
  • \\n` as RendererOutput;\n }\n\n checkbox({ checked }: Tokens.Checkbox): RendererOutput {\n return ' ' as RendererOutput;\n }\n\n paragraph({ tokens }: Tokens.Paragraph): RendererOutput {\n return `

    ${this.parser.parseInline(tokens)}

    \\n` as RendererOutput;\n }\n\n table(token: Tokens.Table): RendererOutput {\n let header = '';\n\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 as ParserOutput });\n\n let body = '';\n for (let j = 0; j < token.rows.length; j++) {\n const row = token.rows[j];\n\n cell = '';\n for (let k = 0; k < row.length; k++) {\n cell += this.tablecell(row[k]);\n }\n\n body += this.tablerow({ text: cell as ParserOutput });\n }\n if (body) body = `${body}`;\n\n return '\\n'\n + '\\n'\n + header\n + '\\n'\n + body\n + '
    \\n' as RendererOutput;\n }\n\n tablerow({ text }: Tokens.TableRow): RendererOutput {\n return `\\n${text}\\n` as RendererOutput;\n }\n\n tablecell(token: Tokens.TableCell): RendererOutput {\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` as RendererOutput;\n }\n\n /**\n * span level renderer\n */\n strong({ tokens }: Tokens.Strong): RendererOutput {\n return `${this.parser.parseInline(tokens)}` as RendererOutput;\n }\n\n em({ tokens }: Tokens.Em): RendererOutput {\n return `${this.parser.parseInline(tokens)}` as RendererOutput;\n }\n\n codespan({ text }: Tokens.Codespan): RendererOutput {\n return `${escapeHtmlEntities(text, true)}` as RendererOutput;\n }\n\n br(token: Tokens.Br): RendererOutput {\n return '
    ' as RendererOutput;\n }\n\n del({ tokens }: Tokens.Del): RendererOutput {\n return `${this.parser.parseInline(tokens)}` as RendererOutput;\n }\n\n link({ href, title, tokens }: Tokens.Link): RendererOutput {\n const text = this.parser.parseInline(tokens) as string;\n const cleanHref = cleanUrl(href);\n if (cleanHref === null) {\n return text as RendererOutput;\n }\n href = cleanHref;\n let out = '
    ';\n return out as RendererOutput;\n }\n\n image({ href, title, text, tokens }: Tokens.Image): RendererOutput {\n if (tokens) {\n text = this.parser.parseInline(tokens, this.parser.textRenderer) as string;\n }\n const cleanHref = cleanUrl(href);\n if (cleanHref === null) {\n return escapeHtmlEntities(text) as RendererOutput;\n }\n href = cleanHref;\n\n let out = `\"${escapeHtmlEntities(text)}\"`;\n {\n // no need for block level renderers\n strong({ text }: Tokens.Strong): RendererOutput {\n return text as RendererOutput;\n }\n\n em({ text }: Tokens.Em): RendererOutput {\n return text as RendererOutput;\n }\n\n codespan({ text }: Tokens.Codespan): RendererOutput {\n return text as RendererOutput;\n }\n\n del({ text }: Tokens.Del): RendererOutput {\n return text as RendererOutput;\n }\n\n html({ text }: Tokens.HTML | Tokens.Tag): RendererOutput {\n return text as RendererOutput;\n }\n\n text({ text }: Tokens.Text | Tokens.Escape | Tokens.Tag): RendererOutput {\n return text as RendererOutput;\n }\n\n link({ text }: Tokens.Link): RendererOutput {\n return '' + text as RendererOutput;\n }\n\n image({ text }: Tokens.Image): RendererOutput {\n return '' + text as RendererOutput;\n }\n\n br(): RendererOutput {\n return '' as RendererOutput;\n }\n\n checkbox({ raw }: Tokens.Checkbox): RendererOutput {\n return raw as RendererOutput;\n }\n}\n", "import { _Renderer } from './Renderer.ts';\nimport { _TextRenderer } from './TextRenderer.ts';\nimport { _defaults } from './defaults.ts';\nimport type { MarkedToken, Token, Tokens } from './Tokens.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\n\n/**\n * Parsing & Compiling\n */\nexport class _Parser {\n options: MarkedOptions;\n renderer: _Renderer;\n textRenderer: _TextRenderer;\n constructor(options?: MarkedOptions) {\n this.options = options || _defaults;\n this.options.renderer = this.options.renderer || new _Renderer();\n this.renderer = this.options.renderer;\n this.renderer.options = this.options;\n this.renderer.parser = this;\n this.textRenderer = new _TextRenderer();\n }\n\n /**\n * Static Parse Method\n */\n static parse(tokens: Token[], options?: MarkedOptions) {\n const parser = new _Parser(options);\n return parser.parse(tokens);\n }\n\n /**\n * Static Parse Inline Method\n */\n static parseInline(tokens: Token[], options?: MarkedOptions) {\n const parser = new _Parser(options);\n return parser.parseInline(tokens);\n }\n\n /**\n * Parse Loop\n */\n parse(tokens: Token[]): ParserOutput {\n this.renderer.parser = this;\n let out = '';\n\n for (let i = 0; i < tokens.length; i++) {\n const anyToken = tokens[i];\n\n // Run any renderer extensions\n if (this.options.extensions?.renderers?.[anyToken.type]) {\n const genericToken = anyToken as Tokens.Generic;\n const ret = this.options.extensions.renderers[genericToken.type].call({ parser: this }, genericToken);\n if (ret !== false || !['space', 'hr', 'heading', 'code', 'table', 'blockquote', 'list', 'html', 'def', 'paragraph', 'text'].includes(genericToken.type)) {\n out += ret || '';\n continue;\n }\n }\n\n const token = anyToken as MarkedToken;\n\n switch (token.type) {\n case 'space': {\n out += this.renderer.space(token);\n break;\n }\n case 'hr': {\n out += this.renderer.hr(token);\n break;\n }\n case 'heading': {\n out += this.renderer.heading(token);\n break;\n }\n case 'code': {\n out += this.renderer.code(token);\n break;\n }\n case 'table': {\n out += this.renderer.table(token);\n break;\n }\n case 'blockquote': {\n out += this.renderer.blockquote(token);\n break;\n }\n case 'list': {\n out += this.renderer.list(token);\n break;\n }\n case 'checkbox': {\n out += this.renderer.checkbox(token);\n break;\n }\n case 'html': {\n out += this.renderer.html(token);\n break;\n }\n case 'def': {\n out += this.renderer.def(token);\n break;\n }\n case 'paragraph': {\n out += this.renderer.paragraph(token);\n break;\n }\n case 'text': {\n out += this.renderer.text(token);\n break;\n }\n\n default: {\n const errMsg = 'Token with \"' + token.type + '\" type was not found.';\n if (this.options.silent) {\n console.error(errMsg);\n return '' as ParserOutput;\n } else {\n throw new Error(errMsg);\n }\n }\n }\n }\n\n return out as ParserOutput;\n }\n\n /**\n * Parse Inline Tokens\n */\n parseInline(tokens: Token[], renderer: _Renderer | _TextRenderer = this.renderer): ParserOutput {\n this.renderer.parser = this;\n let out = '';\n\n for (let i = 0; i < tokens.length; i++) {\n const anyToken = tokens[i];\n\n // Run any renderer extensions\n if (this.options.extensions?.renderers?.[anyToken.type]) {\n const ret = this.options.extensions.renderers[anyToken.type].call({ parser: this }, anyToken);\n if (ret !== false || !['escape', 'html', 'link', 'image', 'strong', 'em', 'codespan', 'br', 'del', 'text'].includes(anyToken.type)) {\n out += ret || '';\n continue;\n }\n }\n\n const token = anyToken as MarkedToken;\n\n switch (token.type) {\n case 'escape': {\n out += renderer.text(token);\n break;\n }\n case 'html': {\n out += renderer.html(token);\n break;\n }\n case 'link': {\n out += renderer.link(token);\n break;\n }\n case 'image': {\n out += renderer.image(token);\n break;\n }\n case 'checkbox': {\n out += renderer.checkbox(token);\n break;\n }\n case 'strong': {\n out += renderer.strong(token);\n break;\n }\n case 'em': {\n out += renderer.em(token);\n break;\n }\n case 'codespan': {\n out += renderer.codespan(token);\n break;\n }\n case 'br': {\n out += renderer.br(token);\n break;\n }\n case 'del': {\n out += renderer.del(token);\n break;\n }\n case 'text': {\n out += renderer.text(token);\n break;\n }\n default: {\n const errMsg = 'Token with \"' + token.type + '\" type was not found.';\n if (this.options.silent) {\n console.error(errMsg);\n return '' as ParserOutput;\n } else {\n throw new Error(errMsg);\n }\n }\n }\n }\n return out as ParserOutput;\n }\n}\n", "import { _defaults } from './defaults.ts';\nimport { _Lexer } from './Lexer.ts';\nimport { _Parser } from './Parser.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\nimport type { Token, TokensList } from './Tokens.ts';\n\nexport class _Hooks {\n options: MarkedOptions;\n block?: boolean;\n\n constructor(options?: MarkedOptions) {\n this.options = options || _defaults;\n }\n\n static passThroughHooks = new Set([\n 'preprocess',\n 'postprocess',\n 'processAllTokens',\n 'emStrongMask',\n ]);\n\n static passThroughHooksRespectAsync = new Set([\n 'preprocess',\n 'postprocess',\n 'processAllTokens',\n ]);\n\n /**\n * Process markdown before marked\n */\n preprocess(markdown: string) {\n return markdown;\n }\n\n /**\n * Process HTML after marked is finished\n */\n postprocess(html: ParserOutput) {\n return html;\n }\n\n /**\n * Process all tokens before walk tokens\n */\n processAllTokens(tokens: Token[] | TokensList) {\n return tokens;\n }\n\n /**\n * Mask contents that should not be interpreted as em/strong delimiters\n */\n emStrongMask(src: string) {\n return src;\n }\n\n /**\n * Provide function to tokenize markdown\n */\n provideLexer(block = this.block) {\n return block ? _Lexer.lex : _Lexer.lexInline;\n }\n\n /**\n * Provide function to parse tokens\n */\n provideParser(block = this.block) {\n return block ? _Parser.parse : _Parser.parseInline;\n }\n}\n", "import { _getDefaults } from './defaults.ts';\nimport { _Lexer } from './Lexer.ts';\nimport { _Parser } from './Parser.ts';\nimport { _Hooks } from './Hooks.ts';\nimport { _Renderer } from './Renderer.ts';\nimport { _Tokenizer } from './Tokenizer.ts';\nimport { _TextRenderer } from './TextRenderer.ts';\nimport { escapeHtmlEntities } from './helpers.ts';\nimport type { MarkedExtension, MarkedOptions } from './MarkedOptions.ts';\nimport type { Token, Tokens, TokensList } from './Tokens.ts';\n\nexport type MaybePromise = void | Promise;\n\ntype UnknownFunction = (...args: unknown[]) => unknown;\ntype GenericRendererFunction = (...args: unknown[]) => string | false;\n\nexport class Marked {\n defaults = _getDefaults();\n options = this.setOptions;\n\n parse = this.parseMarkdown(true);\n parseInline = this.parseMarkdown(false);\n\n Parser = _Parser;\n Renderer = _Renderer;\n TextRenderer = _TextRenderer;\n Lexer = _Lexer;\n Tokenizer = _Tokenizer;\n Hooks = _Hooks;\n\n constructor(...args: MarkedExtension[]) {\n this.use(...args);\n }\n\n /**\n * Run callback for every token\n */\n walkTokens(tokens: Token[] | TokensList, callback: (token: Token) => MaybePromise | MaybePromise[]) {\n let values: MaybePromise[] = [];\n for (const token of tokens) {\n values = values.concat(callback.call(this, token));\n switch (token.type) {\n case 'table': {\n const tableToken = token as Tokens.Table;\n for (const cell of tableToken.header) {\n values = values.concat(this.walkTokens(cell.tokens, callback));\n }\n for (const row of tableToken.rows) {\n for (const cell of row) {\n values = values.concat(this.walkTokens(cell.tokens, callback));\n }\n }\n break;\n }\n case 'list': {\n const listToken = token as Tokens.List;\n values = values.concat(this.walkTokens(listToken.items, callback));\n break;\n }\n default: {\n const genericToken = token as Tokens.Generic;\n if (this.defaults.extensions?.childTokens?.[genericToken.type]) {\n this.defaults.extensions.childTokens[genericToken.type].forEach((childTokens) => {\n const tokens = genericToken[childTokens].flat(Infinity) as Token[] | TokensList;\n values = values.concat(this.walkTokens(tokens, callback));\n });\n } else if (genericToken.tokens) {\n values = values.concat(this.walkTokens(genericToken.tokens, callback));\n }\n }\n }\n }\n return values;\n }\n\n use(...args: MarkedExtension[]) {\n const extensions: MarkedOptions['extensions'] = this.defaults.extensions || { renderers: {}, childTokens: {} };\n\n args.forEach((pack) => {\n // copy options to new object\n const opts = { ...pack } as MarkedOptions;\n\n // set async to true if it was set to true before\n opts.async = this.defaults.async || opts.async || false;\n\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 } 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 } 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 } else {\n extensions.startBlock = [ext.start];\n }\n } else if (ext.level === 'inline') {\n if (extensions.startInline) {\n extensions.startInline.push(ext.start);\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\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 as Exclude, 'options' | 'parser'>;\n const rendererFunc = pack.renderer[rendererProp] as GenericRendererFunction;\n const prevRenderer = renderer[rendererProp] as GenericRendererFunction;\n // Replace renderer with func to run extension, but fall back if false\n renderer[rendererProp] = (...args: unknown[]) => {\n let ret = rendererFunc.apply(renderer, args);\n if (ret === false) {\n ret = prevRenderer.apply(renderer, args);\n }\n return (ret || '') as RendererOutput;\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 as Exclude, 'options' | 'rules' | 'lexer'>;\n const tokenizerFunc = pack.tokenizer[tokenizerProp] as UnknownFunction;\n const prevTokenizer = tokenizer[tokenizerProp] as UnknownFunction;\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: unknown[]) => {\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\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 (['options', 'block'].includes(prop)) {\n // ignore options and block properties\n continue;\n }\n const hooksProp = prop as Exclude, 'options' | 'block'>;\n const hooksFunc = pack.hooks[hooksProp] as UnknownFunction;\n const prevHook = hooks[hooksProp] as UnknownFunction;\n if (_Hooks.passThroughHooks.has(prop)) {\n // @ts-expect-error cannot type hook function dynamically\n hooks[hooksProp] = (arg: unknown) => {\n if (this.defaults.async && _Hooks.passThroughHooksRespectAsync.has(prop)) {\n return (async() => {\n const ret = await hooksFunc.call(hooks, arg);\n return prevHook.call(hooks, ret);\n })();\n }\n\n const ret = hooksFunc.call(hooks, arg);\n return prevHook.call(hooks, ret);\n };\n } else {\n // @ts-expect-error cannot type hook function dynamically\n hooks[hooksProp] = (...args: unknown[]) => {\n if (this.defaults.async) {\n return (async() => {\n let ret = await hooksFunc.apply(hooks, args);\n if (ret === false) {\n ret = await prevHook.apply(hooks, args);\n }\n return ret;\n })();\n }\n\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\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: MaybePromise[] = [];\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\n this.defaults = { ...this.defaults, ...opts };\n });\n\n return this;\n }\n\n setOptions(opt: MarkedOptions) {\n this.defaults = { ...this.defaults, ...opt };\n return this;\n }\n\n lexer(src: string, options?: MarkedOptions) {\n return _Lexer.lex(src, options ?? this.defaults);\n }\n\n parser(tokens: Token[], options?: MarkedOptions) {\n return _Parser.parse(tokens, options ?? this.defaults);\n }\n\n private parseMarkdown(blockType: boolean) {\n type overloadedParse = {\n (src: string, options: MarkedOptions & { async: true }): Promise;\n (src: string, options: MarkedOptions & { async: false }): ParserOutput;\n (src: string, options?: MarkedOptions | null): ParserOutput | Promise;\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const parse: overloadedParse = (src: string, options?: MarkedOptions | null): any => {\n const origOpt = { ...options };\n const opt = { ...this.defaults, ...origOpt };\n\n const throwError = this.onError(!!opt.silent, !!opt.async);\n\n // throw error if an extension set async to true but parse was called with async: false\n if (this.defaults.async === true && origOpt.async === false) {\n return throwError(new Error('marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.'));\n }\n\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\n if (opt.hooks) {\n opt.hooks.options = opt;\n opt.hooks.block = blockType;\n }\n\n if (opt.async) {\n return (async() => {\n const processedSrc = opt.hooks ? await opt.hooks.preprocess(src) : src;\n const lexer = opt.hooks ? await opt.hooks.provideLexer(blockType) : (blockType ? _Lexer.lex : _Lexer.lexInline);\n const tokens = await lexer(processedSrc, opt);\n const processedTokens = opt.hooks ? await opt.hooks.processAllTokens(tokens) : tokens;\n if (opt.walkTokens) {\n await Promise.all(this.walkTokens(processedTokens, opt.walkTokens));\n }\n const parser = opt.hooks ? await opt.hooks.provideParser(blockType) : (blockType ? _Parser.parse : _Parser.parseInline);\n const html = await parser(processedTokens, opt);\n return opt.hooks ? await opt.hooks.postprocess(html) : html;\n })().catch(throwError);\n }\n\n try {\n if (opt.hooks) {\n src = opt.hooks.preprocess(src) as string;\n }\n const lexer = opt.hooks ? opt.hooks.provideLexer(blockType) : (blockType ? _Lexer.lex : _Lexer.lexInline);\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 const parser = opt.hooks ? opt.hooks.provideParser(blockType) : (blockType ? _Parser.parse : _Parser.parseInline);\n let html = parser(tokens, opt);\n if (opt.hooks) {\n html = opt.hooks.postprocess(html);\n }\n return html;\n } catch(e) {\n return throwError(e as Error);\n }\n };\n\n return parse;\n }\n\n private onError(silent: boolean, async: boolean) {\n return (e: Error): string | Promise => {\n e.message += '\\nPlease report this to https://github.com/markedjs/marked.';\n\n if (silent) {\n const msg = '

    An error occurred:

    '\n          + escapeHtmlEntities(e.message + '', true)\n          + '
    ';\n if (async) {\n return Promise.resolve(msg);\n }\n return msg;\n }\n\n if (async) {\n return Promise.reject(e);\n }\n throw e;\n };\n }\n}\n"], + "mappings": ";;;;;;;;;;;;mbAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,WAAAE,EAAA,UAAAC,EAAA,WAAAC,EAAA,WAAAC,EAAA,aAAAC,EAAA,iBAAAC,EAAA,cAAAC,EAAA,aAAAC,EAAA,gBAAAC,EAAA,UAAAC,GAAA,WAAAC,EAAA,YAAAC,GAAA,UAAAC,GAAA,gBAAAC,GAAA,WAAAC,GAAA,eAAAC,GAAA,QAAAC,GAAA,eAAAC,KAAA,eAAAC,GAAApB,ICKO,SAASqB,GAA4G,CAC1H,MAAO,CACL,MAAO,GACP,OAAQ,GACR,WAAY,KACZ,IAAK,GACL,MAAO,KACP,SAAU,GACV,SAAU,KACV,OAAQ,GACR,UAAW,KACX,WAAY,IACd,CACF,CAEO,IAAIC,EAAqCD,EAAa,EAEtD,SAASE,EAA+DC,EAA0D,CACvIF,EAAYE,CACd,CCxBA,IAAMC,EAAW,CAAE,KAAM,IAAM,IAAK,EAEpC,SAASC,EAAKC,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,GAAGS,CAAI,EAC1BP,EAAO,SAAWF,EAAe,SACjCM,EAAeJ,EAAO,QAAQ,EACvBA,CACT,EAMAA,EAAO,WAAa,SAASQ,EAA8BC,EAA2D,CACpH,OAAOX,EAAe,WAAWU,EAAQC,CAAQ,CACnD,EASAT,EAAO,YAAcF,EAAe,YAKpCE,EAAO,OAASU,EAChBV,EAAO,OAASU,EAAQ,MACxBV,EAAO,SAAWW,EAClBX,EAAO,aAAeY,EACtBZ,EAAO,MAAQa,EACfb,EAAO,MAAQa,EAAO,IACtBb,EAAO,UAAYc,EACnBd,EAAO,MAAQe,EACff,EAAO,MAAQA,EAER,IAAMG,GAAUH,EAAO,QACjBgB,GAAahB,EAAO,WACpBiB,GAAMjB,EAAO,IACbkB,GAAalB,EAAO,WACpBmB,GAAcnB,EAAO,YACrBoB,GAAQpB,EACRqB,GAASX,EAAQ,MACjBY,GAAQT,EAAO", + "names": ["marked_exports", "__export", "_Hooks", "_Lexer", "Marked", "_Parser", "_Renderer", "_TextRenderer", "_Tokenizer", "_defaults", "_getDefaults", "lexer", "marked", "options", "parse", "parseInline", "parser", "setOptions", "use", "walkTokens", "__toCommonJS", "_getDefaults", "_defaults", "changeDefaults", "newDefaults", "noopTest", "edit", "regex", "opt", "source", "obj", "name", "val", "valSource", "other", "supportsLookbehind", "bull", "indent", "newline", "blockCode", "fences", "hr", "heading", "bullet", "lheadingCore", "lheading", "lheadingGfm", "_paragraph", "blockText", "_blockLabel", "def", "list", "_tag", "_comment", "html", "paragraph", "blockquote", "blockNormal", "gfmTable", "blockGfm", "blockPedantic", "escape", "inlineCode", "br", "inlineText", "_punctuation", "_punctuationOrSpace", "_notPunctuationOrSpace", "punctuation", "_punctuationGfmStrongEm", "_punctuationOrSpaceGfmStrongEm", "_notPunctuationOrSpaceGfmStrongEm", "blockSkip", "emStrongLDelimCore", "emStrongLDelim", "emStrongLDelimGfm", "emStrongRDelimAstCore", "emStrongRDelimAst", "emStrongRDelimAstGfm", "emStrongRDelimUnd", "delLDelim", "delRDelimCore", "delRDelim", "anyPunctuation", "autolink", "_inlineComment", "tag", "_inlineLabel", "link", "reflink", "nolink", "reflinkSearch", "_caseInsensitiveProtocol", "inlineNormal", "inlinePedantic", "inlineGfm", "inlineBreaks", "block", "inline", "escapeReplacements", "getEscapeReplacement", "ch", "escapeHtmlEntities", "html", "encode", "other", "cleanUrl", "href", "splitCells", "tableRow", "count", "row", "match", "offset", "str", "escaped", "curr", "cells", "i", "rtrim", "c", "invert", "l", "suffLen", "currChar", "trimTrailingBlankLines", "lines", "end", "findClosingBracket", "b", "level", "expandTabs", "line", "indent", "col", "expanded", "char", "added", "outputLink", "cap", "link", "raw", "lexer", "rules", "href", "title", "text", "token", "indentCodeCompensation", "matchIndentToCode", "indentToCode", "node", "matchIndentInNode", "indentInNode", "_Tokenizer", "options", "_defaults", "src", "trimTrailingBlankLines", "trimmed", "rtrim", "lines", "tokens", "inBlockquote", "currentLines", "i", "currentRaw", "currentText", "top", "lastToken", "oldToken", "newText", "newToken", "bull", "isordered", "list", "itemRegex", "endsWithBlankLine", "endEarly", "itemContents", "line", "expandTabs", "nextLine", "blankLine", "indent", "nextBulletRegex", "hrRegex", "fencesBeginRegex", "headingBeginRegex", "htmlBeginRegex", "blockquoteBeginRegex", "rawLine", "nextLineWithoutTabs", "lastItem", "item", "taskRaw", "checkboxToken", "spacers", "t", "hasMultipleLineBreaks", "tag", "headers", "splitCells", "aligns", "rows", "align", "row", "cell", "trimmedUrl", "rtrimSlash", "lastParenIndex", "findClosingBracket", "linkLen", "links", "linkString", "maskedSrc", "prevChar", "match", "lLength", "rDelim", "rLength", "delimTotal", "midDelimTotal", "endReg", "lastCharLength", "hasNonSpaceChars", "hasSpaceCharsOnBothEnds", "prevCapZero", "escaped", "_Lexer", "__Lexer", "options", "_defaults", "_Tokenizer", "rules", "other", "block", "inline", "src", "i", "next", "tokens", "lastParagraphClipped", "token", "extTokenizer", "lastToken", "cutSrc", "startIndex", "tempSrc", "tempStart", "getStartIndex", "errMsg", "maskedSrc", "match", "links", "offset", "keepPrevChar", "prevChar", "_Renderer", "options", "_defaults", "token", "text", "lang", "escaped", "langString", "other", "code", "escapeHtmlEntities", "tokens", "depth", "ordered", "start", "body", "j", "item", "type", "startAttr", "checked", "header", "cell", "row", "k", "content", "href", "title", "cleanHref", "cleanUrl", "out", "_TextRenderer", "text", "raw", "_Parser", "__Parser", "options", "_defaults", "_Renderer", "_TextRenderer", "tokens", "out", "i", "anyToken", "genericToken", "ret", "token", "errMsg", "renderer", "_Hooks", "options", "_defaults", "markdown", "html", "tokens", "src", "block", "_Lexer", "_Parser", "Marked", "_getDefaults", "_Parser", "_Renderer", "_TextRenderer", "_Lexer", "_Tokenizer", "_Hooks", "args", "tokens", "callback", "values", "token", "tableToken", "cell", "row", "listToken", "genericToken", "childTokens", "extensions", "pack", "opts", "ext", "prevRenderer", "ret", "extLevel", "renderer", "prop", "rendererProp", "rendererFunc", "tokenizer", "tokenizerProp", "tokenizerFunc", "prevTokenizer", "hooks", "hooksProp", "hooksFunc", "prevHook", "arg", "walkTokens", "packWalktokens", "opt", "src", "options", "blockType", "origOpt", "throwError", "processedSrc", "processedTokens", "html", "e", "silent", "async", "msg", "escapeHtmlEntities", "markedInstance", "Marked", "marked", "src", "opt", "options", "changeDefaults", "_getDefaults", "_defaults", "args", "tokens", "callback", "_Parser", "_Renderer", "_TextRenderer", "_Lexer", "_Tokenizer", "_Hooks", "setOptions", "use", "walkTokens", "parseInline", "parse", "parser", "lexer"] +} diff --git a/node_modules/marked/man/marked.1 b/node_modules/marked/man/marked.1 new file mode 100644 index 0000000..a6b432b --- /dev/null +++ b/node_modules/marked/man/marked.1 @@ -0,0 +1,113 @@ +.TH "MARKED" "1" "April 2026" "17.0.6" +.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) 2018+, MarkedJS\. (MIT License) +.br +Copyright (c) 2011\-2018, Christopher Jeffrey\. (MIT License) +.SH SEE ALSO +.P +markdown(1), nodejs(1) + diff --git a/node_modules/marked/man/marked.1.md b/node_modules/marked/man/marked.1.md new file mode 100644 index 0000000..0275511 --- /dev/null +++ b/node_modules/marked/man/marked.1.md @@ -0,0 +1,93 @@ +# 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) 2018+, MarkedJS. (MIT License) +Copyright (c) 2011-2018, Christopher Jeffrey. (MIT License) + +## SEE ALSO + +markdown(1), nodejs(1) diff --git a/node_modules/marked/package.json b/node_modules/marked/package.json new file mode 100644 index 0000000..63a1c34 --- /dev/null +++ b/node_modules/marked/package.json @@ -0,0 +1,103 @@ +{ + "name": "marked", + "description": "A markdown parser built for speed", + "author": "Christopher Jeffrey", + "version": "18.0.0", + "type": "module", + "main": "./lib/marked.esm.js", + "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/" + ], + "exports": { + ".": { + "types": "./lib/marked.d.ts", + "default": "./lib/marked.esm.js" + }, + "./bin/marked": "./bin/marked.js", + "./package.json": "./package.json" + }, + "publishConfig": { + "provenance": true + }, + "repository": { + "type": "git", + "url": "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": { + "@arethetypeswrong/cli": "^0.18.2", + "@markedjs/eslint-config": "^1.0.14", + "@markedjs/testutils": "17.0.1-2", + "@semantic-release/commit-analyzer": "^13.0.1", + "@semantic-release/git": "^10.0.1", + "@semantic-release/github": "^12.0.6", + "@semantic-release/npm": "^13.1.5", + "@semantic-release/release-notes-generator": "^14.1.0", + "cheerio": "1.2.0", + "commonmark": "0.31.2", + "cross-env": "^10.1.0", + "dts-bundle-generator": "^9.5.1", + "esbuild": "^0.28.0", + "esbuild-plugin-umd-wrapper": "^3.0.0", + "eslint": "^10.2.0", + "highlight.js": "^11.11.1", + "markdown-it": "14.1.1", + "marked-highlight": "^2.2.3", + "marked-man": "^2.1.0", + "recheck": "^4.5.0", + "rimraf": "^6.1.3", + "semantic-release": "^25.0.3", + "titleize": "^4.0.0", + "tslib": "^2.8.1", + "typescript": "6.0.2" + }, + "scripts": { + "bench": "npm run build && node test/bench.js", + "build": "npm run build:esbuild && npm run build:types && npm run build:man", + "build:docs": "npm run build && node docs/build.js", + "build:esbuild": "node esbuild.config.js", + "build:man": "marked-man man/marked.1.md > man/marked.1", + "build:reset": "rimraf ./lib ./public", + "build:types": "tsc && dts-bundle-generator --export-referenced-types --project tsconfig.json -o lib/marked.d.ts src/marked.ts", + "lint": "eslint --fix", + "rules": "node test/rules.js", + "test": "npm run build:reset && npm run build:docs && npm run test:specs && npm run test:unit && npm run test:umd && npm run test:cjs && npm run test:types && npm run test:lint", + "test:cjs": "node test/cjs-test.cjs", + "test:lint": "eslint", + "test:only": "npm run build && npm run test:specs:only && npm run test:unit:only", + "test:redos": "node test/recheck.ts > vuln.js", + "test:specs:only": "node --test --test-only --test-reporter=spec test/run-spec-tests.js", + "test:specs": "node --test --test-reporter=spec test/run-spec-tests.js", + "test:types": "tsc --project tsconfig-type-test.json && attw -P --entrypoints . --profile esm-only", + "test:umd": "node test/umd-test.js", + "test:unit:only": "node --test --test-only --test-reporter=spec test/unit/*.test.js", + "test:unit": "node --test --test-reporter=spec test/unit/*.test.js", + "test:update": "node test/update-specs.js" + }, + "engines": { + "node": ">= 20" + } +} diff --git a/node_modules/mitt/LICENSE b/node_modules/mitt/LICENSE new file mode 100644 index 0000000..84c52fe --- /dev/null +++ b/node_modules/mitt/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Jason Miller + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/mitt/README.md b/node_modules/mitt/README.md new file mode 100644 index 0000000..0219f3a --- /dev/null +++ b/node_modules/mitt/README.md @@ -0,0 +1,205 @@ +

    + mitt +
    +
    npm + build status + gzip size +

    + +# Mitt + +> Tiny 200b functional event emitter / pubsub. + +- **Microscopic:** weighs less than 200 bytes gzipped +- **Useful:** a wildcard `"*"` event type listens to all events +- **Familiar:** same names & ideas as [Node's EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter) +- **Functional:** methods don't rely on `this` +- **Great Name:** somehow [mitt](https://npm.im/mitt) wasn't taken + +Mitt was made for the browser, but works in any JavaScript runtime. It has no dependencies and supports IE9+. + +## Table of Contents + +- [Install](#install) +- [Usage](#usage) +- [Examples & Demos](#examples--demos) +- [API](#api) +- [Contribute](#contribute) +- [License](#license) + +## Install + +This project uses [node](http://nodejs.org) and [npm](https://npmjs.com). Go check them out if you don't have them locally installed. + +```sh +$ npm install --save mitt +``` + +Then with a module bundler like [rollup](http://rollupjs.org/) or [webpack](https://webpack.js.org/), use as you would anything else: + +```javascript +// using ES6 modules +import mitt from 'mitt' + +// using CommonJS modules +var mitt = require('mitt') +``` + +The [UMD](https://github.com/umdjs/umd) build is also available on [unpkg](https://unpkg.com): + +```html + +``` + +You can find the library on `window.mitt`. + +## Usage + +```js +import mitt from 'mitt' + +const emitter = mitt() + +// listen to an event +emitter.on('foo', e => console.log('foo', e) ) + +// listen to all events +emitter.on('*', (type, e) => console.log(type, e) ) + +// fire an event +emitter.emit('foo', { a: 'b' }) + +// clearing all events +emitter.all.clear() + +// working with handler references: +function onFoo() {} +emitter.on('foo', onFoo) // listen +emitter.off('foo', onFoo) // unlisten +``` + +### Typescript + +Set `"strict": true` in your tsconfig.json to get improved type inference for `mitt` instance methods. + +```ts +import mitt from 'mitt'; + +type Events = { + foo: string; + bar?: number; +}; + +const emitter = mitt(); // inferred as Emitter + +emitter.on('foo', (e) => {}); // 'e' has inferred type 'string' + +emitter.emit('foo', 42); // Error: Argument of type 'number' is not assignable to parameter of type 'string'. (2345) +``` + +Alternatively, you can use the provided `Emitter` type: + +```ts +import mitt, { Emitter } from 'mitt'; + +type Events = { + foo: string; + bar?: number; +}; + +const emitter: Emitter = mitt(); +``` + +## Examples & Demos + + + Preact + Mitt Codepen Demo +
    + preact + mitt preview +
    + +* * * + +## API + + + +#### Table of Contents + +- [mitt](#mitt) +- [all](#all) +- [on](#on) + - [Parameters](#parameters) +- [off](#off) + - [Parameters](#parameters-1) +- [emit](#emit) + - [Parameters](#parameters-2) + +### mitt + +Mitt: Tiny (~200b) functional event emitter / pubsub. + +Returns **Mitt** + +### all + +A Map of event names to registered handler functions. + +### on + +Register an event handler for the given type. + +#### Parameters + +- `type` **([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [symbol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol))** Type of event to listen for, or `'*'` for all events +- `handler` **[Function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function)** Function to call in response to given event + +### off + +Remove an event handler for the given type. +If `handler` is omitted, all handlers of the given type are removed. + +#### Parameters + +- `type` **([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [symbol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol))** Type of event to unregister `handler` from, or `'*'` +- `handler` **[Function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function)?** Handler function to remove + +### emit + +Invoke all handlers for the given type. +If present, `'*'` handlers are invoked after type-matched handlers. + +Note: Manually firing '\*' handlers is not supported. + +#### Parameters + +- `type` **([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [symbol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol))** The event type to invoke +- `evt` **Any?** Any value (object is recommended and powerful), passed to each handler + +## Contribute + +First off, thanks for taking the time to contribute! +Now, take a moment to be sure your contributions make sense to everyone else. + +### Reporting Issues + +Found a problem? Want a new feature? First of all see if your issue or idea has [already been reported](../../issues). +If don't, just open a [new clear and descriptive issue](../../issues/new). + +### Submitting pull requests + +Pull requests are the greatest contributions, so be sure they are focused in scope, and do avoid unrelated commits. + +- Fork it! +- Clone your fork: `git clone https://github.com//mitt` +- Navigate to the newly cloned directory: `cd mitt` +- Create a new branch for the new feature: `git checkout -b my-new-feature` +- Install the tools necessary for development: `npm install` +- Make your changes. +- Commit your changes: `git commit -am 'Add some feature'` +- Push to the branch: `git push origin my-new-feature` +- Submit a pull request with full remarks documenting your changes. + +## License + +[MIT License](https://opensource.org/licenses/MIT) © [Jason Miller](https://jasonformat.com/) diff --git a/node_modules/mitt/dist/mitt.js b/node_modules/mitt/dist/mitt.js new file mode 100644 index 0000000..b30a31a --- /dev/null +++ b/node_modules/mitt/dist/mitt.js @@ -0,0 +1,2 @@ +module.exports=function(n){return{all:n=n||new Map,on:function(e,t){var i=n.get(e);i?i.push(t):n.set(e,[t])},off:function(e,t){var i=n.get(e);i&&(t?i.splice(i.indexOf(t)>>>0,1):n.set(e,[]))},emit:function(e,t){var i=n.get(e);i&&i.slice().map(function(n){n(t)}),(i=n.get("*"))&&i.slice().map(function(n){n(e,t)})}}}; +//# sourceMappingURL=mitt.js.map diff --git a/node_modules/mitt/dist/mitt.js.map b/node_modules/mitt/dist/mitt.js.map new file mode 100644 index 0000000..d726004 --- /dev/null +++ b/node_modules/mitt/dist/mitt.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mitt.js","sources":["../src/index.ts"],"sourcesContent":["export type EventType = string | symbol;\n\n// An event handler can take an optional event argument\n// and should not return a value\nexport type Handler = (event: T) => void;\nexport type WildcardHandler> = (\n\ttype: keyof T,\n\tevent: T[keyof T]\n) => void;\n\n// An array of all currently registered event handlers for a type\nexport type EventHandlerList = Array>;\nexport type WildCardEventHandlerList> = Array<\n\tWildcardHandler\n>;\n\n// A map of event types and their corresponding event handlers.\nexport type EventHandlerMap> = Map<\n\tkeyof Events | '*',\n\tEventHandlerList | WildCardEventHandlerList\n>;\n\nexport interface Emitter> {\n\tall: EventHandlerMap;\n\n\ton(type: Key, handler: Handler): void;\n\ton(type: '*', handler: WildcardHandler): void;\n\n\toff(\n\t\ttype: Key,\n\t\thandler?: Handler\n\t): void;\n\toff(type: '*', handler: WildcardHandler): void;\n\n\temit(type: Key, event: Events[Key]): void;\n\temit(\n\t\ttype: undefined extends Events[Key] ? Key : never\n\t): void;\n}\n\n/**\n * Mitt: Tiny (~200b) functional event emitter / pubsub.\n * @name mitt\n * @returns {Mitt}\n */\nexport default function mitt>(\n\tall?: EventHandlerMap\n): Emitter {\n\ttype GenericEventHandler =\n\t\t| Handler\n\t\t| WildcardHandler;\n\tall = all || new Map();\n\n\treturn {\n\t\t/**\n\t\t * A Map of event names to registered handler functions.\n\t\t */\n\t\tall,\n\n\t\t/**\n\t\t * Register an event handler for the given type.\n\t\t * @param {string|symbol} type Type of event to listen for, or `'*'` for all events\n\t\t * @param {Function} handler Function to call in response to given event\n\t\t * @memberOf mitt\n\t\t */\n\t\ton(type: Key, handler: GenericEventHandler) {\n\t\t\tconst handlers: Array | undefined = all!.get(type);\n\t\t\tif (handlers) {\n\t\t\t\thandlers.push(handler);\n\t\t\t} else {\n\t\t\t\tall!.set(type, [handler] as EventHandlerList);\n\t\t\t}\n\t\t},\n\n\t\t/**\n\t\t * Remove an event handler for the given type.\n\t\t * If `handler` is omitted, all handlers of the given type are removed.\n\t\t * @param {string|symbol} type Type of event to unregister `handler` from (`'*'` to remove a wildcard handler)\n\t\t * @param {Function} [handler] Handler function to remove\n\t\t * @memberOf mitt\n\t\t */\n\t\toff(type: Key, handler?: GenericEventHandler) {\n\t\t\tconst handlers: Array | undefined = all!.get(type);\n\t\t\tif (handlers) {\n\t\t\t\tif (handler) {\n\t\t\t\t\thandlers.splice(handlers.indexOf(handler) >>> 0, 1);\n\t\t\t\t} else {\n\t\t\t\t\tall!.set(type, []);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\n\t\t/**\n\t\t * Invoke all handlers for the given type.\n\t\t * If present, `'*'` handlers are invoked after type-matched handlers.\n\t\t *\n\t\t * Note: Manually firing '*' handlers is not supported.\n\t\t *\n\t\t * @param {string|symbol} type The event type to invoke\n\t\t * @param {Any} [evt] Any value (object is recommended and powerful), passed to each handler\n\t\t * @memberOf mitt\n\t\t */\n\t\temit(type: Key, evt?: Events[Key]) {\n\t\t\tlet handlers = all!.get(type);\n\t\t\tif (handlers) {\n\t\t\t\t(handlers as EventHandlerList)\n\t\t\t\t\t.slice()\n\t\t\t\t\t.map((handler) => {\n\t\t\t\t\t\thandler(evt!);\n\t\t\t\t\t});\n\t\t\t}\n\n\t\t\thandlers = all!.get('*');\n\t\t\tif (handlers) {\n\t\t\t\t(handlers as WildCardEventHandlerList)\n\t\t\t\t\t.slice()\n\t\t\t\t\t.map((handler) => {\n\t\t\t\t\t\thandler(type, evt!);\n\t\t\t\t\t});\n\t\t\t}\n\t\t}\n\t};\n}\n"],"names":["all","Map","on","type","handler","handlers","get","push","set","off","splice","indexOf","emit","evt","slice","map"],"mappings":"wBA8CCA,GAOA,MAAO,CAINA,IANDA,EAAMA,GAAO,IAAIC,IAchBC,YAA6BC,EAAWC,GACvC,IAAMC,EAAmDL,EAAKM,IAAIH,GAC9DE,EACHA,EAASE,KAAKH,GAEdJ,EAAKQ,IAAIL,EAAM,CAACC,KAWlBK,aAA8BN,EAAWC,GACxC,IAAMC,EAAmDL,EAAKM,IAAIH,GAC9DE,IACCD,EACHC,EAASK,OAAOL,EAASM,QAAQP,KAAa,EAAG,GAEjDJ,EAAKQ,IAAIL,EAAM,MAelBS,cAA+BT,EAAWU,GACzC,IAAIR,EAAWL,EAAKM,IAAIH,GACpBE,GACFA,EACCS,QACAC,IAAI,SAACX,GACLA,EAAQS,MAIXR,EAAWL,EAAKM,IAAI,OAElBD,EACCS,QACAC,IAAI,SAACX,GACLA,EAAQD,EAAMU"} \ No newline at end of file diff --git a/node_modules/mitt/dist/mitt.mjs b/node_modules/mitt/dist/mitt.mjs new file mode 100644 index 0000000..5a2e73a --- /dev/null +++ b/node_modules/mitt/dist/mitt.mjs @@ -0,0 +1,2 @@ +export default function(n){return{all:n=n||new Map,on:function(t,e){var i=n.get(t);i?i.push(e):n.set(t,[e])},off:function(t,e){var i=n.get(t);i&&(e?i.splice(i.indexOf(e)>>>0,1):n.set(t,[]))},emit:function(t,e){var i=n.get(t);i&&i.slice().map(function(n){n(e)}),(i=n.get("*"))&&i.slice().map(function(n){n(t,e)})}}} +//# sourceMappingURL=mitt.mjs.map diff --git a/node_modules/mitt/dist/mitt.mjs.map b/node_modules/mitt/dist/mitt.mjs.map new file mode 100644 index 0000000..c4204e8 --- /dev/null +++ b/node_modules/mitt/dist/mitt.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"mitt.mjs","sources":["../src/index.ts"],"sourcesContent":["export type EventType = string | symbol;\n\n// An event handler can take an optional event argument\n// and should not return a value\nexport type Handler = (event: T) => void;\nexport type WildcardHandler> = (\n\ttype: keyof T,\n\tevent: T[keyof T]\n) => void;\n\n// An array of all currently registered event handlers for a type\nexport type EventHandlerList = Array>;\nexport type WildCardEventHandlerList> = Array<\n\tWildcardHandler\n>;\n\n// A map of event types and their corresponding event handlers.\nexport type EventHandlerMap> = Map<\n\tkeyof Events | '*',\n\tEventHandlerList | WildCardEventHandlerList\n>;\n\nexport interface Emitter> {\n\tall: EventHandlerMap;\n\n\ton(type: Key, handler: Handler): void;\n\ton(type: '*', handler: WildcardHandler): void;\n\n\toff(\n\t\ttype: Key,\n\t\thandler?: Handler\n\t): void;\n\toff(type: '*', handler: WildcardHandler): void;\n\n\temit(type: Key, event: Events[Key]): void;\n\temit(\n\t\ttype: undefined extends Events[Key] ? Key : never\n\t): void;\n}\n\n/**\n * Mitt: Tiny (~200b) functional event emitter / pubsub.\n * @name mitt\n * @returns {Mitt}\n */\nexport default function mitt>(\n\tall?: EventHandlerMap\n): Emitter {\n\ttype GenericEventHandler =\n\t\t| Handler\n\t\t| WildcardHandler;\n\tall = all || new Map();\n\n\treturn {\n\t\t/**\n\t\t * A Map of event names to registered handler functions.\n\t\t */\n\t\tall,\n\n\t\t/**\n\t\t * Register an event handler for the given type.\n\t\t * @param {string|symbol} type Type of event to listen for, or `'*'` for all events\n\t\t * @param {Function} handler Function to call in response to given event\n\t\t * @memberOf mitt\n\t\t */\n\t\ton(type: Key, handler: GenericEventHandler) {\n\t\t\tconst handlers: Array | undefined = all!.get(type);\n\t\t\tif (handlers) {\n\t\t\t\thandlers.push(handler);\n\t\t\t} else {\n\t\t\t\tall!.set(type, [handler] as EventHandlerList);\n\t\t\t}\n\t\t},\n\n\t\t/**\n\t\t * Remove an event handler for the given type.\n\t\t * If `handler` is omitted, all handlers of the given type are removed.\n\t\t * @param {string|symbol} type Type of event to unregister `handler` from (`'*'` to remove a wildcard handler)\n\t\t * @param {Function} [handler] Handler function to remove\n\t\t * @memberOf mitt\n\t\t */\n\t\toff(type: Key, handler?: GenericEventHandler) {\n\t\t\tconst handlers: Array | undefined = all!.get(type);\n\t\t\tif (handlers) {\n\t\t\t\tif (handler) {\n\t\t\t\t\thandlers.splice(handlers.indexOf(handler) >>> 0, 1);\n\t\t\t\t} else {\n\t\t\t\t\tall!.set(type, []);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\n\t\t/**\n\t\t * Invoke all handlers for the given type.\n\t\t * If present, `'*'` handlers are invoked after type-matched handlers.\n\t\t *\n\t\t * Note: Manually firing '*' handlers is not supported.\n\t\t *\n\t\t * @param {string|symbol} type The event type to invoke\n\t\t * @param {Any} [evt] Any value (object is recommended and powerful), passed to each handler\n\t\t * @memberOf mitt\n\t\t */\n\t\temit(type: Key, evt?: Events[Key]) {\n\t\t\tlet handlers = all!.get(type);\n\t\t\tif (handlers) {\n\t\t\t\t(handlers as EventHandlerList)\n\t\t\t\t\t.slice()\n\t\t\t\t\t.map((handler) => {\n\t\t\t\t\t\thandler(evt!);\n\t\t\t\t\t});\n\t\t\t}\n\n\t\t\thandlers = all!.get('*');\n\t\t\tif (handlers) {\n\t\t\t\t(handlers as WildCardEventHandlerList)\n\t\t\t\t\t.slice()\n\t\t\t\t\t.map((handler) => {\n\t\t\t\t\t\thandler(type, evt!);\n\t\t\t\t\t});\n\t\t\t}\n\t\t}\n\t};\n}\n"],"names":["all","Map","on","type","handler","handlers","get","push","set","off","splice","indexOf","emit","evt","slice","map"],"mappings":"wBA8CCA,GAOA,MAAO,CAINA,IANDA,EAAMA,GAAO,IAAIC,IAchBC,YAA6BC,EAAWC,GACvC,IAAMC,EAAmDL,EAAKM,IAAIH,GAC9DE,EACHA,EAASE,KAAKH,GAEdJ,EAAKQ,IAAIL,EAAM,CAACC,KAWlBK,aAA8BN,EAAWC,GACxC,IAAMC,EAAmDL,EAAKM,IAAIH,GAC9DE,IACCD,EACHC,EAASK,OAAOL,EAASM,QAAQP,KAAa,EAAG,GAEjDJ,EAAKQ,IAAIL,EAAM,MAelBS,cAA+BT,EAAWU,GACzC,IAAIR,EAAWL,EAAKM,IAAIH,GACpBE,GACFA,EACCS,QACAC,IAAI,SAACX,GACLA,EAAQS,MAIXR,EAAWL,EAAKM,IAAI,OAElBD,EACCS,QACAC,IAAI,SAACX,GACLA,EAAQD,EAAMU"} \ No newline at end of file diff --git a/node_modules/mitt/dist/mitt.umd.js b/node_modules/mitt/dist/mitt.umd.js new file mode 100644 index 0000000..6820e65 --- /dev/null +++ b/node_modules/mitt/dist/mitt.umd.js @@ -0,0 +1,2 @@ +!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(e=e||self).mitt=n()}(this,function(){return function(e){return{all:e=e||new Map,on:function(n,t){var f=e.get(n);f?f.push(t):e.set(n,[t])},off:function(n,t){var f=e.get(n);f&&(t?f.splice(f.indexOf(t)>>>0,1):e.set(n,[]))},emit:function(n,t){var f=e.get(n);f&&f.slice().map(function(e){e(t)}),(f=e.get("*"))&&f.slice().map(function(e){e(n,t)})}}}}); +//# sourceMappingURL=mitt.umd.js.map diff --git a/node_modules/mitt/dist/mitt.umd.js.map b/node_modules/mitt/dist/mitt.umd.js.map new file mode 100644 index 0000000..ebb8e62 --- /dev/null +++ b/node_modules/mitt/dist/mitt.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mitt.umd.js","sources":["../src/index.ts"],"sourcesContent":["export type EventType = string | symbol;\n\n// An event handler can take an optional event argument\n// and should not return a value\nexport type Handler = (event: T) => void;\nexport type WildcardHandler> = (\n\ttype: keyof T,\n\tevent: T[keyof T]\n) => void;\n\n// An array of all currently registered event handlers for a type\nexport type EventHandlerList = Array>;\nexport type WildCardEventHandlerList> = Array<\n\tWildcardHandler\n>;\n\n// A map of event types and their corresponding event handlers.\nexport type EventHandlerMap> = Map<\n\tkeyof Events | '*',\n\tEventHandlerList | WildCardEventHandlerList\n>;\n\nexport interface Emitter> {\n\tall: EventHandlerMap;\n\n\ton(type: Key, handler: Handler): void;\n\ton(type: '*', handler: WildcardHandler): void;\n\n\toff(\n\t\ttype: Key,\n\t\thandler?: Handler\n\t): void;\n\toff(type: '*', handler: WildcardHandler): void;\n\n\temit(type: Key, event: Events[Key]): void;\n\temit(\n\t\ttype: undefined extends Events[Key] ? Key : never\n\t): void;\n}\n\n/**\n * Mitt: Tiny (~200b) functional event emitter / pubsub.\n * @name mitt\n * @returns {Mitt}\n */\nexport default function mitt>(\n\tall?: EventHandlerMap\n): Emitter {\n\ttype GenericEventHandler =\n\t\t| Handler\n\t\t| WildcardHandler;\n\tall = all || new Map();\n\n\treturn {\n\t\t/**\n\t\t * A Map of event names to registered handler functions.\n\t\t */\n\t\tall,\n\n\t\t/**\n\t\t * Register an event handler for the given type.\n\t\t * @param {string|symbol} type Type of event to listen for, or `'*'` for all events\n\t\t * @param {Function} handler Function to call in response to given event\n\t\t * @memberOf mitt\n\t\t */\n\t\ton(type: Key, handler: GenericEventHandler) {\n\t\t\tconst handlers: Array | undefined = all!.get(type);\n\t\t\tif (handlers) {\n\t\t\t\thandlers.push(handler);\n\t\t\t} else {\n\t\t\t\tall!.set(type, [handler] as EventHandlerList);\n\t\t\t}\n\t\t},\n\n\t\t/**\n\t\t * Remove an event handler for the given type.\n\t\t * If `handler` is omitted, all handlers of the given type are removed.\n\t\t * @param {string|symbol} type Type of event to unregister `handler` from (`'*'` to remove a wildcard handler)\n\t\t * @param {Function} [handler] Handler function to remove\n\t\t * @memberOf mitt\n\t\t */\n\t\toff(type: Key, handler?: GenericEventHandler) {\n\t\t\tconst handlers: Array | undefined = all!.get(type);\n\t\t\tif (handlers) {\n\t\t\t\tif (handler) {\n\t\t\t\t\thandlers.splice(handlers.indexOf(handler) >>> 0, 1);\n\t\t\t\t} else {\n\t\t\t\t\tall!.set(type, []);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\n\t\t/**\n\t\t * Invoke all handlers for the given type.\n\t\t * If present, `'*'` handlers are invoked after type-matched handlers.\n\t\t *\n\t\t * Note: Manually firing '*' handlers is not supported.\n\t\t *\n\t\t * @param {string|symbol} type The event type to invoke\n\t\t * @param {Any} [evt] Any value (object is recommended and powerful), passed to each handler\n\t\t * @memberOf mitt\n\t\t */\n\t\temit(type: Key, evt?: Events[Key]) {\n\t\t\tlet handlers = all!.get(type);\n\t\t\tif (handlers) {\n\t\t\t\t(handlers as EventHandlerList)\n\t\t\t\t\t.slice()\n\t\t\t\t\t.map((handler) => {\n\t\t\t\t\t\thandler(evt!);\n\t\t\t\t\t});\n\t\t\t}\n\n\t\t\thandlers = all!.get('*');\n\t\t\tif (handlers) {\n\t\t\t\t(handlers as WildCardEventHandlerList)\n\t\t\t\t\t.slice()\n\t\t\t\t\t.map((handler) => {\n\t\t\t\t\t\thandler(type, evt!);\n\t\t\t\t\t});\n\t\t\t}\n\t\t}\n\t};\n}\n"],"names":["all","Map","on","type","handler","handlers","get","push","set","off","splice","indexOf","emit","evt","slice","map"],"mappings":"6LA8CCA,GAOA,MAAO,CAINA,IANDA,EAAMA,GAAO,IAAIC,IAchBC,YAA6BC,EAAWC,GACvC,IAAMC,EAAmDL,EAAKM,IAAIH,GAC9DE,EACHA,EAASE,KAAKH,GAEdJ,EAAKQ,IAAIL,EAAM,CAACC,KAWlBK,aAA8BN,EAAWC,GACxC,IAAMC,EAAmDL,EAAKM,IAAIH,GAC9DE,IACCD,EACHC,EAASK,OAAOL,EAASM,QAAQP,KAAa,EAAG,GAEjDJ,EAAKQ,IAAIL,EAAM,MAelBS,cAA+BT,EAAWU,GACzC,IAAIR,EAAWL,EAAKM,IAAIH,GACpBE,GACFA,EACCS,QACAC,IAAI,SAACX,GACLA,EAAQS,MAIXR,EAAWL,EAAKM,IAAI,OAElBD,EACCS,QACAC,IAAI,SAACX,GACLA,EAAQD,EAAMU"} \ No newline at end of file diff --git a/node_modules/mitt/index.d.ts b/node_modules/mitt/index.d.ts new file mode 100644 index 0000000..10dc70d --- /dev/null +++ b/node_modules/mitt/index.d.ts @@ -0,0 +1,21 @@ +export declare type EventType = string | symbol; +export declare type Handler = (event: T) => void; +export declare type WildcardHandler> = (type: keyof T, event: T[keyof T]) => void; +export declare type EventHandlerList = Array>; +export declare type WildCardEventHandlerList> = Array>; +export declare type EventHandlerMap> = Map | WildCardEventHandlerList>; +export interface Emitter> { + all: EventHandlerMap; + on(type: Key, handler: Handler): void; + on(type: '*', handler: WildcardHandler): void; + off(type: Key, handler?: Handler): void; + off(type: '*', handler: WildcardHandler): void; + emit(type: Key, event: Events[Key]): void; + emit(type: undefined extends Events[Key] ? Key : never): void; +} +/** + * Mitt: Tiny (~200b) functional event emitter / pubsub. + * @name mitt + * @returns {Mitt} + */ +export default function mitt>(all?: EventHandlerMap): Emitter; diff --git a/node_modules/mitt/package.json b/node_modules/mitt/package.json new file mode 100644 index 0000000..e51397c --- /dev/null +++ b/node_modules/mitt/package.json @@ -0,0 +1,85 @@ +{ + "name": "mitt", + "version": "3.0.1", + "description": "Tiny 200b functional Event Emitter / pubsub.", + "module": "dist/mitt.mjs", + "main": "dist/mitt.js", + "jsnext:main": "dist/mitt.mjs", + "umd:main": "dist/mitt.umd.js", + "source": "src/index.ts", + "typings": "index.d.ts", + "exports": { + "types": "./index.d.ts", + "module": "./dist/mitt.mjs", + "import": "./dist/mitt.mjs", + "require": "./dist/mitt.js", + "default": "./dist/mitt.mjs" + }, + "scripts": { + "test": "npm-run-all --silent typecheck lint mocha test-types", + "mocha": "mocha test", + "test-types": "tsc test/test-types-compilation.ts --noEmit --strict", + "lint": "eslint src test --ext ts --ext js", + "typecheck": "tsc --noEmit", + "bundle": "microbundle -f es,cjs,umd", + "build": "npm-run-all --silent clean -p bundle -s docs", + "clean": "rimraf dist", + "docs": "documentation readme src/index.ts --section API -q --parse-extension ts", + "release": "npm run -s build -s && npm t && git commit -am $npm_package_version && git tag $npm_package_version && git push && git push --tags && npm publish" + }, + "repository": "developit/mitt", + "keywords": [ + "events", + "eventemitter", + "emitter", + "pubsub" + ], + "homepage": "https://github.com/developit/mitt", + "authors": [ + "Jason Miller " + ], + "license": "MIT", + "files": [ + "dist", + "index.d.ts" + ], + "mocha": { + "extension": [ + "ts" + ], + "require": [ + "ts-node/register", + "esm" + ], + "spec": [ + "test/*_test.ts" + ] + }, + "prettier": { + "singleQuote": true, + "trailingComma": "none" + }, + "devDependencies": { + "@types/chai": "^4.2.11", + "@types/mocha": "^7.0.2", + "@types/sinon": "^9.0.4", + "@types/sinon-chai": "^3.2.4", + "@typescript-eslint/eslint-plugin": "^5.61.0", + "@typescript-eslint/parser": "^5.61.0", + "chai": "^4.2.0", + "documentation": "^14.0.2", + "eslint": "^7.32.0", + "eslint-config-developit": "^1.2.0", + "eslint-plugin-compat": "^4.1.4", + "esm": "^3.2.25", + "microbundle": "^0.12.3", + "mocha": "^8.0.1", + "npm-run-all": "^4.1.5", + "prettier": "^2.8.8", + "rimraf": "^3.0.2", + "sinon": "^9.0.2", + "sinon-chai": "^3.5.0", + "ts-node": "^10.9.1", + "typescript": "^4.9.5" + } +} diff --git a/node_modules/ms/index.js b/node_modules/ms/index.js new file mode 100644 index 0000000..ea734fb --- /dev/null +++ b/node_modules/ms/index.js @@ -0,0 +1,162 @@ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function (val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} diff --git a/node_modules/ms/license.md b/node_modules/ms/license.md new file mode 100644 index 0000000..fa5d39b --- /dev/null +++ b/node_modules/ms/license.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2020 Vercel, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/ms/package.json b/node_modules/ms/package.json new file mode 100644 index 0000000..4997189 --- /dev/null +++ b/node_modules/ms/package.json @@ -0,0 +1,38 @@ +{ + "name": "ms", + "version": "2.1.3", + "description": "Tiny millisecond conversion utility", + "repository": "vercel/ms", + "main": "./index", + "files": [ + "index.js" + ], + "scripts": { + "precommit": "lint-staged", + "lint": "eslint lib/* bin/*", + "test": "mocha tests.js" + }, + "eslintConfig": { + "extends": "eslint:recommended", + "env": { + "node": true, + "es6": true + } + }, + "lint-staged": { + "*.js": [ + "npm run lint", + "prettier --single-quote --write", + "git add" + ] + }, + "license": "MIT", + "devDependencies": { + "eslint": "4.18.2", + "expect.js": "0.3.1", + "husky": "0.14.3", + "lint-staged": "5.0.0", + "mocha": "4.0.1", + "prettier": "2.0.5" + } +} diff --git a/node_modules/ms/readme.md b/node_modules/ms/readme.md new file mode 100644 index 0000000..0fc1abb --- /dev/null +++ b/node_modules/ms/readme.md @@ -0,0 +1,59 @@ +# ms + +![CI](https://github.com/vercel/ms/workflows/CI/badge.svg) + +Use this package to easily convert various time formats to milliseconds. + +## Examples + +```js +ms('2 days') // 172800000 +ms('1d') // 86400000 +ms('10h') // 36000000 +ms('2.5 hrs') // 9000000 +ms('2h') // 7200000 +ms('1m') // 60000 +ms('5s') // 5000 +ms('1y') // 31557600000 +ms('100') // 100 +ms('-3 days') // -259200000 +ms('-1h') // -3600000 +ms('-200') // -200 +``` + +### Convert from Milliseconds + +```js +ms(60000) // "1m" +ms(2 * 60000) // "2m" +ms(-3 * 60000) // "-3m" +ms(ms('10 hours')) // "10h" +``` + +### Time Format Written-Out + +```js +ms(60000, { long: true }) // "1 minute" +ms(2 * 60000, { long: true }) // "2 minutes" +ms(-3 * 60000, { long: true }) // "-3 minutes" +ms(ms('10 hours'), { long: true }) // "10 hours" +``` + +## Features + +- Works both in [Node.js](https://nodejs.org) and in the browser +- If a number is supplied to `ms`, a string with a unit is returned +- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`) +- If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned + +## Related Packages + +- [ms.macro](https://github.com/knpwrs/ms.macro) - Run `ms` as a macro at build-time. + +## Caught a Bug? + +1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device +2. Link the package to the global module directory: `npm link` +3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, Node.js will now use your clone of ms! + +As always, you can run the tests using: `npm test` diff --git a/node_modules/netmask/CHANGELOG.md b/node_modules/netmask/CHANGELOG.md new file mode 100644 index 0000000..bf27c95 --- /dev/null +++ b/node_modules/netmask/CHANGELOG.md @@ -0,0 +1,66 @@ +## v2.0.2 (Apr 2, 2021) + +### Bugfixes + +* Fix `08` parsed as decimal while `018` rejected. ([commit](https://github.com/rs/node-netmask/commit/50a0053bd869b72313cc96ab73108bb83079c3f5)) + +## v2.0.1 (Mar 29, 2021) + +### IMPORTANT: Security Fix + +> This version contains an important security fix. If you are using netmask `<=2.0.0`, please upgrade to `2.0.1` or above. + +* Rewrite byte parsing without using JS `parseInt()`([commit](https://github.com/rs/node-netmask/commit/3f19a056c4eb808ea4a29f234274c67bc5a848f4)) + * This is [CVE-2021-29418](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-29418). + +### Bugfixes + +* Add checks on spaces before and after bytes + * This will now throw an exception when spaces are present like ' 1.2.3.4' or '1. 2.3.4' or '1.2.3.4 '. + +### Internal Changes + +* Avoid some useless memory allocations +* New Mocha testing suite, thanks @kaoudis [#36](https://github.com/rs/node-netmask/pull/36) + +## v2.0.0 (Mar 19, 2021) + +### Breaking Change + +Previous API was treating IPs with less than four bytes as IP with a +netmask of the size of the provided bytes (1=8, 2=16, 3=24) and was +interpreting the IP as if it was completed with 0s on the right side. + +*Proper IP parsing for these is to consider missing bytes as being 0s on +the left side.* + +Mask size is no longer infered by the number of bytes provided. + +This means that the input `216.240` will no longer be interpreted as `216.240.0.0/16`, but as `0.0.216.240/32`, +as per convention. + +See [the change](https://github.com/rs/node-netmask/commit/9f9fc38c6db1a682d23289b5c9dc2009d957a00b). + +### Bugfixes + +* Fix improper parsing of hex bytes + +## v1.1.0 (Mar 18, 2021) + +### IMPORTANT: Security Fix + +> This version contains an important security fix. If you are using netmask `<=1.0.6`, please upgrade to `1.1.0` or above. + +* Fix improper parsing of octal bytes ([commit](https://github.com/rs/node-netmask/commit/4678fd840ad0b4730dbad2d415712c0782e886cc)) + * This is [CVE-2021-28918](https://sick.codes/sick-2021-011). + * See also the [npm advisory](https://www.npmjs.com/advisories/1658) + +### Other Changes + +* Performance: Avoid large allocations when provided large netmasks (like `/8`) + * Thanks @dschenkelman [#34](https://github.com/rs/node-netmask/pull/34) + +## v1.0.6 (May 30, 2016) + +* Changes before this release are not documented here. Please see [the commit list](https://github.com/rs/node-netmask/commits/master) + or the [compare view](https://github.com/rs/node-netmask/compare/1.0.5...rs:1.0.6). diff --git a/node_modules/netmask/LICENSE.md b/node_modules/netmask/LICENSE.md new file mode 100644 index 0000000..e2a68d5 --- /dev/null +++ b/node_modules/netmask/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2011 Olivier Poitrey rs@rhapsodyk.net + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/netmask/README.md b/node_modules/netmask/README.md new file mode 100644 index 0000000..45d717b --- /dev/null +++ b/node_modules/netmask/README.md @@ -0,0 +1,112 @@ +Netmask +======= + +The Netmask class parses and understands IPv4 and IPv6 CIDR blocks so they can be explored and compared. This module is highly inspired by Perl [Net::Netmask](http://search.cpan.org/dist/Net-Netmask/) module. + +Synopsis +-------- + +### IPv4 + +```js +var Netmask = require('netmask').Netmask + +var block = new Netmask('10.0.0.0/12'); +block.base; // 10.0.0.0 +block.mask; // 255.240.0.0 +block.bitmask; // 12 +block.hostmask; // 0.15.255.255 +block.broadcast; // 10.15.255.255 +block.size; // 1048576 +block.first; // 10.0.0.1 +block.last; // 10.15.255.254 + +block.contains('10.0.8.10'); // true +block.contains('10.8.0.10'); // true +block.contains('192.168.1.20'); // false + +block.next() // Netmask('10.16.0.0/12') +``` + +### IPv6 + +```js +var Netmask = require('netmask').Netmask + +var block = new Netmask('2001:db8::/32'); +block.base; // 2001:db8:: +block.bitmask; // 32 +block.first; // 2001:db8:: +block.last; // 2001:db8:ffff:ffff:ffff:ffff:ffff:ffff + +block.contains('2001:db8::1'); // true +block.contains('2001:db9::1'); // false + +block.next() // Netmask('2001:db9::/32') +``` + +Constructing +------------ + +Netmask objects are created with an IP address and optionally a mask. The IP version is detected automatically. There are many forms that are recognized: + +### IPv4 + +``` +'216.240.32.0/24' // The preferred form. +'216.240.32.0/255.255.255.0' +'216.240.32.0', '255.255.255.0' +'216.240.32.0', 0xffffff00 +'216.240.32.4' // A /32 block. +'0330.0360.040.04' // Octal form +'0xd8.0xf0.0x20.0x4' // Hex form +``` + +### IPv6 + +``` +'2001:db8::/32' // The preferred form. +'2001:db8::', 32 +'::1' // A /128 block. +'::ffff:192.168.1.1/120' // Mixed IPv4-mapped form. +'fe80::1%eth0' // Zone IDs are stripped. +``` + +API +--- + +- `.base`: The base address of the network block as a string (eg: 216.240.32.0 or 2001:db8::). Base does not give an indication of the size of the network block. +- `.mask`: The netmask as a string (eg: 255.255.255.0 or ffff:ffff::). +- `.hostmask`: The host mask which is the opposite of the netmask (eg: 0.0.0.255). +- `.bitmask`: The netmask as a number of bits in the network portion of the address for this block (eg: 24). +- `.size`: The number of IP addresses in a block (eg: 256). +- `.maskLong`: **Deprecated.** The netmask as an unsigned 32-bit integer. Only meaningful for IPv4; returns `0` for IPv6. +- `.netLong`: **Deprecated.** The base address as an unsigned 32-bit integer. Only meaningful for IPv4; returns `0` for IPv6. +- `.broadcast`: The blocks broadcast address (eg: 192.168.1.0/24 => 192.168.1.255). Always `undefined` for IPv6. +- `.first`, `.last`: First and last useable address. +- `.contains(ip or block)`: Returns a true if the IP number `ip` is part of the network. That is, a true value is returned if `ip` is between `base` and `broadcast`. If a Netmask object or a block is given, it returns true only of the given block fits inside the network. +- `.next(count)`: Without a `count`, return the next block of the same size after the current one. With a count, return the Nth block after the current one. A count of -1 returns the previous block. Undef will be returned if out of legal address space. +- `.toString()`: The netmask in base/bitmask format (e.g., '216.240.32.0/24') + +Installation +------------ + + $ npm install netmask + +Run all tests +------------- + + $ npm test + +License +------- + +(The MIT License) + +Copyright (c) 2011 Olivier Poitrey + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/netmask/dist/netmask.d.ts b/node_modules/netmask/dist/netmask.d.ts new file mode 100644 index 0000000..bf1b05e --- /dev/null +++ b/node_modules/netmask/dist/netmask.d.ts @@ -0,0 +1,21 @@ +import { ip2long, long2ip } from './netmask4'; +declare class Netmask { + base: string; + mask: string; + hostmask: string; + bitmask: number; + maskLong: number; + netLong: number; + size: number; + first: string; + last: string; + broadcast: string | undefined; + private _impl; + constructor(net: string, mask?: string | number); + contains(ip: string | Netmask): boolean; + next(count?: number): Netmask; + /** @deprecated */ + forEach(fn: (ip: string, long: number, index: number) => void): void; + toString(): string; +} +export { Netmask, ip2long, long2ip }; diff --git a/node_modules/netmask/dist/netmask.js b/node_modules/netmask/dist/netmask.js new file mode 100644 index 0000000..4c69836 --- /dev/null +++ b/node_modules/netmask/dist/netmask.js @@ -0,0 +1,68 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.long2ip = exports.ip2long = exports.Netmask = void 0; +const netmask4_1 = require("./netmask4"); +Object.defineProperty(exports, "ip2long", { enumerable: true, get: function () { return netmask4_1.ip2long; } }); +Object.defineProperty(exports, "long2ip", { enumerable: true, get: function () { return netmask4_1.long2ip; } }); +const netmask6_1 = require("./netmask6"); +class Netmask { + constructor(net, mask) { + if (typeof net !== 'string') { + throw new Error("Missing `net' parameter"); + } + // Detect IPv6: check the address part (before any /) for ':' + const addrPart = net.indexOf('/') !== -1 ? net.substring(0, net.indexOf('/')) : net; + if (addrPart.indexOf(':') !== -1) { + this._impl = new netmask6_1.Netmask6Impl(net, mask); + } + else { + this._impl = new netmask4_1.Netmask4Impl(net, mask); + } + this.base = this._impl.base; + this.mask = this._impl.mask; + this.hostmask = this._impl.hostmask; + this.bitmask = this._impl.bitmask; + this.size = this._impl.size; + this.first = this._impl.first; + this.last = this._impl.last; + this.broadcast = this._impl.broadcast; + if (this._impl instanceof netmask4_1.Netmask4Impl) { + this.maskLong = this._impl.maskLong; + this.netLong = this._impl.netLong; + } + else { + this.maskLong = 0; + this.netLong = 0; + } + } + contains(ip) { + if (typeof ip === 'string') { + // If it has a '/', it's a CIDR block — wrap it + if (ip.indexOf('/') > 0) { + ip = new Netmask(ip); + } + // IPv4 shorthand (fewer than 4 octets, no colons) — wrap it + else if (ip.indexOf(':') === -1 && ip.split('.').length !== 4) { + ip = new Netmask(ip); + } + } + if (ip instanceof Netmask) { + return this.contains(ip.base) && this.contains(ip.broadcast || ip.last); + } + // Plain IP string — delegate to impl + return this._impl.contains(ip); + } + next(count = 1) { + const nextImpl = this._impl.next(count); + const result = new Netmask(nextImpl.base, nextImpl.bitmask); + return result; + } + /** @deprecated */ + forEach(fn) { + this._impl.forEach(fn); + } + toString() { + return this._impl.toString(); + } +} +exports.Netmask = Netmask; diff --git a/node_modules/netmask/dist/netmask4.d.ts b/node_modules/netmask/dist/netmask4.d.ts new file mode 100644 index 0000000..147f265 --- /dev/null +++ b/node_modules/netmask/dist/netmask4.d.ts @@ -0,0 +1,20 @@ +declare function long2ip(long: number): string; +declare function ip2long(ip: string): number; +declare class Netmask4Impl { + maskLong: number; + bitmask: number; + netLong: number; + size: number; + base: string; + mask: string; + hostmask: string; + first: string; + last: string; + broadcast: string | undefined; + constructor(net: string, mask?: string | number); + contains(ip: string | Netmask4Impl): boolean; + next(count?: number): Netmask4Impl; + forEach(fn: (ip: string, long: number, index: number) => void): void; + toString(): string; +} +export { ip2long, long2ip, Netmask4Impl }; diff --git a/node_modules/netmask/dist/netmask4.js b/node_modules/netmask/dist/netmask4.js new file mode 100644 index 0000000..082476c --- /dev/null +++ b/node_modules/netmask/dist/netmask4.js @@ -0,0 +1,189 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Netmask4Impl = void 0; +exports.ip2long = ip2long; +exports.long2ip = long2ip; +function long2ip(long) { + const a = (long & (0xff << 24)) >>> 24; + const b = (long & (0xff << 16)) >>> 16; + const c = (long & (0xff << 8)) >>> 8; + const d = long & 0xff; + return [a, b, c, d].join('.'); +} +const chr0 = '0'.charCodeAt(0); +const chra = 'a'.charCodeAt(0); +const chrA = 'A'.charCodeAt(0); +function parseNum(s) { + let n = 0; + let base = 10; + let dmax = '9'; + let i = 0; + if (s.length > 1 && s[i] === '0') { + if (s[i + 1] === 'x' || s[i + 1] === 'X') { + i += 2; + base = 16; + } + else if ('0' <= s[i + 1] && s[i + 1] <= '9') { + i++; + base = 8; + dmax = '7'; + } + } + const start = i; + while (i < s.length) { + if ('0' <= s[i] && s[i] <= dmax) { + n = (n * base + (s.charCodeAt(i) - chr0)) >>> 0; + } + else if (base === 16) { + if ('a' <= s[i] && s[i] <= 'f') { + n = (n * base + (10 + s.charCodeAt(i) - chra)) >>> 0; + } + else if ('A' <= s[i] && s[i] <= 'F') { + n = (n * base + (10 + s.charCodeAt(i) - chrA)) >>> 0; + } + else { + break; + } + } + else { + break; + } + if (n > 0xFFFFFFFF) { + throw new Error('too large'); + } + i++; + } + if (i === start) { + throw new Error('empty octet'); + } + return [n, i]; +} +function ip2long(ip) { + const b = []; + for (let i = 0; i <= 3; i++) { + if (ip.length === 0) { + break; + } + if (i > 0) { + if (ip[0] !== '.') { + throw new Error('Invalid IP'); + } + ip = ip.substring(1); + } + const [n, c] = parseNum(ip); + ip = ip.substring(c); + b.push(n); + } + if (ip.length !== 0) { + throw new Error('Invalid IP'); + } + switch (b.length) { + case 1: + if (b[0] > 0xFFFFFFFF) { + throw new Error('Invalid IP'); + } + return b[0] >>> 0; + case 2: + if (b[0] > 0xFF || b[1] > 0xFFFFFF) { + throw new Error('Invalid IP'); + } + return (b[0] << 24 | b[1]) >>> 0; + case 3: + if (b[0] > 0xFF || b[1] > 0xFF || b[2] > 0xFFFF) { + throw new Error('Invalid IP'); + } + return (b[0] << 24 | b[1] << 16 | b[2]) >>> 0; + case 4: + if (b[0] > 0xFF || b[1] > 0xFF || b[2] > 0xFF || b[3] > 0xFF) { + throw new Error('Invalid IP'); + } + return (b[0] << 24 | b[1] << 16 | b[2] << 8 | b[3]) >>> 0; + default: + throw new Error('Invalid IP'); + } +} +class Netmask4Impl { + constructor(net, mask) { + if (typeof net !== 'string') { + throw new Error("Missing `net' parameter"); + } + let maskStr = mask; + if (!maskStr) { + const parts = net.split('/', 2); + net = parts[0]; + maskStr = parts[1]; + } + if (!maskStr) { + maskStr = 32; + } + if (typeof maskStr === 'string' && maskStr.indexOf('.') > -1) { + try { + this.maskLong = ip2long(maskStr); + } + catch (error) { + throw new Error("Invalid mask: " + maskStr); + } + this.bitmask = NaN; + for (let i = 32; i >= 0; i--) { + if (this.maskLong === (0xffffffff << (32 - i)) >>> 0) { + this.bitmask = i; + break; + } + } + } + else if (maskStr || maskStr === 0) { + this.bitmask = parseInt(maskStr, 10); + this.maskLong = 0; + if (this.bitmask > 0) { + this.maskLong = (0xffffffff << (32 - this.bitmask)) >>> 0; + } + } + else { + throw new Error("Invalid mask: empty"); + } + try { + this.netLong = (ip2long(net) & this.maskLong) >>> 0; + } + catch (error) { + throw new Error("Invalid net address: " + net); + } + if (!(this.bitmask <= 32)) { + throw new Error("Invalid mask for ip4: " + maskStr); + } + this.size = Math.pow(2, 32 - this.bitmask); + this.base = long2ip(this.netLong); + this.mask = long2ip(this.maskLong); + this.hostmask = long2ip(~this.maskLong); + this.first = this.bitmask <= 30 ? long2ip(this.netLong + 1) : this.base; + this.last = this.bitmask <= 30 ? long2ip(this.netLong + this.size - 2) : long2ip(this.netLong + this.size - 1); + this.broadcast = this.bitmask <= 30 ? long2ip(this.netLong + this.size - 1) : undefined; + } + contains(ip) { + if (typeof ip === 'string' && (ip.indexOf('/') > 0 || ip.split('.').length !== 4)) { + ip = new Netmask4Impl(ip); + } + if (ip instanceof Netmask4Impl) { + return this.contains(ip.base) && this.contains((ip.broadcast || ip.last)); + } + else { + return (ip2long(ip) & this.maskLong) >>> 0 === (this.netLong & this.maskLong) >>> 0; + } + } + next(count = 1) { + return new Netmask4Impl(long2ip(this.netLong + (this.size * count)), this.mask); + } + forEach(fn) { + let long = ip2long(this.first); + const lastLong = ip2long(this.last); + let index = 0; + while (long <= lastLong) { + fn(long2ip(long), long, index); + index++; + long++; + } + } + toString() { + return this.base + "/" + this.bitmask; + } +} +exports.Netmask4Impl = Netmask4Impl; diff --git a/node_modules/netmask/dist/netmask6.d.ts b/node_modules/netmask/dist/netmask6.d.ts new file mode 100644 index 0000000..7328292 --- /dev/null +++ b/node_modules/netmask/dist/netmask6.d.ts @@ -0,0 +1,20 @@ +declare function ip6bigint(ip: string): bigint; +declare function bigint2ip6(n: bigint): string; +declare class Netmask6Impl { + netBigint: bigint; + maskBigint: bigint; + bitmask: number; + size: number; + base: string; + mask: string; + hostmask: string; + first: string; + last: string; + broadcast: undefined; + constructor(net: string, mask?: number); + contains(ip: string | Netmask6Impl): boolean; + next(count?: number): Netmask6Impl; + forEach(fn: (ip: string, long: number, index: number) => void): void; + toString(): string; +} +export { ip6bigint, bigint2ip6, Netmask6Impl }; diff --git a/node_modules/netmask/dist/netmask6.js b/node_modules/netmask/dist/netmask6.js new file mode 100644 index 0000000..960db5b --- /dev/null +++ b/node_modules/netmask/dist/netmask6.js @@ -0,0 +1,187 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Netmask6Impl = void 0; +exports.ip6bigint = ip6bigint; +exports.bigint2ip6 = bigint2ip6; +const netmask4_1 = require("./netmask4"); +const MAX_IPV6 = (1n << 128n) - 1n; +function ip6bigint(ip) { + // Strip zone ID (e.g. %eth0) + const zoneIdx = ip.indexOf('%'); + if (zoneIdx !== -1) { + ip = ip.substring(0, zoneIdx); + } + // Handle mixed IPv4-mapped (e.g. ::ffff:192.168.1.1) + const lastColon = ip.lastIndexOf(':'); + if (lastColon !== -1 && ip.indexOf('.', lastColon) !== -1) { + const ipv4Part = ip.substring(lastColon + 1); + const ipv4Long = (0, netmask4_1.ip2long)(ipv4Part); + // IPv4 part replaces last 2 groups (32 bits), expand prefix to 6 groups + const ipv6Prefix = ip.substring(0, lastColon + 1) + '0:0'; + const prefixVal = parseIPv6Pure(ipv6Prefix); + return (prefixVal & ~0xffffffffn) | BigInt(ipv4Long); + } + return parseIPv6Pure(ip); +} +function parseIPv6Pure(ip) { + const doubleColonIdx = ip.indexOf('::'); + let groups; + if (doubleColonIdx !== -1) { + const left = ip.substring(0, doubleColonIdx); + const right = ip.substring(doubleColonIdx + 2); + const leftGroups = left === '' ? [] : left.split(':'); + const rightGroups = right === '' ? [] : right.split(':'); + const missing = 8 - leftGroups.length - rightGroups.length; + if (missing < 0) { + throw new Error('Invalid IPv6: too many groups'); + } + groups = [...leftGroups, ...Array(missing).fill('0'), ...rightGroups]; + } + else { + groups = ip.split(':'); + } + if (groups.length !== 8) { + throw new Error('Invalid IPv6: expected 8 groups, got ' + groups.length); + } + let result = 0n; + for (let i = 0; i < 8; i++) { + const g = groups[i]; + if (g.length === 0 || g.length > 4) { + throw new Error('Invalid IPv6: bad group "' + g + '"'); + } + const val = parseInt(g, 16); + if (isNaN(val) || val < 0 || val > 0xffff) { + throw new Error('Invalid IPv6: bad group "' + g + '"'); + } + result = (result << 16n) | BigInt(val); + } + return result; +} +function bigint2ip6(n) { + if (n < 0n || n > MAX_IPV6) { + throw new Error('Invalid IPv6 address value'); + } + const groups = []; + for (let i = 0; i < 8; i++) { + groups.unshift(Number(n & 0xffffn)); + n >>= 16n; + } + // RFC 5952: find longest run of consecutive zero groups + let bestStart = -1; + let bestLen = 0; + let curStart = -1; + let curLen = 0; + for (let i = 0; i < 8; i++) { + if (groups[i] === 0) { + if (curStart === -1) { + curStart = i; + curLen = 1; + } + else { + curLen++; + } + } + else { + if (curLen > bestLen && curLen >= 2) { + bestStart = curStart; + bestLen = curLen; + } + curStart = -1; + curLen = 0; + } + } + if (curLen > bestLen && curLen >= 2) { + bestStart = curStart; + bestLen = curLen; + } + if (bestStart !== -1 && bestStart + bestLen === 8 && bestStart > 0) { + const before = groups.slice(0, bestStart).map(g => g.toString(16)); + return before.join(':') + '::'; + } + else if (bestStart === 0) { + const after = groups.slice(bestLen).map(g => g.toString(16)); + return '::' + after.join(':'); + } + else if (bestStart > 0) { + const before = groups.slice(0, bestStart).map(g => g.toString(16)); + const after = groups.slice(bestStart + bestLen).map(g => g.toString(16)); + return before.join(':') + '::' + after.join(':'); + } + else { + return groups.map(g => g.toString(16)).join(':'); + } +} +class Netmask6Impl { + constructor(net, mask) { + if (typeof net !== 'string') { + throw new Error("Missing `net' parameter"); + } + let prefixLen = mask; + if (prefixLen === undefined || prefixLen === null) { + const slashIdx = net.indexOf('/'); + if (slashIdx !== -1) { + prefixLen = parseInt(net.substring(slashIdx + 1), 10); + net = net.substring(0, slashIdx); + } + else { + prefixLen = 128; + } + } + if (isNaN(prefixLen) || prefixLen < 0 || prefixLen > 128) { + throw new Error('Invalid mask for IPv6: ' + prefixLen); + } + this.bitmask = prefixLen; + if (this.bitmask === 0) { + this.maskBigint = 0n; + } + else { + this.maskBigint = (MAX_IPV6 >> BigInt(128 - this.bitmask)) << BigInt(128 - this.bitmask); + } + try { + this.netBigint = ip6bigint(net) & this.maskBigint; + } + catch (error) { + throw new Error('Invalid IPv6 net address: ' + net); + } + this.size = Number(1n << BigInt(128 - this.bitmask)); + this.base = bigint2ip6(this.netBigint); + this.mask = bigint2ip6(this.maskBigint); + this.hostmask = bigint2ip6(~this.maskBigint & MAX_IPV6); + this.first = this.base; + this.last = bigint2ip6(this.netBigint + (1n << BigInt(128 - this.bitmask)) - 1n); + this.broadcast = undefined; + } + contains(ip) { + if (typeof ip === 'string') { + if (ip.indexOf('/') > 0) { + ip = new Netmask6Impl(ip); + } + } + if (ip instanceof Netmask6Impl) { + return this.contains(ip.base) && this.contains(ip.last); + } + else { + const addr = ip6bigint(ip); + return (addr & this.maskBigint) === this.netBigint; + } + } + next(count = 1) { + const sizeBig = 1n << BigInt(128 - this.bitmask); + return new Netmask6Impl(bigint2ip6(this.netBigint + sizeBig * BigInt(count)), this.bitmask); + } + forEach(fn) { + let addr = this.netBigint; + const sizeBig = 1n << BigInt(128 - this.bitmask); + const lastAddr = this.netBigint + sizeBig - 1n; + let index = 0; + while (addr <= lastAddr) { + fn(bigint2ip6(addr), Number(addr), index); + index++; + addr++; + } + } + toString() { + return this.base + '/' + this.bitmask; + } +} +exports.Netmask6Impl = Netmask6Impl; diff --git a/node_modules/netmask/package.json b/node_modules/netmask/package.json new file mode 100644 index 0000000..2cce46c --- /dev/null +++ b/node_modules/netmask/package.json @@ -0,0 +1,45 @@ +{ + "author": "Olivier Poitrey ", + "name": "netmask", + "description": "Parse and lookup IP network blocks", + "version": "2.1.1", + "homepage": "https://github.com/rs/node-netmask", + "bugs": "https://github.com/rs/node-netmask/issues", + "license": "MIT", + "repository": { + "type": "git", + "url": "git://github.com/rs/node-netmask.git" + }, + "keywords": [ + "net", + "mask", + "ip", + "network", + "cidr", + "netmask", + "subnet", + "ipcalc" + ], + "files": [ + "dist", + "README.md", + "CHANGELOG.md", + "LICENSE" + ], + "main": "./dist/netmask", + "types": "./dist/netmask.d.ts", + "scripts": { + "prepublish": "tsc", + "test": "tsc && mocha --require ts-node/register tests/*.ts" + }, + "engines": { + "node": ">= 0.4.0" + }, + "devDependencies": { + "@types/mocha": "^9.0.0", + "@types/node": "^18.0.0", + "mocha": "^10.2.0", + "ts-node": "^10.0.0", + "typescript": "^5.0.0" + } +} diff --git a/node_modules/once/LICENSE b/node_modules/once/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/once/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/once/README.md b/node_modules/once/README.md new file mode 100644 index 0000000..1f1ffca --- /dev/null +++ b/node_modules/once/README.md @@ -0,0 +1,79 @@ +# once + +Only call a function once. + +## usage + +```javascript +var once = require('once') + +function load (file, cb) { + cb = once(cb) + loader.load('file') + loader.once('load', cb) + loader.once('error', cb) +} +``` + +Or add to the Function.prototype in a responsible way: + +```javascript +// only has to be done once +require('once').proto() + +function load (file, cb) { + cb = cb.once() + loader.load('file') + loader.once('load', cb) + loader.once('error', cb) +} +``` + +Ironically, the prototype feature makes this module twice as +complicated as necessary. + +To check whether you function has been called, use `fn.called`. Once the +function is called for the first time the return value of the original +function is saved in `fn.value` and subsequent calls will continue to +return this value. + +```javascript +var once = require('once') + +function load (cb) { + cb = once(cb) + var stream = createStream() + stream.once('data', cb) + stream.once('end', function () { + if (!cb.called) cb(new Error('not found')) + }) +} +``` + +## `once.strict(func)` + +Throw an error if the function is called twice. + +Some functions are expected to be called only once. Using `once` for them would +potentially hide logical errors. + +In the example below, the `greet` function has to call the callback only once: + +```javascript +function greet (name, cb) { + // return is missing from the if statement + // when no name is passed, the callback is called twice + if (!name) cb('Hello anonymous') + cb('Hello ' + name) +} + +function log (msg) { + console.log(msg) +} + +// this will print 'Hello anonymous' but the logical error will be missed +greet(null, once(msg)) + +// once.strict will print 'Hello anonymous' and throw an error when the callback will be called the second time +greet(null, once.strict(msg)) +``` diff --git a/node_modules/once/once.js b/node_modules/once/once.js new file mode 100644 index 0000000..2354067 --- /dev/null +++ b/node_modules/once/once.js @@ -0,0 +1,42 @@ +var wrappy = require('wrappy') +module.exports = wrappy(once) +module.exports.strict = wrappy(onceStrict) + +once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true + }) + + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }) +}) + +function once (fn) { + var f = function () { + if (f.called) return f.value + f.called = true + return f.value = fn.apply(this, arguments) + } + f.called = false + return f +} + +function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true + return f.value = fn.apply(this, arguments) + } + var name = fn.name || 'Function wrapped with `once`' + f.onceError = name + " shouldn't be called more than once" + f.called = false + return f +} diff --git a/node_modules/once/package.json b/node_modules/once/package.json new file mode 100644 index 0000000..16815b2 --- /dev/null +++ b/node_modules/once/package.json @@ -0,0 +1,33 @@ +{ + "name": "once", + "version": "1.4.0", + "description": "Run a function exactly one time", + "main": "once.js", + "directories": { + "test": "test" + }, + "dependencies": { + "wrappy": "1" + }, + "devDependencies": { + "tap": "^7.0.1" + }, + "scripts": { + "test": "tap test/*.js" + }, + "files": [ + "once.js" + ], + "repository": { + "type": "git", + "url": "git://github.com/isaacs/once" + }, + "keywords": [ + "once", + "function", + "one", + "single" + ], + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "license": "ISC" +} diff --git a/node_modules/pac-proxy-agent/LICENSE b/node_modules/pac-proxy-agent/LICENSE new file mode 100644 index 0000000..0dc3bc0 --- /dev/null +++ b/node_modules/pac-proxy-agent/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014 Nathan Rajlich + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/pac-proxy-agent/README.md b/node_modules/pac-proxy-agent/README.md new file mode 100644 index 0000000..990a7b7 --- /dev/null +++ b/node_modules/pac-proxy-agent/README.md @@ -0,0 +1,27 @@ +pac-proxy-agent +=============== +### A [PAC file][pac-wikipedia] proxy `http.Agent` implementation for HTTP and HTTPS + +This module provides an `http.Agent` implementation that retreives the specified +[PAC proxy file][pac-wikipedia] and uses it to resolve which HTTP, HTTPS, or +SOCKS proxy, or if a direct connection should be used to connect to the +HTTP endpoint. + +It is designed to be be used with the built-in `http` and `https` modules. + +Example +------- + +```ts +import * as http from 'http'; +import { PacProxyAgent } from 'pac-proxy-agent'; + +const agent = new PacProxyAgent('pac+https://cloudup.com/ceGH2yZ0Bjp+'); + +http.get('http://nodejs.org/api/', { agent }, (res) => { + console.log('"response" event!', res.headers); + res.pipe(process.stdout); +}); +``` + +[pac-wikipedia]: http://wikipedia.org/wiki/Proxy_auto-config diff --git a/node_modules/pac-proxy-agent/dist/index.d.ts b/node_modules/pac-proxy-agent/dist/index.d.ts new file mode 100644 index 0000000..901600f --- /dev/null +++ b/node_modules/pac-proxy-agent/dist/index.d.ts @@ -0,0 +1,60 @@ +/// +/// +/// +/// +import * as net from 'net'; +import * as http from 'http'; +import { Readable } from 'stream'; +import { URL } from 'url'; +import { Agent, AgentConnectOpts } from 'agent-base'; +import type { HttpProxyAgentOptions } from 'http-proxy-agent'; +import type { HttpsProxyAgentOptions } from 'https-proxy-agent'; +import type { SocksProxyAgentOptions } from 'socks-proxy-agent'; +import { protocols as gProtocols, ProtocolOpts as GetUriOptions } from 'get-uri'; +import { FindProxyForURL, PacResolverOptions } from 'pac-resolver'; +type Protocols = keyof typeof gProtocols; +type Protocol = T extends `pac+${infer P}:${infer _}` ? P : T extends `${infer P}:${infer _}` ? P : never; +export type PacProxyAgentOptions = http.AgentOptions & PacResolverOptions & GetUriOptions<`${Protocol}:`> & HttpProxyAgentOptions<''> & HttpsProxyAgentOptions<''> & SocksProxyAgentOptions & { + fallbackToDirect?: boolean; +}; +/** + * The `PacProxyAgent` class. + * + * A few different "protocol" modes are supported (supported protocols are + * backed by the `get-uri` module): + * + * - "pac+data", "data" - refers to an embedded "data:" URI + * - "pac+file", "file" - refers to a local file + * - "pac+ftp", "ftp" - refers to a file located on an FTP server + * - "pac+http", "http" - refers to an HTTP endpoint + * - "pac+https", "https" - refers to an HTTPS endpoint + */ +export declare class PacProxyAgent extends Agent { + static readonly protocols: `pac+${Protocols}`[]; + uri: URL; + opts: PacProxyAgentOptions; + cache?: Readable; + resolver?: FindProxyForURL; + resolverHash: string; + resolverPromise?: Promise; + constructor(uri: Uri | URL, opts?: PacProxyAgentOptions); + private clearResolverPromise; + /** + * Loads the PAC proxy file from the source if necessary, and returns + * a generated `FindProxyForURL()` resolver function to use. + */ + getResolver(): Promise; + private loadResolver; + /** + * Loads the contents of the PAC proxy file. + * + * @api private + */ + private loadPacFile; + /** + * Called when the node-core HTTP client library is creating a new HTTP request. + */ + connect(req: http.ClientRequest, opts: AgentConnectOpts): Promise; +} +export {}; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/pac-proxy-agent/dist/index.d.ts.map b/node_modules/pac-proxy-agent/dist/index.d.ts.map new file mode 100644 index 0000000..c106353 --- /dev/null +++ b/node_modules/pac-proxy-agent/dist/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;AAAA,OAAO,KAAK,GAAG,MAAM,KAAK,CAAC;AAE3B,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAI7B,OAAO,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAClC,OAAO,EAAE,GAAG,EAAE,MAAM,KAAK,CAAC;AAC1B,OAAO,EAAE,KAAK,EAAE,gBAAgB,EAAY,MAAM,YAAY,CAAC;AAC/D,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAC9D,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AAChE,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AAChE,OAAO,EAEN,SAAS,IAAI,UAAU,EACvB,YAAY,IAAI,aAAa,EAC7B,MAAM,SAAS,CAAC;AACjB,OAAO,EAEN,eAAe,EACf,kBAAkB,EAClB,MAAM,cAAc,CAAC;AAuBtB,KAAK,SAAS,GAAG,MAAM,OAAO,UAAU,CAAC;AAGzC,KAAK,QAAQ,CAAC,CAAC,IAAI,CAAC,SAAS,OAAO,MAAM,CAAC,IAAI,MAAM,CAAC,EAAE,GACrD,CAAC,GAEH,CAAC,SAAS,GAAG,MAAM,CAAC,IAAI,MAAM,CAAC,EAAE,GAC/B,CAAC,GACD,KAAK,CAAC;AAET,MAAM,MAAM,oBAAoB,CAAC,CAAC,IAAI,IAAI,CAAC,YAAY,GACtD,kBAAkB,GAClB,aAAa,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,GAChC,qBAAqB,CAAC,EAAE,CAAC,GACzB,sBAAsB,CAAC,EAAE,CAAC,GAC1B,sBAAsB,GAAG;IACxB,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAC3B,CAAC;AAEH;;;;;;;;;;;GAWG;AACH,qBAAa,aAAa,CAAC,GAAG,SAAS,MAAM,CAAE,SAAQ,KAAK;IAC3D,MAAM,CAAC,QAAQ,CAAC,SAAS,EAAE,OAAO,SAAS,EAAE,EAAE,CAM7C;IAEF,GAAG,EAAE,GAAG,CAAC;IACT,IAAI,EAAE,oBAAoB,CAAC,GAAG,CAAC,CAAC;IAChC,KAAK,CAAC,EAAE,QAAQ,CAAC;IACjB,QAAQ,CAAC,EAAE,eAAe,CAAC;IAC3B,YAAY,EAAE,MAAM,CAAC;IACrB,eAAe,CAAC,EAAE,OAAO,CAAC,eAAe,CAAC,CAAC;gBAE/B,GAAG,EAAE,GAAG,GAAG,GAAG,EAAE,IAAI,CAAC,EAAE,oBAAoB,CAAC,GAAG,CAAC;IAsB5D,OAAO,CAAC,oBAAoB,CAE1B;IAEF;;;OAGG;IACH,WAAW,IAAI,OAAO,CAAC,eAAe,CAAC;YAWzB,YAAY;IAwC1B;;;;OAIG;YACW,WAAW;IAazB;;OAEG;IACG,OAAO,CACZ,GAAG,EAAE,IAAI,CAAC,aAAa,EACvB,IAAI,EAAE,gBAAgB,GACpB,OAAO,CAAC,IAAI,CAAC,KAAK,GAAG,GAAG,CAAC,MAAM,CAAC;CA2GnC"} \ No newline at end of file diff --git a/node_modules/pac-proxy-agent/dist/index.js b/node_modules/pac-proxy-agent/dist/index.js new file mode 100644 index 0000000..e9fd034 --- /dev/null +++ b/node_modules/pac-proxy-agent/dist/index.js @@ -0,0 +1,238 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PacProxyAgent = void 0; +const net = __importStar(require("net")); +const tls = __importStar(require("tls")); +const crypto = __importStar(require("crypto")); +const events_1 = require("events"); +const debug_1 = __importDefault(require("debug")); +const url_1 = require("url"); +const agent_base_1 = require("agent-base"); +const get_uri_1 = require("get-uri"); +const pac_resolver_1 = require("pac-resolver"); +const quickjs_emscripten_1 = require("@tootallnate/quickjs-emscripten"); +const debug = (0, debug_1.default)('pac-proxy-agent'); +const setServernameFromNonIpHost = (options) => { + if (options.servername === undefined && + options.host && + !net.isIP(options.host)) { + return { + ...options, + servername: options.host, + }; + } + return options; +}; +/** + * The `PacProxyAgent` class. + * + * A few different "protocol" modes are supported (supported protocols are + * backed by the `get-uri` module): + * + * - "pac+data", "data" - refers to an embedded "data:" URI + * - "pac+file", "file" - refers to a local file + * - "pac+ftp", "ftp" - refers to a file located on an FTP server + * - "pac+http", "http" - refers to an HTTP endpoint + * - "pac+https", "https" - refers to an HTTPS endpoint + */ +class PacProxyAgent extends agent_base_1.Agent { + constructor(uri, opts) { + super(opts); + this.clearResolverPromise = () => { + this.resolverPromise = undefined; + }; + // Strip the "pac+" prefix + const uriStr = typeof uri === 'string' ? uri : uri.href; + this.uri = new url_1.URL(uriStr.replace(/^pac\+/i, '')); + debug('Creating PacProxyAgent with URI %o', this.uri.href); + // @ts-expect-error Not sure why TS is complaining here… + this.opts = { ...opts }; + this.cache = undefined; + this.resolver = undefined; + this.resolverHash = ''; + this.resolverPromise = undefined; + // For `PacResolver` + if (!this.opts.filename) { + this.opts.filename = this.uri.href; + } + } + /** + * Loads the PAC proxy file from the source if necessary, and returns + * a generated `FindProxyForURL()` resolver function to use. + */ + getResolver() { + if (!this.resolverPromise) { + this.resolverPromise = this.loadResolver(); + this.resolverPromise.then(this.clearResolverPromise, this.clearResolverPromise); + } + return this.resolverPromise; + } + async loadResolver() { + try { + // (Re)load the contents of the PAC file URI + const [qjs, code] = await Promise.all([ + (0, quickjs_emscripten_1.getQuickJS)(), + this.loadPacFile(), + ]); + // Create a sha1 hash of the JS code + const hash = crypto.createHash('sha1').update(code).digest('hex'); + if (this.resolver && this.resolverHash === hash) { + debug('Same sha1 hash for code - contents have not changed, reusing previous proxy resolver'); + return this.resolver; + } + // Cache the resolver + debug('Creating new proxy resolver instance'); + this.resolver = (0, pac_resolver_1.createPacResolver)(qjs, code, this.opts); + // Store that sha1 hash for future comparison purposes + this.resolverHash = hash; + return this.resolver; + } + catch (err) { + if (this.resolver && + err.code === 'ENOTMODIFIED') { + debug('Got ENOTMODIFIED response, reusing previous proxy resolver'); + return this.resolver; + } + throw err; + } + } + /** + * Loads the contents of the PAC proxy file. + * + * @api private + */ + async loadPacFile() { + debug('Loading PAC file: %o', this.uri); + const rs = await (0, get_uri_1.getUri)(this.uri, { ...this.opts, cache: this.cache }); + debug('Got `Readable` instance for URI'); + this.cache = rs; + const buf = await (0, agent_base_1.toBuffer)(rs); + debug('Read %o byte PAC file from URI', buf.length); + return buf.toString('utf8'); + } + /** + * Called when the node-core HTTP client library is creating a new HTTP request. + */ + async connect(req, opts) { + const { secureEndpoint } = opts; + const isWebSocket = req.getHeader('upgrade') === 'websocket'; + // First, get a generated `FindProxyForURL()` function, + // either cached or retrieved from the source + const resolver = await this.getResolver(); + // Calculate the `url` parameter + const protocol = secureEndpoint ? 'https:' : 'http:'; + const host = opts.host && net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host; + const defaultPort = secureEndpoint ? 443 : 80; + const url = Object.assign(new url_1.URL(req.path, `${protocol}//${host}`), defaultPort ? undefined : { port: opts.port }); + debug('url: %s', url); + let result = await resolver(url); + // Default to "DIRECT" if a falsey value was returned (or nothing) + if (!result) { + result = 'DIRECT'; + } + const proxies = String(result) + .trim() + .split(/\s*;\s*/g) + .filter(Boolean); + if (this.opts.fallbackToDirect && !proxies.includes('DIRECT')) { + proxies.push('DIRECT'); + } + for (const proxy of proxies) { + let agent = null; + let socket = null; + const [type, target] = proxy.split(/\s+/); + debug('Attempting to use proxy: %o', proxy); + if (type === 'DIRECT') { + // Direct connection to the destination endpoint + if (secureEndpoint) { + socket = tls.connect(setServernameFromNonIpHost(opts)); + } + else { + socket = net.connect(opts); + } + } + else if (type === 'SOCKS' || type === 'SOCKS5') { + // Use a SOCKSv5h proxy + const { SocksProxyAgent } = await Promise.resolve().then(() => __importStar(require('socks-proxy-agent'))); + agent = new SocksProxyAgent(`socks://${target}`, this.opts); + } + else if (type === 'SOCKS4') { + // Use a SOCKSv4a proxy + const { SocksProxyAgent } = await Promise.resolve().then(() => __importStar(require('socks-proxy-agent'))); + agent = new SocksProxyAgent(`socks4a://${target}`, this.opts); + } + else if (type === 'PROXY' || + type === 'HTTP' || + type === 'HTTPS') { + // Use an HTTP or HTTPS proxy + // http://dev.chromium.org/developers/design-documents/secure-web-proxy + const proxyURL = `${type === 'HTTPS' ? 'https' : 'http'}://${target}`; + if (secureEndpoint || isWebSocket) { + const { HttpsProxyAgent } = await Promise.resolve().then(() => __importStar(require('https-proxy-agent'))); + agent = new HttpsProxyAgent(proxyURL, this.opts); + } + else { + const { HttpProxyAgent } = await Promise.resolve().then(() => __importStar(require('http-proxy-agent'))); + agent = new HttpProxyAgent(proxyURL, this.opts); + } + } + try { + if (socket) { + // "DIRECT" connection, wait for connection confirmation + await (0, events_1.once)(socket, 'connect'); + req.emit('proxy', { proxy, socket }); + return socket; + } + if (agent) { + const s = await agent.connect(req, opts); + if (!(s instanceof net.Socket)) { + throw new Error('Expected a `net.Socket` to be returned from agent'); + } + req.emit('proxy', { proxy, socket: s }); + return s; + } + throw new Error(`Could not determine proxy type for: ${proxy}`); + } + catch (err) { + debug('Got error for proxy %o: %o', proxy, err); + req.emit('proxy', { proxy, error: err }); + } + } + throw new Error(`Failed to establish a socket connection to proxies: ${JSON.stringify(proxies)}`); + } +} +PacProxyAgent.protocols = [ + 'pac+data', + 'pac+file', + 'pac+ftp', + 'pac+http', + 'pac+https', +]; +exports.PacProxyAgent = PacProxyAgent; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/pac-proxy-agent/dist/index.js.map b/node_modules/pac-proxy-agent/dist/index.js.map new file mode 100644 index 0000000..e41babb --- /dev/null +++ b/node_modules/pac-proxy-agent/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,yCAA2B;AAC3B,yCAA2B;AAE3B,+CAAiC;AACjC,mCAA8B;AAC9B,kDAAgC;AAEhC,6BAA0B;AAC1B,2CAA+D;AAI/D,qCAIiB;AACjB,+CAIsB;AACtB,wEAA6D;AAE7D,MAAM,KAAK,GAAG,IAAA,eAAW,EAAC,iBAAiB,CAAC,CAAC;AAE7C,MAAM,0BAA0B,GAAG,CAGlC,OAAU,EACT,EAAE;IACH,IACC,OAAO,CAAC,UAAU,KAAK,SAAS;QAChC,OAAO,CAAC,IAAI;QACZ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KAAK,CAAC,OAAO,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;oBACzC,IAAI,CAAC,CAAC,CAAC,YAAY,GAAG,CAAC,MAAM,CAAC,EAAE;wBAC/B,MAAM,IAAI,KAAK,CACd,mDAAmD,CACnD,CAAC;qBACF;oBACD,GAAG,CAAC,IAAI,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC,EAAE,CAAC,CAAC;oBACxC,OAAO,CAAC,CAAC;iBACT;gBACD,MAAM,IAAI,KAAK,CAAC,uCAAuC,KAAK,EAAE,CAAC,CAAC;aAChE;YAAC,OAAO,GAAG,EAAE;gBACb,KAAK,CAAC,4BAA4B,EAAE,KAAK,EAAE,GAAG,CAAC,CAAC;gBAChD,GAAG,CAAC,IAAI,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAC;aACzC;SACD;QAED,MAAM,IAAI,KAAK,CACd,uDAAuD,IAAI,CAAC,SAAS,CACpE,OAAO,CACP,EAAE,CACH,CAAC;IACH,CAAC;;AAlOe,uBAAS,GAAyB;IACjD,UAAU;IACV,UAAU;IACV,SAAS;IACT,UAAU;IACV,WAAW;CACX,AANwB,CAMvB;AAPU,sCAAa"} \ No newline at end of file diff --git a/node_modules/pac-proxy-agent/package.json b/node_modules/pac-proxy-agent/package.json new file mode 100644 index 0000000..3d178ae --- /dev/null +++ b/node_modules/pac-proxy-agent/package.json @@ -0,0 +1,58 @@ +{ + "name": "pac-proxy-agent", + "version": "7.2.0", + "description": "A PAC file proxy `http.Agent` implementation for HTTP", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "dist" + ], + "repository": { + "type": "git", + "url": "https://github.com/TooTallNate/proxy-agents.git", + "directory": "packages/pac-proxy-agent" + }, + "keywords": [ + "pac", + "proxy", + "agent", + "http", + "https", + "socks", + "request", + "access" + ], + "author": "Nathan Rajlich (http://n8.io/)", + "license": "MIT", + "dependencies": { + "@tootallnate/quickjs-emscripten": "^0.23.0", + "agent-base": "^7.1.2", + "debug": "^4.3.4", + "get-uri": "^6.0.1", + "http-proxy-agent": "^7.0.0", + "https-proxy-agent": "^7.0.6", + "pac-resolver": "^7.0.1", + "socks-proxy-agent": "^8.0.5" + }, + "devDependencies": { + "@types/debug": "^4.1.7", + "@types/jest": "^29.5.1", + "@types/node": "^14.18.45", + "async-listen": "^3.0.0", + "jest": "^29.5.0", + "socksv5": "0.0.6", + "ts-jest": "^29.1.0", + "typescript": "^5.0.4", + "proxy": "2.2.0", + "tsconfig": "0.0.0" + }, + "engines": { + "node": ">= 14" + }, + "scripts": { + "build": "tsc", + "test": "jest --env node --verbose --bail", + "lint": "eslint --ext .ts", + "pack": "node ../../scripts/pack.mjs" + } +} \ No newline at end of file diff --git a/node_modules/pac-resolver/LICENSE b/node_modules/pac-resolver/LICENSE new file mode 100644 index 0000000..008728c --- /dev/null +++ b/node_modules/pac-resolver/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2013 Nathan Rajlich + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/pac-resolver/README.md b/node_modules/pac-resolver/README.md new file mode 100644 index 0000000..2b99643 --- /dev/null +++ b/node_modules/pac-resolver/README.md @@ -0,0 +1,59 @@ +pac-resolver +============ +### Generates an asynchronous resolver function from a [PAC file][pac-wikipedia] + + +This module accepts a JavaScript String of code, which is meant to be a +[PAC proxy file][pac-wikipedia], and returns a generated asynchronous +`FindProxyForURL()` function. + +Example +------- + +Given the PAC proxy file named `proxy.pac`: + +```js +function FindProxyForURL(url, host) { + if (isInNet(myIpAddress(), "10.1.10.0", "255.255.255.0")) { + return "PROXY 1.2.3.4:8080"; + } else { + return "DIRECT"; + } +} +``` + +You can consume this PAC file with `pac-resolver` like so: + +```ts +import { readFileSync } from 'fs'; +import { createPacResolver } from 'pac-resolver'; + +const FindProxyForURL = createPacResolver(readFileSync('proxy.pac')); + +const res = await FindProxyForURL('http://foo.com/'); +console.log(res); +// "DIRECT" +``` + + +API +--- + +### pac(qjs: QuickJSWASMModule, pacFileContents: string | Buffer, options?: PacResolverOptions) → Function + +Returns an asynchronous `FindProxyForURL()` function based off of the given JS +string `pacFileContents` PAC proxy file. An optional `options` object may be +passed in which respects the following options: + + * `filename` - String - the filename to use in error stack traces. Defaults to `proxy.pac`. + * `sandbox` - Object - a map of functions to include in the sandbox of the + JavaScript environment where the JS code will be executed. i.e. if you wanted to + include the common `alert` function you could pass `alert: console.log`. For + async functions, you must set the `async = true` property on the function + instance, and the JS code will be able to invoke the function as if it were + synchronous. + + The `qjs` parameter is a QuickJS module instance as returned from `getQuickJS()` from the `quickjs-emscripten` module. + +[pac-file-docs]: https://web.archive.org/web/20070602031929/http://wp.netscape.com/eng/mozilla/2.0/relnotes/demo/proxy-live.html +[pac-wikipedia]: http://wikipedia.org/wiki/Proxy_auto-config diff --git a/node_modules/pac-resolver/dist/dateRange.d.ts b/node_modules/pac-resolver/dist/dateRange.d.ts new file mode 100644 index 0000000..0a0f564 --- /dev/null +++ b/node_modules/pac-resolver/dist/dateRange.d.ts @@ -0,0 +1,67 @@ +/** + * If only a single value is specified (from each category: day, month, year), the + * function returns a true value only on days that match that specification. If + * both values are specified, the result is true between those times, including + * bounds. + * + * Even though the examples don't show, the "GMT" parameter can be specified + * in any of the 9 different call profiles, always as the last parameter. + * + * Examples: + * + * ``` js + * dateRange(1) + * true on the first day of each month, local timezone. + * + * dateRange(1, "GMT") + * true on the first day of each month, GMT timezone. + * + * dateRange(1, 15) + * true on the first half of each month. + * + * dateRange(24, "DEC") + * true on 24th of December each year. + * + * dateRange(24, "DEC", 1995) + * true on 24th of December, 1995. + * + * dateRange("JAN", "MAR") + * true on the first quarter of the year. + * + * dateRange(1, "JUN", 15, "AUG") + * true from June 1st until August 15th, each year (including June 1st and August + * 15th). + * + * dateRange(1, "JUN", 15, 1995, "AUG", 1995) + * true from June 1st, 1995, until August 15th, same year. + * + * dateRange("OCT", 1995, "MAR", 1996) + * true from October 1995 until March 1996 (including the entire month of October + * 1995 and March 1996). + * + * dateRange(1995) + * true during the entire year 1995. + * + * dateRange(1995, 1997) + * true from beginning of year 1995 until the end of year 1997. + * ``` + * + * dateRange(day) + * dateRange(day1, day2) + * dateRange(mon) + * dateRange(month1, month2) + * dateRange(year) + * dateRange(year1, year2) + * dateRange(day1, month1, day2, month2) + * dateRange(month1, year1, month2, year2) + * dateRange(day1, month1, year1, day2, month2, year2) + * dateRange(day1, month1, year1, day2, month2, year2, gmt) + * + * @param {String} day is the day of month between 1 and 31 (as an integer). + * @param {String} month is one of the month strings: JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC + * @param {String} year is the full year number, for example 1995 (but not 95). Integer. + * @param {String} gmt is either the string "GMT", which makes time comparison occur in GMT timezone; if left unspecified, times are taken to be in the local timezone. + * @return {Boolean} + */ +export default function dateRange(): boolean; +//# sourceMappingURL=dateRange.d.ts.map \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/dateRange.d.ts.map b/node_modules/pac-resolver/dist/dateRange.d.ts.map new file mode 100644 index 0000000..ee30daf --- /dev/null +++ b/node_modules/pac-resolver/dist/dateRange.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"dateRange.d.ts","sourceRoot":"","sources":["../src/dateRange.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgEG;AAEH,MAAM,CAAC,OAAO,UAAU,SAAS,IAAI,OAAO,CAG3C"} \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/dateRange.js b/node_modules/pac-resolver/dist/dateRange.js new file mode 100644 index 0000000..e23a242 --- /dev/null +++ b/node_modules/pac-resolver/dist/dateRange.js @@ -0,0 +1,73 @@ +"use strict"; +/** + * If only a single value is specified (from each category: day, month, year), the + * function returns a true value only on days that match that specification. If + * both values are specified, the result is true between those times, including + * bounds. + * + * Even though the examples don't show, the "GMT" parameter can be specified + * in any of the 9 different call profiles, always as the last parameter. + * + * Examples: + * + * ``` js + * dateRange(1) + * true on the first day of each month, local timezone. + * + * dateRange(1, "GMT") + * true on the first day of each month, GMT timezone. + * + * dateRange(1, 15) + * true on the first half of each month. + * + * dateRange(24, "DEC") + * true on 24th of December each year. + * + * dateRange(24, "DEC", 1995) + * true on 24th of December, 1995. + * + * dateRange("JAN", "MAR") + * true on the first quarter of the year. + * + * dateRange(1, "JUN", 15, "AUG") + * true from June 1st until August 15th, each year (including June 1st and August + * 15th). + * + * dateRange(1, "JUN", 15, 1995, "AUG", 1995) + * true from June 1st, 1995, until August 15th, same year. + * + * dateRange("OCT", 1995, "MAR", 1996) + * true from October 1995 until March 1996 (including the entire month of October + * 1995 and March 1996). + * + * dateRange(1995) + * true during the entire year 1995. + * + * dateRange(1995, 1997) + * true from beginning of year 1995 until the end of year 1997. + * ``` + * + * dateRange(day) + * dateRange(day1, day2) + * dateRange(mon) + * dateRange(month1, month2) + * dateRange(year) + * dateRange(year1, year2) + * dateRange(day1, month1, day2, month2) + * dateRange(month1, year1, month2, year2) + * dateRange(day1, month1, year1, day2, month2, year2) + * dateRange(day1, month1, year1, day2, month2, year2, gmt) + * + * @param {String} day is the day of month between 1 and 31 (as an integer). + * @param {String} month is one of the month strings: JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC + * @param {String} year is the full year number, for example 1995 (but not 95). Integer. + * @param {String} gmt is either the string "GMT", which makes time comparison occur in GMT timezone; if left unspecified, times are taken to be in the local timezone. + * @return {Boolean} + */ +Object.defineProperty(exports, "__esModule", { value: true }); +function dateRange() { + // TODO: implement me! + return false; +} +exports.default = dateRange; +//# sourceMappingURL=dateRange.js.map \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/dateRange.js.map b/node_modules/pac-resolver/dist/dateRange.js.map new file mode 100644 index 0000000..87ed665 --- /dev/null +++ b/node_modules/pac-resolver/dist/dateRange.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dateRange.js","sourceRoot":"","sources":["../src/dateRange.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgEG;;AAEH,SAAwB,SAAS;IAChC,sBAAsB;IACtB,OAAO,KAAK,CAAC;AACd,CAAC;AAHD,4BAGC"} \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/dnsDomainIs.d.ts b/node_modules/pac-resolver/dist/dnsDomainIs.d.ts new file mode 100644 index 0000000..45c0c5d --- /dev/null +++ b/node_modules/pac-resolver/dist/dnsDomainIs.d.ts @@ -0,0 +1,23 @@ +/** + * Returns true iff the domain of hostname matches. + * + * Examples: + * + * ``` js + * dnsDomainIs("www.netscape.com", ".netscape.com") + * // is true. + * + * dnsDomainIs("www", ".netscape.com") + * // is false. + * + * dnsDomainIs("www.mcom.com", ".netscape.com") + * // is false. + * ``` + * + * + * @param {String} host is the hostname from the URL. + * @param {String} domain is the domain name to test the hostname against. + * @return {Boolean} true iff the domain of the hostname matches. + */ +export default function dnsDomainIs(host: string, domain: string): boolean; +//# sourceMappingURL=dnsDomainIs.d.ts.map \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/dnsDomainIs.d.ts.map b/node_modules/pac-resolver/dist/dnsDomainIs.d.ts.map new file mode 100644 index 0000000..452592e --- /dev/null +++ b/node_modules/pac-resolver/dist/dnsDomainIs.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"dnsDomainIs.d.ts","sourceRoot":"","sources":["../src/dnsDomainIs.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,CAAC,OAAO,UAAU,WAAW,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAIzE"} \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/dnsDomainIs.js b/node_modules/pac-resolver/dist/dnsDomainIs.js new file mode 100644 index 0000000..29667e8 --- /dev/null +++ b/node_modules/pac-resolver/dist/dnsDomainIs.js @@ -0,0 +1,30 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * Returns true iff the domain of hostname matches. + * + * Examples: + * + * ``` js + * dnsDomainIs("www.netscape.com", ".netscape.com") + * // is true. + * + * dnsDomainIs("www", ".netscape.com") + * // is false. + * + * dnsDomainIs("www.mcom.com", ".netscape.com") + * // is false. + * ``` + * + * + * @param {String} host is the hostname from the URL. + * @param {String} domain is the domain name to test the hostname against. + * @return {Boolean} true iff the domain of the hostname matches. + */ +function dnsDomainIs(host, domain) { + host = String(host); + domain = String(domain); + return host.substr(domain.length * -1) === domain; +} +exports.default = dnsDomainIs; +//# sourceMappingURL=dnsDomainIs.js.map \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/dnsDomainIs.js.map b/node_modules/pac-resolver/dist/dnsDomainIs.js.map new file mode 100644 index 0000000..4409347 --- /dev/null +++ b/node_modules/pac-resolver/dist/dnsDomainIs.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dnsDomainIs.js","sourceRoot":"","sources":["../src/dnsDomainIs.ts"],"names":[],"mappings":";;AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,SAAwB,WAAW,CAAC,IAAY,EAAE,MAAc;IAC/D,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;IACpB,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC;IACxB,OAAO,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,KAAK,MAAM,CAAC;AACnD,CAAC;AAJD,8BAIC"} \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/dnsDomainLevels.d.ts b/node_modules/pac-resolver/dist/dnsDomainLevels.d.ts new file mode 100644 index 0000000..493e3c1 --- /dev/null +++ b/node_modules/pac-resolver/dist/dnsDomainLevels.d.ts @@ -0,0 +1,18 @@ +/** + * Returns the number (integer) of DNS domain levels (number of dots) in the + * hostname. + * + * Examples: + * + * ``` js + * dnsDomainLevels("www") + * // returns 0. + * dnsDomainLevels("www.netscape.com") + * // returns 2. + * ``` + * + * @param {String} host is the hostname from the URL. + * @return {Number} number of domain levels + */ +export default function dnsDomainLevels(host: string): number; +//# sourceMappingURL=dnsDomainLevels.d.ts.map \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/dnsDomainLevels.d.ts.map b/node_modules/pac-resolver/dist/dnsDomainLevels.d.ts.map new file mode 100644 index 0000000..2c643f5 --- /dev/null +++ b/node_modules/pac-resolver/dist/dnsDomainLevels.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"dnsDomainLevels.d.ts","sourceRoot":"","sources":["../src/dnsDomainLevels.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,MAAM,CAAC,OAAO,UAAU,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAO5D"} \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/dnsDomainLevels.js b/node_modules/pac-resolver/dist/dnsDomainLevels.js new file mode 100644 index 0000000..269a830 --- /dev/null +++ b/node_modules/pac-resolver/dist/dnsDomainLevels.js @@ -0,0 +1,28 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * Returns the number (integer) of DNS domain levels (number of dots) in the + * hostname. + * + * Examples: + * + * ``` js + * dnsDomainLevels("www") + * // returns 0. + * dnsDomainLevels("www.netscape.com") + * // returns 2. + * ``` + * + * @param {String} host is the hostname from the URL. + * @return {Number} number of domain levels + */ +function dnsDomainLevels(host) { + const match = String(host).match(/\./g); + let levels = 0; + if (match) { + levels = match.length; + } + return levels; +} +exports.default = dnsDomainLevels; +//# sourceMappingURL=dnsDomainLevels.js.map \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/dnsDomainLevels.js.map b/node_modules/pac-resolver/dist/dnsDomainLevels.js.map new file mode 100644 index 0000000..06abf8d --- /dev/null +++ b/node_modules/pac-resolver/dist/dnsDomainLevels.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dnsDomainLevels.js","sourceRoot":"","sources":["../src/dnsDomainLevels.ts"],"names":[],"mappings":";;AAAA;;;;;;;;;;;;;;;GAeG;AACH,SAAwB,eAAe,CAAC,IAAY;IACnD,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IACxC,IAAI,MAAM,GAAG,CAAC,CAAC;IACf,IAAI,KAAK,EAAE;QACV,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC;KACtB;IACD,OAAO,MAAM,CAAC;AACf,CAAC;AAPD,kCAOC"} \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/dnsResolve.d.ts b/node_modules/pac-resolver/dist/dnsResolve.d.ts new file mode 100644 index 0000000..d1b2afe --- /dev/null +++ b/node_modules/pac-resolver/dist/dnsResolve.d.ts @@ -0,0 +1,16 @@ +/** + * Resolves the given DNS hostname into an IP address, and returns it in the dot + * separated format as a string. + * + * Example: + * + * ``` js + * dnsResolve("home.netscape.com") + * // returns the string "198.95.249.79". + * ``` + * + * @param {String} host hostname to resolve + * @return {String} resolved IP address + */ +export default function dnsResolve(host: string): Promise; +//# sourceMappingURL=dnsResolve.d.ts.map \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/dnsResolve.d.ts.map b/node_modules/pac-resolver/dist/dnsResolve.d.ts.map new file mode 100644 index 0000000..4b79f53 --- /dev/null +++ b/node_modules/pac-resolver/dist/dnsResolve.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"dnsResolve.d.ts","sourceRoot":"","sources":["../src/dnsResolve.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;GAaG;AAEH,wBAA8B,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAW7E"} \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/dnsResolve.js b/node_modules/pac-resolver/dist/dnsResolve.js new file mode 100644 index 0000000..5e48a08 --- /dev/null +++ b/node_modules/pac-resolver/dist/dnsResolve.js @@ -0,0 +1,32 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const util_1 = require("./util"); +/** + * Resolves the given DNS hostname into an IP address, and returns it in the dot + * separated format as a string. + * + * Example: + * + * ``` js + * dnsResolve("home.netscape.com") + * // returns the string "198.95.249.79". + * ``` + * + * @param {String} host hostname to resolve + * @return {String} resolved IP address + */ +async function dnsResolve(host) { + const family = 4; + try { + const r = await (0, util_1.dnsLookup)(host, { family }); + if (typeof r === 'string') { + return r; + } + } + catch (err) { + // @ignore + } + return null; +} +exports.default = dnsResolve; +//# sourceMappingURL=dnsResolve.js.map \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/dnsResolve.js.map b/node_modules/pac-resolver/dist/dnsResolve.js.map new file mode 100644 index 0000000..65e8d98 --- /dev/null +++ b/node_modules/pac-resolver/dist/dnsResolve.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dnsResolve.js","sourceRoot":"","sources":["../src/dnsResolve.ts"],"names":[],"mappings":";;AAAA,iCAAmC;AAEnC;;;;;;;;;;;;;GAaG;AAEY,KAAK,UAAU,UAAU,CAAC,IAAY;IACpD,MAAM,MAAM,GAAG,CAAC,CAAC;IACjB,IAAI;QACH,MAAM,CAAC,GAAG,MAAM,IAAA,gBAAS,EAAC,IAAI,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC;QAC5C,IAAI,OAAO,CAAC,KAAK,QAAQ,EAAE;YAC1B,OAAO,CAAC,CAAC;SACT;KACD;IAAC,OAAO,GAAG,EAAE;QACb,UAAU;KACV;IACD,OAAO,IAAI,CAAC;AACb,CAAC;AAXD,6BAWC"} \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/index.d.ts b/node_modules/pac-resolver/dist/index.d.ts new file mode 100644 index 0000000..7f42c7f --- /dev/null +++ b/node_modules/pac-resolver/dist/index.d.ts @@ -0,0 +1,50 @@ +/// +/// +import { CompileOptions } from 'degenerator'; +/** + * Built-in PAC functions. + */ +import dateRange from './dateRange'; +import dnsDomainIs from './dnsDomainIs'; +import dnsDomainLevels from './dnsDomainLevels'; +import dnsResolve from './dnsResolve'; +import isInNet from './isInNet'; +import isPlainHostName from './isPlainHostName'; +import isResolvable from './isResolvable'; +import localHostOrDomainIs from './localHostOrDomainIs'; +import myIpAddress from './myIpAddress'; +import shExpMatch from './shExpMatch'; +import timeRange from './timeRange'; +import weekdayRange from './weekdayRange'; +import type { QuickJSWASMModule } from '@tootallnate/quickjs-emscripten'; +/** + * Returns an asynchronous `FindProxyForURL()` function + * from the given JS string (from a PAC file). + */ +export declare function createPacResolver(qjs: QuickJSWASMModule, _str: string | Buffer, _opts?: PacResolverOptions): (url: string | URL, _host?: string) => Promise; +export type GMT = 'GMT'; +export type Hour = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23; +export type Day = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31; +export type Weekday = 'SUN' | 'MON' | 'TUE' | 'WED' | 'THU' | 'FRI' | 'SAT'; +export type Month = 'JAN' | 'FEB' | 'MAR' | 'APR' | 'MAY' | 'JUN' | 'JUL' | 'AUG' | 'SEP' | 'OCT' | 'NOV' | 'DEC'; +export type PacResolverOptions = CompileOptions; +export interface FindProxyForURLCallback { + (err?: Error | null, result?: string): void; +} +export type FindProxyForURL = ReturnType; +export declare const sandbox: Readonly<{ + alert: (message?: string) => void; + dateRange: typeof dateRange; + dnsDomainIs: typeof dnsDomainIs; + dnsDomainLevels: typeof dnsDomainLevels; + dnsResolve: typeof dnsResolve; + isInNet: typeof isInNet; + isPlainHostName: typeof isPlainHostName; + isResolvable: typeof isResolvable; + localHostOrDomainIs: typeof localHostOrDomainIs; + myIpAddress: typeof myIpAddress; + shExpMatch: typeof shExpMatch; + timeRange: typeof timeRange; + weekdayRange: typeof weekdayRange; +}>; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/index.d.ts.map b/node_modules/pac-resolver/dist/index.d.ts.map new file mode 100644 index 0000000..d454717 --- /dev/null +++ b/node_modules/pac-resolver/dist/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;AACA,OAAO,EAAE,cAAc,EAAW,MAAM,aAAa,CAAC;AAEtD;;GAEG;AACH,OAAO,SAAS,MAAM,aAAa,CAAC;AACpC,OAAO,WAAW,MAAM,eAAe,CAAC;AACxC,OAAO,eAAe,MAAM,mBAAmB,CAAC;AAChD,OAAO,UAAU,MAAM,cAAc,CAAC;AACtC,OAAO,OAAO,MAAM,WAAW,CAAC;AAChC,OAAO,eAAe,MAAM,mBAAmB,CAAC;AAChD,OAAO,YAAY,MAAM,gBAAgB,CAAC;AAC1C,OAAO,mBAAmB,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C;AAC5E,MAAM,MAAM,KAAK,GACd,KAAK,GACL,KAAK,GACL,KAAK,GACL,KAAK,GACL,KAAK,GACL,KAAK,GACL,KAAK,GACL,KAAK,GACL,KAAK,GACL,KAAK,GACL,KAAK,GACL,KAAK,CAAC;AACT,MAAM,MAAM,kBAAkB,GAAG,cAAc,CAAC;AAChD,MAAM,WAAW,uBAAuB;IACvC,CAAC,GAAG,CAAC,EAAE,KAAK,GAAG,IAAI,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC5C;AACD,MAAM,MAAM,eAAe,GAAG,UAAU,CAAC,OAAO,iBAAiB,CAAC,CAAC;AAEnE,eAAO,MAAM,OAAO;;;;;;;;;;;;;;EAclB,CAAC"} \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/index.js b/node_modules/pac-resolver/dist/index.js new file mode 100644 index 0000000..4d009ff --- /dev/null +++ b/node_modules/pac-resolver/dist/index.js @@ -0,0 +1,87 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.sandbox = exports.createPacResolver = void 0; +const degenerator_1 = require("degenerator"); +/** + * Built-in PAC functions. + */ +const dateRange_1 = __importDefault(require("./dateRange")); +const dnsDomainIs_1 = __importDefault(require("./dnsDomainIs")); +const dnsDomainLevels_1 = __importDefault(require("./dnsDomainLevels")); +const dnsResolve_1 = __importDefault(require("./dnsResolve")); +const isInNet_1 = __importDefault(require("./isInNet")); +const isPlainHostName_1 = __importDefault(require("./isPlainHostName")); +const isResolvable_1 = __importDefault(require("./isResolvable")); +const localHostOrDomainIs_1 = __importDefault(require("./localHostOrDomainIs")); +const myIpAddress_1 = __importDefault(require("./myIpAddress")); +const shExpMatch_1 = __importDefault(require("./shExpMatch")); +const timeRange_1 = __importDefault(require("./timeRange")); +const weekdayRange_1 = __importDefault(require("./weekdayRange")); +/** + * Returns an asynchronous `FindProxyForURL()` function + * from the given JS string (from a PAC file). + */ +function createPacResolver(qjs, _str, _opts = {}) { + const str = Buffer.isBuffer(_str) ? _str.toString('utf8') : _str; + // The sandbox to use for the `vm` context. + const context = { + ...exports.sandbox, + ..._opts.sandbox, + }; + // Construct the array of async function names to add `await` calls to. + const names = Object.keys(context).filter((k) => isAsyncFunction(context[k])); + const opts = { + filename: 'proxy.pac', + names, + ..._opts, + sandbox: context, + }; + // Compile the JS `FindProxyForURL()` function into an async function. + const resolver = (0, degenerator_1.compile)(qjs, str, 'FindProxyForURL', opts); + function FindProxyForURL(url, _host) { + const urlObj = typeof url === 'string' ? new URL(url) : url; + const host = _host || urlObj.hostname; + if (!host) { + throw new TypeError('Could not determine `host`'); + } + return resolver(urlObj.href, host); + } + Object.defineProperty(FindProxyForURL, 'toString', { + value: () => resolver.toString(), + enumerable: false, + }); + return FindProxyForURL; +} +exports.createPacResolver = createPacResolver; +exports.sandbox = Object.freeze({ + alert: (message = '') => console.log('%s', message), + dateRange: dateRange_1.default, + dnsDomainIs: dnsDomainIs_1.default, + dnsDomainLevels: dnsDomainLevels_1.default, + dnsResolve: dnsResolve_1.default, + isInNet: isInNet_1.default, + isPlainHostName: isPlainHostName_1.default, + isResolvable: isResolvable_1.default, + localHostOrDomainIs: localHostOrDomainIs_1.default, + myIpAddress: myIpAddress_1.default, + shExpMatch: shExpMatch_1.default, + timeRange: timeRange_1.default, + weekdayRange: weekdayRange_1.default, +}); +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function isAsyncFunction(v) { + if (typeof v !== 'function') + return false; + // Native `AsyncFunction` + if (v.constructor.name === 'AsyncFunction') + return true; + // TypeScript compiled + if (String(v).indexOf('__awaiter(') !== -1) + return true; + // Legacy behavior - set `async` property on the function + return Boolean(v.async); +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/index.js.map b/node_modules/pac-resolver/dist/index.js.map new file mode 100644 index 0000000..b6df751 --- /dev/null +++ b/node_modules/pac-resolver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O,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;AACzB,CAAC"} \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/ip.d.ts b/node_modules/pac-resolver/dist/ip.d.ts new file mode 100644 index 0000000..05f2b24 --- /dev/null +++ b/node_modules/pac-resolver/dist/ip.d.ts @@ -0,0 +1,8 @@ +export declare const ip: { + address(): string; + isLoopback(addr: string): boolean; + loopback(family: IpFamily): string; +}; +type IpFamily = 'ipv4' | 'ipv6'; +export {}; +//# sourceMappingURL=ip.d.ts.map \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/ip.d.ts.map b/node_modules/pac-resolver/dist/ip.d.ts.map new file mode 100644 index 0000000..45b4178 --- /dev/null +++ b/node_modules/pac-resolver/dist/ip.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ip.d.ts","sourceRoot":"","sources":["../src/ip.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,EAAE;eACH,MAAM;qBAsBA,MAAM,GAAG,OAAO;qBAQhB,QAAQ,GAAG,MAAM;CAWlC,CAAC;AAYF,KAAK,QAAQ,GAAG,MAAM,GAAG,MAAM,CAAA"} \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/ip.js b/node_modules/pac-resolver/dist/ip.js new file mode 100644 index 0000000..e039700 --- /dev/null +++ b/node_modules/pac-resolver/dist/ip.js @@ -0,0 +1,50 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ip = void 0; +const os_1 = __importDefault(require("os")); +exports.ip = { + address() { + const interfaces = os_1.default.networkInterfaces(); + // Default to `ipv4` + const family = normalizeFamily(); + const all = Object.values(interfaces).map((addrs = []) => { + const addresses = addrs.filter((details) => { + const detailsFamily = normalizeFamily(details.family); + if (detailsFamily !== family || exports.ip.isLoopback(details.address)) { + return false; + } + return true; + }); + return addresses.length ? addresses[0].address : undefined; + }).filter(Boolean); + return !all.length ? exports.ip.loopback(family) : all[0]; + }, + isLoopback(addr) { + return /^(::f{4}:)?127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/ + .test(addr) + || /^fe80::1$/.test(addr) + || /^::1$/.test(addr) + || /^::$/.test(addr); + }, + loopback(family) { + // Default to `ipv4` + family = normalizeFamily(family); + if (family !== 'ipv4' && family !== 'ipv6') { + throw new Error('family must be ipv4 or ipv6'); + } + return family === 'ipv4' ? '127.0.0.1' : 'fe80::1'; + } +}; +function normalizeFamily(family) { + if (family === 4) { + return 'ipv4'; + } + if (family === 6) { + return 'ipv6'; + } + return family ? family.toLowerCase() : 'ipv4'; +} +//# sourceMappingURL=ip.js.map \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/ip.js.map b/node_modules/pac-resolver/dist/ip.js.map new file mode 100644 index 0000000..b0ab97c --- /dev/null +++ b/node_modules/pac-resolver/dist/ip.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ip.js","sourceRoot":"","sources":["../src/ip.ts"],"names":[],"mappings":";;;;;;AAAA,4CAAoB;AAEP,QAAA,EAAE,GAAG;IACjB,OAAO;QACN,MAAM,UAAU,GAAG,YAAE,CAAC,iBAAiB,EAAE,CAAC;QAE1C,oBAAoB;QACpB,MAAM,MAAM,GAAG,eAAe,EAAE,CAAC;QAEjC,MAAM,GAAG,GAAG,MAAM,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,GAAG,EAAE,EAAE,EAAE;YACxD,MAAM,SAAS,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,OAAO,EAAE,EAAE;gBAC1C,MAAM,aAAa,GAAG,eAAe,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;gBACtD,IAAI,aAAa,KAAK,MAAM,IAAI,UAAE,CAAC,UAAU,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE;oBAC/D,OAAO,KAAK,CAAC;iBACb;gBACD,OAAO,IAAI,CAAC;YAEb,CAAC,CAAC,CAAC;YAEH,OAAO,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC;QAC5D,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QAEnB,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,UAAE,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAW,CAAC;IAC7D,CAAC;IAED,UAAU,CAAC,IAAY;QACtB,OAAO,0DAA0D;aAC/D,IAAI,CAAC,IAAI,CAAC;eACR,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC;eACtB,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC;eAClB,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACvB,CAAC;IAED,QAAQ,CAAC,MAAgB;QACxB,oBAAoB;QACpB,MAAM,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC;QAEjC,IAAI,MAAM,KAAK,MAAM,IAAI,MAAM,KAAK,MAAM,EAAE;YAC3C,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC;SAC/C;QAED,OAAO,MAAM,KAAK,MAAM,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,SAAS,CAAC;IACpD,CAAC;CAED,CAAC;AAEF,SAAS,eAAe,CAAC,MAAgB;IACxC,IAAI,MAAM,KAAK,CAAC,EAAE;QACjB,OAAO,MAAM,CAAC;KACd;IACD,IAAI,MAAM,KAAK,CAAC,EAAE;QACjB,OAAO,MAAM,CAAC;KACd;IACD,OAAO,MAAM,CAAC,CAAC,CAAE,MAAiB,CAAC,WAAW,EAAc,CAAC,CAAC,CAAC,MAAM,CAAC;AACvE,CAAC"} \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/isInNet.d.ts b/node_modules/pac-resolver/dist/isInNet.d.ts new file mode 100644 index 0000000..adcada0 --- /dev/null +++ b/node_modules/pac-resolver/dist/isInNet.d.ts @@ -0,0 +1,24 @@ +/** + * True iff the IP address of the host matches the specified IP address pattern. + * + * Pattern and mask specification is done the same way as for SOCKS configuration. + * + * Examples: + * + * ``` js + * isInNet(host, "198.95.249.79", "255.255.255.255") + * // is true iff the IP address of host matches exactly 198.95.249.79. + * + * isInNet(host, "198.95.0.0", "255.255.0.0") + * // is true iff the IP address of the host matches 198.95.*.*. + * ``` + * + * @param {String} host a DNS hostname, or IP address. If a hostname is passed, + * it will be resoved into an IP address by this function. + * @param {String} pattern an IP address pattern in the dot-separated format mask. + * @param {String} mask for the IP address pattern informing which parts of the + * IP address should be matched against. 0 means ignore, 255 means match. + * @return {Boolean} + */ +export default function isInNet(host: string, pattern: string, mask: string): Promise; +//# sourceMappingURL=isInNet.d.ts.map \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/isInNet.d.ts.map b/node_modules/pac-resolver/dist/isInNet.d.ts.map new file mode 100644 index 0000000..989813c --- /dev/null +++ b/node_modules/pac-resolver/dist/isInNet.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"isInNet.d.ts","sourceRoot":"","sources":["../src/isInNet.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,wBAA8B,OAAO,CACpC,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,MAAM,GACV,OAAO,CAAC,OAAO,CAAC,CAYlB"} \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/isInNet.js b/node_modules/pac-resolver/dist/isInNet.js new file mode 100644 index 0000000..d382b14 --- /dev/null +++ b/node_modules/pac-resolver/dist/isInNet.js @@ -0,0 +1,42 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const netmask_1 = require("netmask"); +const util_1 = require("./util"); +/** + * True iff the IP address of the host matches the specified IP address pattern. + * + * Pattern and mask specification is done the same way as for SOCKS configuration. + * + * Examples: + * + * ``` js + * isInNet(host, "198.95.249.79", "255.255.255.255") + * // is true iff the IP address of host matches exactly 198.95.249.79. + * + * isInNet(host, "198.95.0.0", "255.255.0.0") + * // is true iff the IP address of the host matches 198.95.*.*. + * ``` + * + * @param {String} host a DNS hostname, or IP address. If a hostname is passed, + * it will be resoved into an IP address by this function. + * @param {String} pattern an IP address pattern in the dot-separated format mask. + * @param {String} mask for the IP address pattern informing which parts of the + * IP address should be matched against. 0 means ignore, 255 means match. + * @return {Boolean} + */ +async function isInNet(host, pattern, mask) { + const family = 4; + try { + const ip = await (0, util_1.dnsLookup)(host, { family }); + if (typeof ip === 'string') { + const netmask = new netmask_1.Netmask(pattern, mask); + return netmask.contains(ip); + } + } + catch (err) { + // ignore + } + return false; +} +exports.default = isInNet; +//# sourceMappingURL=isInNet.js.map \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/isInNet.js.map b/node_modules/pac-resolver/dist/isInNet.js.map new file mode 100644 index 0000000..5df22a6 --- /dev/null +++ b/node_modules/pac-resolver/dist/isInNet.js.map @@ -0,0 +1 @@ +{"version":3,"file":"isInNet.js","sourceRoot":"","sources":["../src/isInNet.ts"],"names":[],"mappings":";;AAAA,qCAAkC;AAClC,iCAAmC;AAEnC;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEY,KAAK,UAAU,OAAO,CACpC,IAAY,EACZ,OAAe,EACf,IAAY;IAEZ,MAAM,MAAM,GAAG,CAAC,CAAC;IACjB,IAAI;QACH,MAAM,EAAE,GAAG,MAAM,IAAA,gBAAS,EAAC,IAAI,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC;QAC7C,IAAI,OAAO,EAAE,KAAK,QAAQ,EAAE;YAC3B,MAAM,OAAO,GAAG,IAAI,iBAAO,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;YAC3C,OAAO,OAAO,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;SAC5B;KACD;IAAC,OAAO,GAAG,EAAE;QACb,SAAS;KACT;IACD,OAAO,KAAK,CAAC;AACd,CAAC;AAhBD,0BAgBC"} \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/isPlainHostName.d.ts b/node_modules/pac-resolver/dist/isPlainHostName.d.ts new file mode 100644 index 0000000..21f5ab3 --- /dev/null +++ b/node_modules/pac-resolver/dist/isPlainHostName.d.ts @@ -0,0 +1,18 @@ +/** + * True iff there is no domain name in the hostname (no dots). + * + * Examples: + * + * ``` js + * isPlainHostName("www") + * // is true. + * + * isPlainHostName("www.netscape.com") + * // is false. + * ``` + * + * @param {String} host The hostname from the URL (excluding port number). + * @return {Boolean} + */ +export default function isPlainHostName(host: string): boolean; +//# sourceMappingURL=isPlainHostName.d.ts.map \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/isPlainHostName.d.ts.map b/node_modules/pac-resolver/dist/isPlainHostName.d.ts.map new file mode 100644 index 0000000..205c6e5 --- /dev/null +++ b/node_modules/pac-resolver/dist/isPlainHostName.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"isPlainHostName.d.ts","sourceRoot":"","sources":["../src/isPlainHostName.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,MAAM,CAAC,OAAO,UAAU,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAE7D"} \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/isPlainHostName.js b/node_modules/pac-resolver/dist/isPlainHostName.js new file mode 100644 index 0000000..7e89dcf --- /dev/null +++ b/node_modules/pac-resolver/dist/isPlainHostName.js @@ -0,0 +1,23 @@ +"use strict"; +/** + * True iff there is no domain name in the hostname (no dots). + * + * Examples: + * + * ``` js + * isPlainHostName("www") + * // is true. + * + * isPlainHostName("www.netscape.com") + * // is false. + * ``` + * + * @param {String} host The hostname from the URL (excluding port number). + * @return {Boolean} + */ +Object.defineProperty(exports, "__esModule", { value: true }); +function isPlainHostName(host) { + return !/\./.test(host); +} +exports.default = isPlainHostName; +//# sourceMappingURL=isPlainHostName.js.map \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/isPlainHostName.js.map b/node_modules/pac-resolver/dist/isPlainHostName.js.map new file mode 100644 index 0000000..191e78e --- /dev/null +++ b/node_modules/pac-resolver/dist/isPlainHostName.js.map @@ -0,0 +1 @@ +{"version":3,"file":"isPlainHostName.js","sourceRoot":"","sources":["../src/isPlainHostName.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;AAEH,SAAwB,eAAe,CAAC,IAAY;IACnD,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACzB,CAAC;AAFD,kCAEC"} \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/isResolvable.d.ts b/node_modules/pac-resolver/dist/isResolvable.d.ts new file mode 100644 index 0000000..00a4a3c --- /dev/null +++ b/node_modules/pac-resolver/dist/isResolvable.d.ts @@ -0,0 +1,8 @@ +/** + * Tries to resolve the hostname. Returns true if succeeds. + * + * @param {String} host is the hostname from the URL. + * @return {Boolean} + */ +export default function isResolvable(host: string): Promise; +//# sourceMappingURL=isResolvable.d.ts.map \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/isResolvable.d.ts.map b/node_modules/pac-resolver/dist/isResolvable.d.ts.map new file mode 100644 index 0000000..90f2285 --- /dev/null +++ b/node_modules/pac-resolver/dist/isResolvable.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"isResolvable.d.ts","sourceRoot":"","sources":["../src/isResolvable.ts"],"names":[],"mappings":"AAEA;;;;;GAKG;AAEH,wBAA8B,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAUzE"} \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/isResolvable.js b/node_modules/pac-resolver/dist/isResolvable.js new file mode 100644 index 0000000..89a5cb7 --- /dev/null +++ b/node_modules/pac-resolver/dist/isResolvable.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const util_1 = require("./util"); +/** + * Tries to resolve the hostname. Returns true if succeeds. + * + * @param {String} host is the hostname from the URL. + * @return {Boolean} + */ +async function isResolvable(host) { + const family = 4; + try { + if (await (0, util_1.dnsLookup)(host, { family })) { + return true; + } + } + catch (err) { + // ignore + } + return false; +} +exports.default = isResolvable; +//# sourceMappingURL=isResolvable.js.map \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/isResolvable.js.map b/node_modules/pac-resolver/dist/isResolvable.js.map new file mode 100644 index 0000000..5a73eda --- /dev/null +++ b/node_modules/pac-resolver/dist/isResolvable.js.map @@ -0,0 +1 @@ +{"version":3,"file":"isResolvable.js","sourceRoot":"","sources":["../src/isResolvable.ts"],"names":[],"mappings":";;AAAA,iCAAmC;AAEnC;;;;;GAKG;AAEY,KAAK,UAAU,YAAY,CAAC,IAAY;IACtD,MAAM,MAAM,GAAG,CAAC,CAAC;IACjB,IAAI;QACH,IAAI,MAAM,IAAA,gBAAS,EAAC,IAAI,EAAE,EAAE,MAAM,EAAE,CAAC,EAAE;YACtC,OAAO,IAAI,CAAC;SACZ;KACD;IAAC,OAAO,GAAG,EAAE;QACb,SAAS;KACT;IACD,OAAO,KAAK,CAAC;AACd,CAAC;AAVD,+BAUC"} \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/localHostOrDomainIs.d.ts b/node_modules/pac-resolver/dist/localHostOrDomainIs.d.ts new file mode 100644 index 0000000..30febbc --- /dev/null +++ b/node_modules/pac-resolver/dist/localHostOrDomainIs.d.ts @@ -0,0 +1,26 @@ +/** + * Is true if the hostname matches exactly the specified hostname, or if there is + * no domain name part in the hostname, but the unqualified hostname matches. + * + * Examples: + * + * ``` js + * localHostOrDomainIs("www.netscape.com", "www.netscape.com") + * // is true (exact match). + * + * localHostOrDomainIs("www", "www.netscape.com") + * // is true (hostname match, domain not specified). + * + * localHostOrDomainIs("www.mcom.com", "www.netscape.com") + * // is false (domain name mismatch). + * + * localHostOrDomainIs("home.netscape.com", "www.netscape.com") + * // is false (hostname mismatch). + * ``` + * + * @param {String} host the hostname from the URL. + * @param {String} hostdom fully qualified hostname to match against. + * @return {Boolean} + */ +export default function localHostOrDomainIs(host: string, hostdom: string): boolean; +//# sourceMappingURL=localHostOrDomainIs.d.ts.map \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/localHostOrDomainIs.d.ts.map b/node_modules/pac-resolver/dist/localHostOrDomainIs.d.ts.map new file mode 100644 index 0000000..c4abc16 --- /dev/null +++ b/node_modules/pac-resolver/dist/localHostOrDomainIs.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"localHostOrDomainIs.d.ts","sourceRoot":"","sources":["../src/localHostOrDomainIs.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,CAAC,OAAO,UAAU,mBAAmB,CAC1C,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,MAAM,GACb,OAAO,CAaT"} \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/localHostOrDomainIs.js b/node_modules/pac-resolver/dist/localHostOrDomainIs.js new file mode 100644 index 0000000..ff4cdfd --- /dev/null +++ b/node_modules/pac-resolver/dist/localHostOrDomainIs.js @@ -0,0 +1,40 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * Is true if the hostname matches exactly the specified hostname, or if there is + * no domain name part in the hostname, but the unqualified hostname matches. + * + * Examples: + * + * ``` js + * localHostOrDomainIs("www.netscape.com", "www.netscape.com") + * // is true (exact match). + * + * localHostOrDomainIs("www", "www.netscape.com") + * // is true (hostname match, domain not specified). + * + * localHostOrDomainIs("www.mcom.com", "www.netscape.com") + * // is false (domain name mismatch). + * + * localHostOrDomainIs("home.netscape.com", "www.netscape.com") + * // is false (hostname mismatch). + * ``` + * + * @param {String} host the hostname from the URL. + * @param {String} hostdom fully qualified hostname to match against. + * @return {Boolean} + */ +function localHostOrDomainIs(host, hostdom) { + const parts = host.split('.'); + const domparts = hostdom.split('.'); + let matches = true; + for (let i = 0; i < parts.length; i++) { + if (parts[i] !== domparts[i]) { + matches = false; + break; + } + } + return matches; +} +exports.default = localHostOrDomainIs; +//# sourceMappingURL=localHostOrDomainIs.js.map \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/localHostOrDomainIs.js.map b/node_modules/pac-resolver/dist/localHostOrDomainIs.js.map new file mode 100644 index 0000000..1eea2b0 --- /dev/null +++ b/node_modules/pac-resolver/dist/localHostOrDomainIs.js.map @@ -0,0 +1 @@ +{"version":3,"file":"localHostOrDomainIs.js","sourceRoot":"","sources":["../src/localHostOrDomainIs.ts"],"names":[],"mappings":";;AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,SAAwB,mBAAmB,CAC1C,IAAY,EACZ,OAAe;IAEf,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC9B,MAAM,QAAQ,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACpC,IAAI,OAAO,GAAG,IAAI,CAAC;IAEnB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACtC,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,EAAE;YAC7B,OAAO,GAAG,KAAK,CAAC;YAChB,MAAM;SACN;KACD;IAED,OAAO,OAAO,CAAC;AAChB,CAAC;AAhBD,sCAgBC"} \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/myIpAddress.d.ts b/node_modules/pac-resolver/dist/myIpAddress.d.ts new file mode 100644 index 0000000..bb20b4a --- /dev/null +++ b/node_modules/pac-resolver/dist/myIpAddress.d.ts @@ -0,0 +1,16 @@ +/** + * Returns the IP address of the host that the Navigator is running on, as + * a string in the dot-separated integer format. + * + * Example: + * + * ``` js + * myIpAddress() + * // would return the string "198.95.249.79" if you were running the + * // Navigator on that host. + * ``` + * + * @return {String} external IP address + */ +export default function myIpAddress(): Promise; +//# sourceMappingURL=myIpAddress.d.ts.map \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/myIpAddress.d.ts.map b/node_modules/pac-resolver/dist/myIpAddress.d.ts.map new file mode 100644 index 0000000..a724736 --- /dev/null +++ b/node_modules/pac-resolver/dist/myIpAddress.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"myIpAddress.d.ts","sourceRoot":"","sources":["../src/myIpAddress.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;GAaG;AACH,wBAA8B,WAAW,IAAI,OAAO,CAAC,MAAM,CAAC,CAwB3D"} \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/myIpAddress.js b/node_modules/pac-resolver/dist/myIpAddress.js new file mode 100644 index 0000000..1702462 --- /dev/null +++ b/node_modules/pac-resolver/dist/myIpAddress.js @@ -0,0 +1,50 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const ip_1 = require("./ip"); +const net_1 = __importDefault(require("net")); +/** + * Returns the IP address of the host that the Navigator is running on, as + * a string in the dot-separated integer format. + * + * Example: + * + * ``` js + * myIpAddress() + * // would return the string "198.95.249.79" if you were running the + * // Navigator on that host. + * ``` + * + * @return {String} external IP address + */ +async function myIpAddress() { + return new Promise((resolve, reject) => { + // 8.8.8.8:53 is "Google Public DNS": + // https://developers.google.com/speed/public-dns/ + const socket = net_1.default.connect({ host: '8.8.8.8', port: 53 }); + const onError = () => { + // if we fail to access Google DNS (as in firewall blocks access), + // fallback to querying IP locally + resolve(ip_1.ip.address()); + }; + socket.once('error', onError); + socket.once('connect', () => { + socket.removeListener('error', onError); + const addr = socket.address(); + socket.destroy(); + if (typeof addr === 'string') { + resolve(addr); + } + else if (addr.address) { + resolve(addr.address); + } + else { + reject(new Error('Expected a `string`')); + } + }); + }); +} +exports.default = myIpAddress; +//# sourceMappingURL=myIpAddress.js.map \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/myIpAddress.js.map b/node_modules/pac-resolver/dist/myIpAddress.js.map new file mode 100644 index 0000000..e8ff48b --- /dev/null +++ b/node_modules/pac-resolver/dist/myIpAddress.js.map @@ -0,0 +1 @@ +{"version":3,"file":"myIpAddress.js","sourceRoot":"","sources":["../src/myIpAddress.ts"],"names":[],"mappings":";;;;;AAAA,6BAA0B;AAC1B,8CAAuC;AAEvC;;;;;;;;;;;;;GAaG;AACY,KAAK,UAAU,WAAW;IACxC,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACtC,qCAAqC;QACrC,kDAAkD;QAClD,MAAM,MAAM,GAAG,aAAG,CAAC,OAAO,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,CAAC;QAC1D,MAAM,OAAO,GAAG,GAAG,EAAE;YACpB,kEAAkE;YAClE,kCAAkC;YAClC,OAAO,CAAC,OAAE,CAAC,OAAO,EAAE,CAAC,CAAC;QACvB,CAAC,CAAC;QACF,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAC9B,MAAM,CAAC,IAAI,CAAC,SAAS,EAAE,GAAG,EAAE;YAC3B,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YACxC,MAAM,IAAI,GAAG,MAAM,CAAC,OAAO,EAAE,CAAC;YAC9B,MAAM,CAAC,OAAO,EAAE,CAAC;YACjB,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;gBAC7B,OAAO,CAAC,IAAI,CAAC,CAAC;aACd;iBAAM,IAAK,IAAoB,CAAC,OAAO,EAAE;gBACzC,OAAO,CAAE,IAAoB,CAAC,OAAO,CAAC,CAAC;aACvC;iBAAM;gBACN,MAAM,CAAC,IAAI,KAAK,CAAC,qBAAqB,CAAC,CAAC,CAAC;aACzC;QACF,CAAC,CAAC,CAAC;IACJ,CAAC,CAAC,CAAC;AACJ,CAAC;AAxBD,8BAwBC"} \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/shExpMatch.d.ts b/node_modules/pac-resolver/dist/shExpMatch.d.ts new file mode 100644 index 0000000..c9de761 --- /dev/null +++ b/node_modules/pac-resolver/dist/shExpMatch.d.ts @@ -0,0 +1,23 @@ +/** + * Returns true if the string matches the specified shell + * expression. + * + * Actually, currently the patterns are shell expressions, + * not regular expressions. + * + * Examples: + * + * ``` js + * shExpMatch("http://home.netscape.com/people/ari/index.html", "*\/ari/*") + * // is true. + * + * shExpMatch("http://home.netscape.com/people/montulli/index.html", "*\/ari/*") + * // is false. + * ``` + * + * @param {String} str is any string to compare (e.g. the URL, or the hostname). + * @param {String} shexp is a shell expression to compare against. + * @return {Boolean} true if the string matches the shell expression. + */ +export default function shExpMatch(str: string, shexp: string): boolean; +//# sourceMappingURL=shExpMatch.d.ts.map \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/shExpMatch.d.ts.map b/node_modules/pac-resolver/dist/shExpMatch.d.ts.map new file mode 100644 index 0000000..bb4ba54 --- /dev/null +++ b/node_modules/pac-resolver/dist/shExpMatch.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"shExpMatch.d.ts","sourceRoot":"","sources":["../src/shExpMatch.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,MAAM,CAAC,OAAO,UAAU,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAGtE"} \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/shExpMatch.js b/node_modules/pac-resolver/dist/shExpMatch.js new file mode 100644 index 0000000..6c77b98 --- /dev/null +++ b/node_modules/pac-resolver/dist/shExpMatch.js @@ -0,0 +1,41 @@ +"use strict"; +/** + * Returns true if the string matches the specified shell + * expression. + * + * Actually, currently the patterns are shell expressions, + * not regular expressions. + * + * Examples: + * + * ``` js + * shExpMatch("http://home.netscape.com/people/ari/index.html", "*\/ari/*") + * // is true. + * + * shExpMatch("http://home.netscape.com/people/montulli/index.html", "*\/ari/*") + * // is false. + * ``` + * + * @param {String} str is any string to compare (e.g. the URL, or the hostname). + * @param {String} shexp is a shell expression to compare against. + * @return {Boolean} true if the string matches the shell expression. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +function shExpMatch(str, shexp) { + const re = toRegExp(shexp); + return re.test(str); +} +exports.default = shExpMatch; +/** + * Converts a "shell expression" to a JavaScript RegExp. + * + * @api private + */ +function toRegExp(str) { + str = String(str) + .replace(/\./g, '\\.') + .replace(/\?/g, '.') + .replace(/\*/g, '.*'); + return new RegExp(`^${str}$`); +} +//# sourceMappingURL=shExpMatch.js.map \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/shExpMatch.js.map b/node_modules/pac-resolver/dist/shExpMatch.js.map new file mode 100644 index 0000000..041621d --- /dev/null +++ b/node_modules/pac-resolver/dist/shExpMatch.js.map @@ -0,0 +1 @@ +{"version":3,"file":"shExpMatch.js","sourceRoot":"","sources":["../src/shExpMatch.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;AAEH,SAAwB,UAAU,CAAC,GAAW,EAAE,KAAa;IAC5D,MAAM,EAAE,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC;IAC3B,OAAO,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACrB,CAAC;AAHD,6BAGC;AAED;;;;GAIG;AAEH,SAAS,QAAQ,CAAC,GAAW;IAC5B,GAAG,GAAG,MAAM,CAAC,GAAG,CAAC;SACf,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC;SACrB,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC;SACnB,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;IACvB,OAAO,IAAI,MAAM,CAAC,IAAI,GAAG,GAAG,CAAC,CAAC;AAC/B,CAAC"} \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/timeRange.d.ts b/node_modules/pac-resolver/dist/timeRange.d.ts new file mode 100644 index 0000000..05e2ee1 --- /dev/null +++ b/node_modules/pac-resolver/dist/timeRange.d.ts @@ -0,0 +1,43 @@ +/** + * True during (or between) the specified time(s). + * + * Even though the examples don't show it, this parameter may be present in + * each of the different parameter profiles, always as the last parameter. + * + * + * Examples: + * + * ``` js + * timerange(12) + * true from noon to 1pm. + * + * timerange(12, 13) + * same as above. + * + * timerange(12, "GMT") + * true from noon to 1pm, in GMT timezone. + * + * timerange(9, 17) + * true from 9am to 5pm. + * + * timerange(8, 30, 17, 00) + * true from 8:30am to 5:00pm. + * + * timerange(0, 0, 0, 0, 0, 30) + * true between midnight and 30 seconds past midnight. + * ``` + * + * timeRange(hour) + * timeRange(hour1, hour2) + * timeRange(hour1, min1, hour2, min2) + * timeRange(hour1, min1, sec1, hour2, min2, sec2) + * timeRange(hour1, min1, sec1, hour2, min2, sec2, gmt) + * + * @param {String} hour is the hour from 0 to 23. (0 is midnight, 23 is 11 pm.) + * @param {String} min minutes from 0 to 59. + * @param {String} sec seconds from 0 to 59. + * @param {String} gmt either the string "GMT" for GMT timezone, or not specified, for local timezone. + * @return {Boolean} + */ +export default function timeRange(): boolean; +//# sourceMappingURL=timeRange.d.ts.map \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/timeRange.d.ts.map b/node_modules/pac-resolver/dist/timeRange.d.ts.map new file mode 100644 index 0000000..9618234 --- /dev/null +++ b/node_modules/pac-resolver/dist/timeRange.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"timeRange.d.ts","sourceRoot":"","sources":["../src/timeRange.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AAEH,MAAM,CAAC,OAAO,UAAU,SAAS,IAAI,OAAO,CAkD3C"} \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/timeRange.js b/node_modules/pac-resolver/dist/timeRange.js new file mode 100644 index 0000000..cc45d7b --- /dev/null +++ b/node_modules/pac-resolver/dist/timeRange.js @@ -0,0 +1,92 @@ +"use strict"; +/** + * True during (or between) the specified time(s). + * + * Even though the examples don't show it, this parameter may be present in + * each of the different parameter profiles, always as the last parameter. + * + * + * Examples: + * + * ``` js + * timerange(12) + * true from noon to 1pm. + * + * timerange(12, 13) + * same as above. + * + * timerange(12, "GMT") + * true from noon to 1pm, in GMT timezone. + * + * timerange(9, 17) + * true from 9am to 5pm. + * + * timerange(8, 30, 17, 00) + * true from 8:30am to 5:00pm. + * + * timerange(0, 0, 0, 0, 0, 30) + * true between midnight and 30 seconds past midnight. + * ``` + * + * timeRange(hour) + * timeRange(hour1, hour2) + * timeRange(hour1, min1, hour2, min2) + * timeRange(hour1, min1, sec1, hour2, min2, sec2) + * timeRange(hour1, min1, sec1, hour2, min2, sec2, gmt) + * + * @param {String} hour is the hour from 0 to 23. (0 is midnight, 23 is 11 pm.) + * @param {String} min minutes from 0 to 59. + * @param {String} sec seconds from 0 to 59. + * @param {String} gmt either the string "GMT" for GMT timezone, or not specified, for local timezone. + * @return {Boolean} + */ +Object.defineProperty(exports, "__esModule", { value: true }); +function timeRange() { + // eslint-disable-next-line prefer-rest-params + const args = Array.prototype.slice.call(arguments); + const lastArg = args.pop(); + const useGMTzone = lastArg === 'GMT'; + const currentDate = new Date(); + if (!useGMTzone) { + args.push(lastArg); + } + let result = false; + const noOfArgs = args.length; + const numericArgs = args.map((n) => parseInt(n, 10)); + // timeRange(hour) + if (noOfArgs === 1) { + result = getCurrentHour(useGMTzone, currentDate) === numericArgs[0]; + // timeRange(hour1, hour2) + } + else if (noOfArgs === 2) { + const currentHour = getCurrentHour(useGMTzone, currentDate); + result = numericArgs[0] <= currentHour && currentHour < numericArgs[1]; + // timeRange(hour1, min1, hour2, min2) + } + else if (noOfArgs === 4) { + result = valueInRange(secondsElapsedToday(numericArgs[0], numericArgs[1], 0), secondsElapsedToday(getCurrentHour(useGMTzone, currentDate), getCurrentMinute(useGMTzone, currentDate), 0), secondsElapsedToday(numericArgs[2], numericArgs[3], 59)); + // timeRange(hour1, min1, sec1, hour2, min2, sec2) + } + else if (noOfArgs === 6) { + result = valueInRange(secondsElapsedToday(numericArgs[0], numericArgs[1], numericArgs[2]), secondsElapsedToday(getCurrentHour(useGMTzone, currentDate), getCurrentMinute(useGMTzone, currentDate), getCurrentSecond(useGMTzone, currentDate)), secondsElapsedToday(numericArgs[3], numericArgs[4], numericArgs[5])); + } + return result; +} +exports.default = timeRange; +function secondsElapsedToday(hh, mm, ss) { + return hh * 3600 + mm * 60 + ss; +} +function getCurrentHour(gmt, currentDate) { + return gmt ? currentDate.getUTCHours() : currentDate.getHours(); +} +function getCurrentMinute(gmt, currentDate) { + return gmt ? currentDate.getUTCMinutes() : currentDate.getMinutes(); +} +function getCurrentSecond(gmt, currentDate) { + return gmt ? currentDate.getUTCSeconds() : currentDate.getSeconds(); +} +// start <= value <= finish +function valueInRange(start, value, finish) { + return start <= value && value <= finish; +} +//# sourceMappingURL=timeRange.js.map \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/timeRange.js.map b/node_modules/pac-resolver/dist/timeRange.js.map new file mode 100644 index 0000000..a4dcea0 --- /dev/null +++ b/node_modules/pac-resolver/dist/timeRange.js.map @@ -0,0 +1 @@ +{"version":3,"file":"timeRange.js","sourceRoot":"","sources":["../src/timeRange.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;;AAEH,SAAwB,SAAS;IAChC,8CAA8C;IAC9C,MAAM,IAAI,GAAG,KAAK,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IACnD,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;IAC3B,MAAM,UAAU,GAAG,OAAO,KAAK,KAAK,CAAC;IACrC,MAAM,WAAW,GAAG,IAAI,IAAI,EAAE,CAAC;IAE/B,IAAI,CAAC,UAAU,EAAE;QAChB,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;KACnB;IAED,IAAI,MAA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B,CAAC,UAAU,EAAE,WAAW,CAAC,EACzC,gBAAgB,CAAC,UAAU,EAAE,WAAW,CAAC,CACzC,EACD,mBAAmB,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,WAAW,CAAC,CAAC,CAAC,EAAE,WAAW,CAAC,CAAC,CAAC,CAAC,CACnE,CAAC;KACF;IAED,OAAO,MAAM,CAAC;AACf,CAAC;AAlDD,4BAkDC;AAED,SAAS,mBAAmB,CAAC,EAAU,EAAE,EAAU,EAAE,EAAU;IAC9D,OAAO,EAAE,GAAG,IAAI,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC;AACjC,CAAC;AAED,SAAS,cAAc,CAAC,GAAY,EAAE,WAAiB;IACtD,OAAO,GAAG,CAAC,CAAC,CAAC,WAAW,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,WAAW,CAAC,QAAQ,EAAE,CAAC;AACjE,CAAC;AAED,SAAS,gBAAgB,CAAC,GAAY,EAAE,WAAiB;IACxD,OAAO,GAAG,CAAC,CAAC,CAAC,WAAW,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC,WAAW,CAAC,UAAU,EAAE,CAAC;AACrE,CAAC;AAED,SAAS,gBAAgB,CAAC,GAAY,EAAE,WAAiB;IACxD,OAAO,GAAG,CAAC,CAAC,CAAC,WAAW,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC,WAAW,CAAC,UAAU,EAAE,CAAC;AACrE,CAAC;AAED,2BAA2B;AAC3B,SAAS,YAAY,CAAC,KAAa,EAAE,KAAa,EAAE,MAAc;IACjE,OAAO,KAAK,IAAI,KAAK,IAAI,KAAK,IAAI,MAAM,CAAC;AAC1C,CAAC"} \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/util.d.ts b/node_modules/pac-resolver/dist/util.d.ts new file mode 100644 index 0000000..5fa9b3b --- /dev/null +++ b/node_modules/pac-resolver/dist/util.d.ts @@ -0,0 +1,6 @@ +/// +import { LookupAddress, LookupOptions } from 'dns'; +import { GMT } from './index'; +export declare function dnsLookup(host: string, opts: LookupOptions): Promise; +export declare function isGMT(v?: string): v is GMT; +//# sourceMappingURL=util.d.ts.map \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/util.d.ts.map b/node_modules/pac-resolver/dist/util.d.ts.map new file mode 100644 index 0000000..e9aa0c1 --- /dev/null +++ b/node_modules/pac-resolver/dist/util.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"util.d.ts","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,aAAa,EAAE,aAAa,EAAU,MAAM,KAAK,CAAC;AAC3D,OAAO,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AAE9B,wBAAgB,SAAS,CACxB,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,aAAa,GACjB,OAAO,CAAC,MAAM,GAAG,aAAa,EAAE,CAAC,CAUnC;AAED,wBAAgB,KAAK,CAAC,CAAC,CAAC,EAAE,MAAM,GAAG,CAAC,IAAI,GAAG,CAE1C"} \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/util.js b/node_modules/pac-resolver/dist/util.js new file mode 100644 index 0000000..11709f5 --- /dev/null +++ b/node_modules/pac-resolver/dist/util.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isGMT = exports.dnsLookup = void 0; +const dns_1 = require("dns"); +function dnsLookup(host, opts) { + return new Promise((resolve, reject) => { + (0, dns_1.lookup)(host, opts, (err, res) => { + if (err) { + reject(err); + } + else { + resolve(res); + } + }); + }); +} +exports.dnsLookup = dnsLookup; +function isGMT(v) { + return v === 'GMT'; +} +exports.isGMT = isGMT; +//# sourceMappingURL=util.js.map \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/util.js.map b/node_modules/pac-resolver/dist/util.js.map new file mode 100644 index 0000000..67cf2df --- /dev/null +++ b/node_modules/pac-resolver/dist/util.js.map @@ -0,0 +1 @@ +{"version":3,"file":"util.js","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":";;;AAAA,6BAA2D;AAG3D,SAAgB,SAAS,CACxB,IAAY,EACZ,IAAmB;IAEnB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACtC,IAAA,YAAM,EAAC,IAAI,EAAE,IAAI,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;YAC/B,IAAI,GAAG,EAAE;gBACR,MAAM,CAAC,GAAG,CAAC,CAAC;aACZ;iBAAM;gBACN,OAAO,CAAC,GAAG,CAAC,CAAC;aACb;QACF,CAAC,CAAC,CAAC;IACJ,CAAC,CAAC,CAAC;AACJ,CAAC;AAbD,8BAaC;AAED,SAAgB,KAAK,CAAC,CAAU;IAC/B,OAAO,CAAC,KAAK,KAAK,CAAC;AACpB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/weekdayRange.d.ts b/node_modules/pac-resolver/dist/weekdayRange.d.ts new file mode 100644 index 0000000..4e1389e --- /dev/null +++ b/node_modules/pac-resolver/dist/weekdayRange.d.ts @@ -0,0 +1,45 @@ +import { GMT, Weekday } from './index'; +/** + * Only the first parameter is mandatory. Either the second, the third, or both + * may be left out. + * + * If only one parameter is present, the function yeilds a true value on the + * weekday that the parameter represents. If the string "GMT" is specified as + * a second parameter, times are taken to be in GMT, otherwise in local timezone. + * + * If both wd1 and wd1 are defined, the condition is true if the current weekday + * is in between those two weekdays. Bounds are inclusive. If the "GMT" parameter + * is specified, times are taken to be in GMT, otherwise the local timezone is + * used. + * + * Valid "weekday strings" are: + * + * SUN MON TUE WED THU FRI SAT + * + * Examples: + * + * ``` js + * weekdayRange("MON", "FRI") + * true Monday trhough Friday (local timezone). + * + * weekdayRange("MON", "FRI", "GMT") + * same as above, but GMT timezone. + * + * weekdayRange("SAT") + * true on Saturdays local time. + * + * weekdayRange("SAT", "GMT") + * true on Saturdays GMT time. + * + * weekdayRange("FRI", "MON") + * true Friday through Monday (note, order does matter!). + * ``` + * + * + * @param {String} wd1 one of the weekday strings. + * @param {String} wd2 one of the weekday strings. + * @param {String} gmt is either the string: GMT or is left out. + * @return {Boolean} + */ +export default function weekdayRange(wd1: Weekday, wd2?: Weekday | GMT, gmt?: GMT): boolean; +//# sourceMappingURL=weekdayRange.d.ts.map \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/weekdayRange.d.ts.map b/node_modules/pac-resolver/dist/weekdayRange.d.ts.map new file mode 100644 index 0000000..3b54aa8 --- /dev/null +++ b/node_modules/pac-resolver/dist/weekdayRange.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"weekdayRange.d.ts","sourceRoot":"","sources":["../src/weekdayRange.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,GAAG,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAIvC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AAEH,MAAM,CAAC,OAAO,UAAU,YAAY,CACnC,GAAG,EAAE,OAAO,EACZ,GAAG,CAAC,EAAE,OAAO,GAAG,GAAG,EACnB,GAAG,CAAC,EAAE,GAAG,GACP,OAAO,CAiCT"} \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/weekdayRange.js b/node_modules/pac-resolver/dist/weekdayRange.js new file mode 100644 index 0000000..39f21e8 --- /dev/null +++ b/node_modules/pac-resolver/dist/weekdayRange.js @@ -0,0 +1,91 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const util_1 = require("./util"); +const weekdays = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT']; +/** + * Only the first parameter is mandatory. Either the second, the third, or both + * may be left out. + * + * If only one parameter is present, the function yeilds a true value on the + * weekday that the parameter represents. If the string "GMT" is specified as + * a second parameter, times are taken to be in GMT, otherwise in local timezone. + * + * If both wd1 and wd1 are defined, the condition is true if the current weekday + * is in between those two weekdays. Bounds are inclusive. If the "GMT" parameter + * is specified, times are taken to be in GMT, otherwise the local timezone is + * used. + * + * Valid "weekday strings" are: + * + * SUN MON TUE WED THU FRI SAT + * + * Examples: + * + * ``` js + * weekdayRange("MON", "FRI") + * true Monday trhough Friday (local timezone). + * + * weekdayRange("MON", "FRI", "GMT") + * same as above, but GMT timezone. + * + * weekdayRange("SAT") + * true on Saturdays local time. + * + * weekdayRange("SAT", "GMT") + * true on Saturdays GMT time. + * + * weekdayRange("FRI", "MON") + * true Friday through Monday (note, order does matter!). + * ``` + * + * + * @param {String} wd1 one of the weekday strings. + * @param {String} wd2 one of the weekday strings. + * @param {String} gmt is either the string: GMT or is left out. + * @return {Boolean} + */ +function weekdayRange(wd1, wd2, gmt) { + let useGMTzone = false; + let wd1Index = -1; + let wd2Index = -1; + let wd2IsGmt = false; + if ((0, util_1.isGMT)(gmt)) { + useGMTzone = true; + } + else if ((0, util_1.isGMT)(wd2)) { + useGMTzone = true; + wd2IsGmt = true; + } + wd1Index = weekdays.indexOf(wd1); + if (!wd2IsGmt && isWeekday(wd2)) { + wd2Index = weekdays.indexOf(wd2); + } + const todaysDay = getTodaysDay(useGMTzone); + let result; + if (wd2Index < 0) { + result = todaysDay === wd1Index; + } + else if (wd1Index <= wd2Index) { + result = valueInRange(wd1Index, todaysDay, wd2Index); + } + else { + result = + valueInRange(wd1Index, todaysDay, 6) || + valueInRange(0, todaysDay, wd2Index); + } + return result; +} +exports.default = weekdayRange; +function getTodaysDay(gmt) { + return gmt ? new Date().getUTCDay() : new Date().getDay(); +} +// start <= value <= finish +function valueInRange(start, value, finish) { + return start <= value && value <= finish; +} +function isWeekday(v) { + if (!v) + return false; + return weekdays.includes(v); +} +//# sourceMappingURL=weekdayRange.js.map \ No newline at end of file diff --git a/node_modules/pac-resolver/dist/weekdayRange.js.map b/node_modules/pac-resolver/dist/weekdayRange.js.map new file mode 100644 index 0000000..28a89ac --- /dev/null +++ b/node_modules/pac-resolver/dist/weekdayRange.js.map @@ -0,0 +1 @@ +{"version":3,"file":"weekdayRange.js","sourceRoot":"","sources":["../src/weekday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Q,CAAC,CAAC;KACtC;IAED,OAAO,MAAM,CAAC;AACf,CAAC;AArCD,+BAqCC;AAED,SAAS,YAAY,CAAC,GAAY;IACjC,OAAO,GAAG,CAAC,CAAC,CAAC,IAAI,IAAI,EAAE,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,IAAI,IAAI,EAAE,CAAC,MAAM,EAAE,CAAC;AAC3D,CAAC;AAED,2BAA2B;AAC3B,SAAS,YAAY,CAAC,KAAa,EAAE,KAAa,EAAE,MAAc;IACjE,OAAO,KAAK,IAAI,KAAK,IAAI,KAAK,IAAI,MAAM,CAAC;AAC1C,CAAC;AAED,SAAS,SAAS,CAAC,CAAU;IAC5B,IAAI,CAAC,CAAC;QAAE,OAAO,KAAK,CAAC;IACrB,OAAQ,QAAqB,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;AAC3C,CAAC"} \ No newline at end of file diff --git a/node_modules/pac-resolver/package.json b/node_modules/pac-resolver/package.json new file mode 100644 index 0000000..1abfd28 --- /dev/null +++ b/node_modules/pac-resolver/package.json @@ -0,0 +1,47 @@ +{ + "name": "pac-resolver", + "version": "7.0.1", + "description": "Generates an asynchronous resolver function from a PAC file", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "dist" + ], + "dependencies": { + "degenerator": "^5.0.0", + "netmask": "^2.0.2" + }, + "devDependencies": { + "@tootallnate/quickjs-emscripten": "^0.23.0", + "@types/jest": "^29.5.2", + "@types/netmask": "^1.0.30", + "@types/node": "^14.18.52", + "jest": "^29.5.0", + "ts-jest": "^29.1.0", + "typescript": "^5.1.6", + "tsconfig": "0.0.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/TooTallNate/proxy-agents.git", + "directory": "packages/pac-resolver" + }, + "engines": { + "node": ">= 14" + }, + "keywords": [ + "pac", + "file", + "proxy", + "resolve", + "dns" + ], + "author": "Nathan Rajlich (http://n8.io/)", + "license": "MIT", + "scripts": { + "build": "tsc", + "test": "jest --env node --verbose --bail", + "lint": "eslint . --ext .ts", + "pack": "node ../../scripts/pack.mjs" + } +} \ No newline at end of file diff --git a/node_modules/pend/LICENSE b/node_modules/pend/LICENSE new file mode 100644 index 0000000..0bbb53e --- /dev/null +++ b/node_modules/pend/LICENSE @@ -0,0 +1,23 @@ +The MIT License (Expat) + +Copyright (c) 2014 Andrew Kelley + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation files +(the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of the Software, +and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS +BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/pend/README.md b/node_modules/pend/README.md new file mode 100644 index 0000000..bb40a07 --- /dev/null +++ b/node_modules/pend/README.md @@ -0,0 +1,41 @@ +# Pend + +Dead-simple optimistic async helper. + +## Usage + +```js +var Pend = require('pend'); +var pend = new Pend(); +pend.max = 10; // defaults to Infinity +setTimeout(pend.hold(), 1000); // pend.wait will have to wait for this hold to finish +pend.go(function(cb) { + console.log("this function is immediately executed"); + setTimeout(function() { + console.log("calling cb 1"); + cb(); + }, 500); +}); +pend.go(function(cb) { + console.log("this function is also immediately executed"); + setTimeout(function() { + console.log("calling cb 2"); + cb(); + }, 1000); +}); +pend.wait(function(err) { + console.log("this is excuted when the first 2 have returned."); + console.log("err is a possible error in the standard callback style."); +}); +``` + +Output: + +``` +this function is immediately executed +this function is also immediately executed +calling cb 1 +calling cb 2 +this is excuted when the first 2 have returned. +err is a possible error in the standard callback style. +``` diff --git a/node_modules/pend/index.js b/node_modules/pend/index.js new file mode 100644 index 0000000..3bf485e --- /dev/null +++ b/node_modules/pend/index.js @@ -0,0 +1,55 @@ +module.exports = Pend; + +function Pend() { + this.pending = 0; + this.max = Infinity; + this.listeners = []; + this.waiting = []; + this.error = null; +} + +Pend.prototype.go = function(fn) { + if (this.pending < this.max) { + pendGo(this, fn); + } else { + this.waiting.push(fn); + } +}; + +Pend.prototype.wait = function(cb) { + if (this.pending === 0) { + cb(this.error); + } else { + this.listeners.push(cb); + } +}; + +Pend.prototype.hold = function() { + return pendHold(this); +}; + +function pendHold(self) { + self.pending += 1; + var called = false; + return onCb; + function onCb(err) { + if (called) throw new Error("callback called twice"); + called = true; + self.error = self.error || err; + self.pending -= 1; + if (self.waiting.length > 0 && self.pending < self.max) { + pendGo(self, self.waiting.shift()); + } else if (self.pending === 0) { + var listeners = self.listeners; + self.listeners = []; + listeners.forEach(cbListener); + } + } + function cbListener(listener) { + listener(self.error); + } +} + +function pendGo(self, fn) { + fn(pendHold(self)); +} diff --git a/node_modules/pend/package.json b/node_modules/pend/package.json new file mode 100644 index 0000000..8181f8b --- /dev/null +++ b/node_modules/pend/package.json @@ -0,0 +1,18 @@ +{ + "name": "pend", + "version": "1.2.0", + "description": "dead-simple optimistic async helper", + "main": "index.js", + "scripts": { + "test": "node test.js" + }, + "author": "Andrew Kelley ", + "license": "MIT", + "repository": { + "type": "git", + "url": "git://github.com/andrewrk/node-pend.git" + }, + "bugs": { + "url": "https://github.com/andrewrk/node-pend/issues" + } +} diff --git a/node_modules/pend/test.js b/node_modules/pend/test.js new file mode 100644 index 0000000..75c0f2a --- /dev/null +++ b/node_modules/pend/test.js @@ -0,0 +1,137 @@ +var assert = require('assert'); +var Pend = require('./'); + +var tests = [ + { + name: "basic", + fn: testBasic, + }, + { + name: "max", + fn: testWithMax, + }, + { + name: "callback twice", + fn: testCallbackTwice, + }, + { + name: "calling wait twice", + fn: testCallingWaitTwice, + }, + { + name: "hold()", + fn: testHoldFn, + }, +]; +var testCount = tests.length; + +doOneTest(); + +function doOneTest() { + var test = tests.shift(); + if (!test) { + console.log(testCount + " tests passed."); + return; + } + process.stdout.write(test.name + "..."); + test.fn(function() { + process.stdout.write("OK\n"); + doOneTest(); + }); +} + +function testBasic(cb) { + var pend = new Pend(); + var results = []; + pend.go(function(cb) { + results.push(1); + setTimeout(function() { + results.push(3); + cb(); + }, 500); + }); + pend.go(function(cb) { + results.push(2); + setTimeout(function() { + results.push(4); + cb(); + }, 1000); + }); + pend.wait(function(err) { + assert.deepEqual(results, [1,2,3,4]); + cb(); + }); + assert.deepEqual(results, [1, 2]); +} + +function testWithMax(cb) { + var pend = new Pend(); + var results = []; + pend.max = 2; + pend.go(function(cb) { + results.push('a'); + setTimeout(function() { + results.push(1); + cb(); + }, 500); + }); + pend.go(function(cb) { + results.push('b'); + setTimeout(function() { + results.push(1); + cb(); + }, 500); + }); + pend.go(function(cb) { + results.push('c'); + setTimeout(function() { + results.push(2); + cb(); + }, 100); + }); + pend.wait(function(err) { + assert.deepEqual(results, ['a', 'b', 1, 'c', 1, 2]); + cb(); + }); + assert.deepEqual(results, ['a', 'b']); +} + +function testCallbackTwice(cb) { + var pend = new Pend(); + pend.go(function(cb) { + setTimeout(cb, 100); + }); + pend.go(function(cb) { + cb(); + assert.throws(cb, /callback called twice/); + }); + pend.wait(cb); +} + +function testCallingWaitTwice(cb) { + var pend = new Pend(); + pend.go(function(cb) { + setTimeout(cb, 100); + }); + pend.wait(function() { + pend.go(function(cb) { + setTimeout(cb, 50); + }); + pend.go(function(cb) { + setTimeout(cb, 10); + }); + pend.go(function(cb) { + setTimeout(cb, 20); + }); + pend.wait(cb); + }); +} + +function testHoldFn(cb) { + var pend = new Pend(); + setTimeout(pend.hold(), 100); + pend.go(function(cb) { + cb(); + }); + pend.wait(cb); +} diff --git a/node_modules/progress/CHANGELOG.md b/node_modules/progress/CHANGELOG.md new file mode 100644 index 0000000..d9be0aa --- /dev/null +++ b/node_modules/progress/CHANGELOG.md @@ -0,0 +1,115 @@ + +2.0.0 / 2017-04-04 +================== + + * Fix: check before using stream.clearLine to prevent crash in Docker + * Fix: fixed output multiline on windows cmd + * Fix: Bug with array length when window is too small + * Fix: Don't clear whole line every time; instead, clear everything after end of line + * Fix: Use `this.stream` instead of `console.log` when terminating a progress bar to ensure that, if a writable stream is provided, it uses that rather than process.stdout + * Fix: Bug causing potentially stale tokens on render + * Feature: configurable cursor + * Feature: feature to interrupt the bar and display a message + * Feature: Add rate reporting to progress bar + * Improvement: Add head option to specify head character + * Improvement: Rename tickTokens to tokens + * Improvement: Change default throttle time to 16ms + * Improvement: Rename renderDelay to renderThrottle + * Improvement: Add delay between render updates + * Docs: Add example and documentation for custom token usage + * Docs: Add head option to readme + * Docs: Updated README example for public use + * Docs: Add renderThrottle option to code documentation + +1.1.7 / 2014-06-30 +================== + + * fixed a bug that occurs when a progress bar attempts to draw itself + on a console with very few columns + +1.1.6 / 2014-06-16 +================== + + * now prevents progress bar from exceeding TTY width by limiting its width to + the with of the TTY + +1.1.5 / 2014-03-25 +================== + + * updated documentation and various other repo maintenance + * updated makefile to run examples with `make` + * removed dependency on readline module + +1.1.4 / 2014-03-14 +================== + + * now supports streams, for example output progress bar to stderr, while piping + stdout + * increases performance and flicker by remembering the last drawn progress bar + +1.1.3 / 2013-12-31 +================== + + * fixes a bug where bar would bug when initializing + * allows to pass updated tokens when ticking or updating the bar + * fixes a bug where the bar would throw if skipping to far + +1.1.2 / 2013-10-17 +================== + + * lets you pass an `fmt` and a `total` instead of an options object + +1.1.0 / 2013-09-18 +================== + + * eta and elapsed tokens default to 0.0 instead of ?.? + * better JSDocs + * added back and forth example + * added method to update the progress bar to a specific percentage + * added an option to hide the bar on completion + +1.0.1 / 2013-08-07 +================== + + * on os x readline now works, reverting the terminal hack + +1.0.0 / 2013-06-18 +================== + + * remove .version + * merge pull request #15 from davglass/readline-osx + * on OSX revert back to terminal hack to avoid a readline bug + +0.1.0 / 2012-09-19 +================== + + * fixed logic bug that caused bar to jump one extra space at the end [davglass] + * working with readline impl, even on Windows [davglass] + * using readline instead of the \r hack [davglass] + +0.0.5 / 2012-08-07 +================== + + * add ability to tick by zero chunks - tick(0) + * fix ETA. Closes #4 [lwille] + +0.0.4 / 2011-11-14 +================== + + * allow more recent versions of node + +0.0.3 / 2011-04-20 +================== + + * changed; erase the line when complete + +0.0.2 / 2011-04-20 +================== + + * added custom tokens support + * fixed; clear line before writing + +0.0.1 / 2010-01-03 +================== + + * initial release diff --git a/node_modules/progress/LICENSE b/node_modules/progress/LICENSE new file mode 100644 index 0000000..4608b39 --- /dev/null +++ b/node_modules/progress/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2017 TJ Holowaychuk + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/progress/Makefile b/node_modules/progress/Makefile new file mode 100644 index 0000000..f933be1 --- /dev/null +++ b/node_modules/progress/Makefile @@ -0,0 +1,8 @@ + +EXAMPLES = $(foreach EXAMPLE, $(wildcard examples/*.js), $(EXAMPLE)) + +.PHONY: test +test: $(EXAMPLES) + +.PHONY: $(EXAMPLES) +$(EXAMPLES): ; node $@ && echo diff --git a/node_modules/progress/Readme.md b/node_modules/progress/Readme.md new file mode 100644 index 0000000..6d4271a --- /dev/null +++ b/node_modules/progress/Readme.md @@ -0,0 +1,146 @@ +Flexible ascii progress bar. + +## Installation + +```bash +$ npm install progress +``` + +## Usage + +First we create a `ProgressBar`, giving it a format string +as well as the `total`, telling the progress bar when it will +be considered complete. After that all we need to do is `tick()` appropriately. + +```javascript +var ProgressBar = require('progress'); + +var bar = new ProgressBar(':bar', { total: 10 }); +var timer = setInterval(function () { + bar.tick(); + if (bar.complete) { + console.log('\ncomplete\n'); + clearInterval(timer); + } +}, 100); +``` + +### Options + +These are keys in the options object you can pass to the progress bar along with +`total` as seen in the example above. + +- `curr` current completed index +- `total` total number of ticks to complete +- `width` the displayed width of the progress bar defaulting to total +- `stream` the output stream defaulting to stderr +- `head` head character defaulting to complete character +- `complete` completion character defaulting to "=" +- `incomplete` incomplete character defaulting to "-" +- `renderThrottle` minimum time between updates in milliseconds defaulting to 16 +- `clear` option to clear the bar on completion defaulting to false +- `callback` optional function to call when the progress bar completes + +### Tokens + +These are tokens you can use in the format of your progress bar. + +- `:bar` the progress bar itself +- `:current` current tick number +- `:total` total ticks +- `:elapsed` time elapsed in seconds +- `:percent` completion percentage +- `:eta` estimated completion time in seconds +- `:rate` rate of ticks per second + +### Custom Tokens + +You can define custom tokens by adding a `{'name': value}` object parameter to your method (`tick()`, `update()`, etc.) calls. + +```javascript +var bar = new ProgressBar(':current: :token1 :token2', { total: 3 }) +bar.tick({ + 'token1': "Hello", + 'token2': "World!\n" +}) +bar.tick(2, { + 'token1': "Goodbye", + 'token2': "World!" +}) +``` +The above example would result in the output below. + +``` +1: Hello World! +3: Goodbye World! +``` + +## Examples + +### Download + +In our download example each tick has a variable influence, so we pass the chunk +length which adjusts the progress bar appropriately relative to the total +length. + +```javascript +var ProgressBar = require('progress'); +var https = require('https'); + +var req = https.request({ + host: 'download.github.com', + port: 443, + path: '/visionmedia-node-jscoverage-0d4608a.zip' +}); + +req.on('response', function(res){ + var len = parseInt(res.headers['content-length'], 10); + + console.log(); + var bar = new ProgressBar(' downloading [:bar] :rate/bps :percent :etas', { + complete: '=', + incomplete: ' ', + width: 20, + total: len + }); + + res.on('data', function (chunk) { + bar.tick(chunk.length); + }); + + res.on('end', function () { + console.log('\n'); + }); +}); + +req.end(); +``` + +The above example result in a progress bar like the one below. + +``` +downloading [===== ] 39/bps 29% 3.7s +``` + +### Interrupt + +To display a message during progress bar execution, use `interrupt()` +```javascript +var ProgressBar = require('progress'); + +var bar = new ProgressBar(':bar :current/:total', { total: 10 }); +var timer = setInterval(function () { + bar.tick(); + if (bar.complete) { + clearInterval(timer); + } else if (bar.curr === 5) { + bar.interrupt('this message appears above the progress bar\ncurrent progress is ' + bar.curr + '/' + bar.total); + } +}, 1000); +``` + +You can see more examples in the `examples` folder. + +## License + +MIT diff --git a/node_modules/progress/index.js b/node_modules/progress/index.js new file mode 100644 index 0000000..4449dd3 --- /dev/null +++ b/node_modules/progress/index.js @@ -0,0 +1 @@ +module.exports = require('./lib/node-progress'); diff --git a/node_modules/progress/lib/node-progress.js b/node_modules/progress/lib/node-progress.js new file mode 100644 index 0000000..8eb0740 --- /dev/null +++ b/node_modules/progress/lib/node-progress.js @@ -0,0 +1,236 @@ +/*! + * node-progress + * Copyright(c) 2011 TJ Holowaychuk + * MIT Licensed + */ + +/** + * Expose `ProgressBar`. + */ + +exports = module.exports = ProgressBar; + +/** + * Initialize a `ProgressBar` with the given `fmt` string and `options` or + * `total`. + * + * Options: + * + * - `curr` current completed index + * - `total` total number of ticks to complete + * - `width` the displayed width of the progress bar defaulting to total + * - `stream` the output stream defaulting to stderr + * - `head` head character defaulting to complete character + * - `complete` completion character defaulting to "=" + * - `incomplete` incomplete character defaulting to "-" + * - `renderThrottle` minimum time between updates in milliseconds defaulting to 16 + * - `callback` optional function to call when the progress bar completes + * - `clear` will clear the progress bar upon termination + * + * Tokens: + * + * - `:bar` the progress bar itself + * - `:current` current tick number + * - `:total` total ticks + * - `:elapsed` time elapsed in seconds + * - `:percent` completion percentage + * - `:eta` eta in seconds + * - `:rate` rate of ticks per second + * + * @param {string} fmt + * @param {object|number} options or total + * @api public + */ + +function ProgressBar(fmt, options) { + this.stream = options.stream || process.stderr; + + if (typeof(options) == 'number') { + var total = options; + options = {}; + options.total = total; + } else { + options = options || {}; + if ('string' != typeof fmt) throw new Error('format required'); + if ('number' != typeof options.total) throw new Error('total required'); + } + + this.fmt = fmt; + this.curr = options.curr || 0; + this.total = options.total; + this.width = options.width || this.total; + this.clear = options.clear + this.chars = { + complete : options.complete || '=', + incomplete : options.incomplete || '-', + head : options.head || (options.complete || '=') + }; + this.renderThrottle = options.renderThrottle !== 0 ? (options.renderThrottle || 16) : 0; + this.lastRender = -Infinity; + this.callback = options.callback || function () {}; + this.tokens = {}; + this.lastDraw = ''; +} + +/** + * "tick" the progress bar with optional `len` and optional `tokens`. + * + * @param {number|object} len or tokens + * @param {object} tokens + * @api public + */ + +ProgressBar.prototype.tick = function(len, tokens){ + if (len !== 0) + len = len || 1; + + // swap tokens + if ('object' == typeof len) tokens = len, len = 1; + if (tokens) this.tokens = tokens; + + // start time for eta + if (0 == this.curr) this.start = new Date; + + this.curr += len + + // try to render + this.render(); + + // progress complete + if (this.curr >= this.total) { + this.render(undefined, true); + this.complete = true; + this.terminate(); + this.callback(this); + return; + } +}; + +/** + * Method to render the progress bar with optional `tokens` to place in the + * progress bar's `fmt` field. + * + * @param {object} tokens + * @api public + */ + +ProgressBar.prototype.render = function (tokens, force) { + force = force !== undefined ? force : false; + if (tokens) this.tokens = tokens; + + if (!this.stream.isTTY) return; + + var now = Date.now(); + var delta = now - this.lastRender; + if (!force && (delta < this.renderThrottle)) { + return; + } else { + this.lastRender = now; + } + + var ratio = this.curr / this.total; + ratio = Math.min(Math.max(ratio, 0), 1); + + var percent = Math.floor(ratio * 100); + var incomplete, complete, completeLength; + var elapsed = new Date - this.start; + var eta = (percent == 100) ? 0 : elapsed * (this.total / this.curr - 1); + var rate = this.curr / (elapsed / 1000); + + /* populate the bar template with percentages and timestamps */ + var str = this.fmt + .replace(':current', this.curr) + .replace(':total', this.total) + .replace(':elapsed', isNaN(elapsed) ? '0.0' : (elapsed / 1000).toFixed(1)) + .replace(':eta', (isNaN(eta) || !isFinite(eta)) ? '0.0' : (eta / 1000) + .toFixed(1)) + .replace(':percent', percent.toFixed(0) + '%') + .replace(':rate', Math.round(rate)); + + /* compute the available space (non-zero) for the bar */ + var availableSpace = Math.max(0, this.stream.columns - str.replace(':bar', '').length); + if(availableSpace && process.platform === 'win32'){ + availableSpace = availableSpace - 1; + } + + var width = Math.min(this.width, availableSpace); + + /* TODO: the following assumes the user has one ':bar' token */ + completeLength = Math.round(width * ratio); + complete = Array(Math.max(0, completeLength + 1)).join(this.chars.complete); + incomplete = Array(Math.max(0, width - completeLength + 1)).join(this.chars.incomplete); + + /* add head to the complete string */ + if(completeLength > 0) + complete = complete.slice(0, -1) + this.chars.head; + + /* fill in the actual progress bar */ + str = str.replace(':bar', complete + incomplete); + + /* replace the extra tokens */ + if (this.tokens) for (var key in this.tokens) str = str.replace(':' + key, this.tokens[key]); + + if (this.lastDraw !== str) { + this.stream.cursorTo(0); + this.stream.write(str); + this.stream.clearLine(1); + this.lastDraw = str; + } +}; + +/** + * "update" the progress bar to represent an exact percentage. + * The ratio (between 0 and 1) specified will be multiplied by `total` and + * floored, representing the closest available "tick." For example, if a + * progress bar has a length of 3 and `update(0.5)` is called, the progress + * will be set to 1. + * + * A ratio of 0.5 will attempt to set the progress to halfway. + * + * @param {number} ratio The ratio (between 0 and 1 inclusive) to set the + * overall completion to. + * @api public + */ + +ProgressBar.prototype.update = function (ratio, tokens) { + var goal = Math.floor(ratio * this.total); + var delta = goal - this.curr; + + this.tick(delta, tokens); +}; + +/** + * "interrupt" the progress bar and write a message above it. + * @param {string} message The message to write. + * @api public + */ + +ProgressBar.prototype.interrupt = function (message) { + // clear the current line + this.stream.clearLine(); + // move the cursor to the start of the line + this.stream.cursorTo(0); + // write the message text + this.stream.write(message); + // terminate the line after writing the message + this.stream.write('\n'); + // re-display the progress bar with its lastDraw + this.stream.write(this.lastDraw); +}; + +/** + * Terminates a progress bar. + * + * @api public + */ + +ProgressBar.prototype.terminate = function () { + if (this.clear) { + if (this.stream.clearLine) { + this.stream.clearLine(); + this.stream.cursorTo(0); + } + } else { + this.stream.write('\n'); + } +}; diff --git a/node_modules/progress/package.json b/node_modules/progress/package.json new file mode 100644 index 0000000..bb81fa0 --- /dev/null +++ b/node_modules/progress/package.json @@ -0,0 +1,26 @@ +{ + "name": "progress", + "version": "2.0.3", + "description": "Flexible ascii progress bar", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/node-progress" + }, + "keywords": [ + "cli", + "progress" + ], + "author": "TJ Holowaychuk ", + "contributors": [ + "Christoffer Hallas ", + "Jordan Scales ", + "Andrew Rhyne ", + "Marco Brack " + ], + "dependencies": {}, + "main": "./index.js", + "engines": { + "node": ">=0.4.0" + }, + "license": "MIT" +} diff --git a/node_modules/proxy-agent/LICENSE b/node_modules/proxy-agent/LICENSE new file mode 100644 index 0000000..008728c --- /dev/null +++ b/node_modules/proxy-agent/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2013 Nathan Rajlich + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/proxy-agent/README.md b/node_modules/proxy-agent/README.md new file mode 100644 index 0000000..7bc9b3e --- /dev/null +++ b/node_modules/proxy-agent/README.md @@ -0,0 +1,59 @@ +proxy-agent +=========== +### Maps proxy protocols to `http.Agent` implementations + +This module provides an `http.Agent` implementation which automatically uses +proxy servers based off of the various proxy-related environment variables +(`HTTP_PROXY`, `HTTPS_PROXY` and `NO_PROXY` among others). + +Which proxy is used for each HTTP request is determined by the +[`proxy-from-env`](https://www.npmjs.com/package/proxy-from-env) module, so +check its documentation for instructions on configuring your environment variables. + +An LRU cache is used so that `http.Agent` instances are transparently re-used for +subsequent HTTP requests to the same proxy server. + +The currently implemented protocol mappings are listed in the table below: + + +| Protocol | Proxy Agent for `http` requests | Proxy Agent for `https` requests | Example +|:----------:|:-------------------------------:|:--------------------------------:|:--------: +| `http` | [http-proxy-agent][] | [https-proxy-agent][] | `http://proxy-server-over-tcp.com:3128` +| `https` | [http-proxy-agent][] | [https-proxy-agent][] | `https://proxy-server-over-tls.com:3129` +| `socks(v5)`| [socks-proxy-agent][] | [socks-proxy-agent][] | `socks://username:password@some-socks-proxy.com:9050` (username & password are optional) +| `socks5` | [socks-proxy-agent][] | [socks-proxy-agent][] | `socks5://username:password@some-socks-proxy.com:9050` (username & password are optional) +| `socks4` | [socks-proxy-agent][] | [socks-proxy-agent][] | `socks4://some-socks-proxy.com:9050` +| `pac-*` | [pac-proxy-agent][] | [pac-proxy-agent][] | `pac+http://www.example.com/proxy.pac` + +Example +------- + +```ts +import * as https from 'https'; +import { ProxyAgent } from 'proxy-agent'; + +// The correct proxy `Agent` implementation to use will be determined +// via the `http_proxy` / `https_proxy` / `no_proxy` / etc. env vars +const agent = new ProxyAgent(); + +// The rest works just like any other normal HTTP request +https.get('https://jsonip.com', { agent }, (res) => { + console.log(res.statusCode, res.headers); + res.pipe(process.stdout); +}); +``` + + +API +--- + +### new ProxyAgent(options?: ProxyAgentOptions) + +Creates an `http.Agent` instance which relies on the various proxy-related +environment variables. An LRU cache is used, so the same `http.Agent` instance +will be returned if identical args are passed in. + +[http-proxy-agent]: ../http-proxy-agent +[https-proxy-agent]: ../https-proxy-agent +[socks-proxy-agent]: ../socks-proxy-agent +[pac-proxy-agent]: ../pac-proxy-agent diff --git a/node_modules/proxy-agent/dist/index.d.ts b/node_modules/proxy-agent/dist/index.d.ts new file mode 100644 index 0000000..e883ce4 --- /dev/null +++ b/node_modules/proxy-agent/dist/index.d.ts @@ -0,0 +1,62 @@ +/// +import * as http from 'http'; +import LRUCache from 'lru-cache'; +import { Agent, AgentConnectOpts } from 'agent-base'; +import type { PacProxyAgent, PacProxyAgentOptions } from 'pac-proxy-agent'; +import type { HttpProxyAgent, HttpProxyAgentOptions } from 'http-proxy-agent'; +import type { HttpsProxyAgent, HttpsProxyAgentOptions } from 'https-proxy-agent'; +import type { SocksProxyAgent, SocksProxyAgentOptions } from 'socks-proxy-agent'; +type ValidProtocol = (typeof HttpProxyAgent.protocols)[number] | (typeof HttpsProxyAgent.protocols)[number] | (typeof SocksProxyAgent.protocols)[number] | (typeof PacProxyAgent.protocols)[number]; +type AgentConstructor = new (proxy: string, proxyAgentOptions?: ProxyAgentOptions) => Agent; +type GetProxyForUrlCallback = (url: string, req: http.ClientRequest) => string | Promise; +/** + * Supported proxy types. + */ +export declare const proxies: { + [P in ValidProtocol]: [ + () => Promise, + () => Promise + ]; +}; +export type ProxyAgentOptions = HttpProxyAgentOptions<''> & HttpsProxyAgentOptions<''> & SocksProxyAgentOptions & PacProxyAgentOptions<''> & { + /** + * Default `http.Agent` instance to use when no proxy is + * configured for a request. Defaults to a new `http.Agent()` + * instance with the proxy agent options passed in. + */ + httpAgent?: http.Agent; + /** + * Default `http.Agent` instance to use when no proxy is + * configured for a request. Defaults to a new `https.Agent()` + * instance with the proxy agent options passed in. + */ + httpsAgent?: http.Agent; + /** + * A callback for dynamic provision of proxy for url. + * Defaults to standard proxy environment variables, + * see https://www.npmjs.com/package/proxy-from-env for details + */ + getProxyForUrl?: GetProxyForUrlCallback; +}; +/** + * Uses the appropriate `Agent` subclass based off of the "proxy" + * environment variables that are currently set. + * + * An LRU cache is used, to prevent unnecessary creation of proxy + * `http.Agent` instances. + */ +export declare class ProxyAgent extends Agent { + /** + * Cache for `Agent` instances. + */ + cache: LRUCache; + connectOpts?: ProxyAgentOptions; + httpAgent: http.Agent; + httpsAgent: http.Agent; + getProxyForUrl: GetProxyForUrlCallback; + constructor(opts?: ProxyAgentOptions); + connect(req: http.ClientRequest, opts: AgentConnectOpts): Promise; + destroy(): void; +} +export {}; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/proxy-agent/dist/index.d.ts.map b/node_modules/proxy-agent/dist/index.d.ts.map new file mode 100644 index 0000000..2cbaaa1 --- /dev/null +++ b/node_modules/proxy-agent/dist/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAG7B,OAAO,QAAQ,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAGrD,OAAO,KAAK,EAAE,aAAa,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AAC3E,OAAO,KAAK,EAAE,cAAc,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAC9E,OAAO,KAAK,EACX,eA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BAAiB,CAAC;IAChC,SAAS,EAAE,IAAI,CAAC,KAAK,CAAC;IACtB,UAAU,EAAE,IAAI,CAAC,KAAK,CAAC;IACvB,cAAc,EAAE,sBAAsB,CAAC;gBAE3B,IAAI,CAAC,EAAE,iBAAiB;IAU9B,OAAO,CACZ,GAAG,EAAE,IAAI,CAAC,aAAa,EACvB,IAAI,EAAE,gBAAgB,GACpB,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC;IA2CtB,OAAO,IAAI,IAAI;CAMf"} \ No newline at end of file diff --git a/node_modules/proxy-agent/dist/index.js b/node_modules/proxy-agent/dist/index.js new file mode 100644 index 0000000..95680f4 --- /dev/null +++ b/node_modules/proxy-agent/dist/index.js @@ -0,0 +1,138 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ProxyAgent = exports.proxies = void 0; +const http = __importStar(require("http")); +const https = __importStar(require("https")); +const url_1 = require("url"); +const lru_cache_1 = __importDefault(require("lru-cache")); +const agent_base_1 = require("agent-base"); +const debug_1 = __importDefault(require("debug")); +const proxy_from_env_1 = require("proxy-from-env"); +const debug = (0, debug_1.default)('proxy-agent'); +/** + * Shorthands for built-in supported types. + * Lazily loaded since some of these imports can be quite expensive + * (in particular, pac-proxy-agent). + */ +const wellKnownAgents = { + http: async () => (await Promise.resolve().then(() => __importStar(require('http-proxy-agent')))).HttpProxyAgent, + https: async () => (await Promise.resolve().then(() => __importStar(require('https-proxy-agent')))).HttpsProxyAgent, + socks: async () => (await Promise.resolve().then(() => __importStar(require('socks-proxy-agent')))).SocksProxyAgent, + pac: async () => (await Promise.resolve().then(() => __importStar(require('pac-proxy-agent')))).PacProxyAgent, +}; +/** + * Supported proxy types. + */ +exports.proxies = { + http: [wellKnownAgents.http, wellKnownAgents.https], + https: [wellKnownAgents.http, wellKnownAgents.https], + socks: [wellKnownAgents.socks, wellKnownAgents.socks], + socks4: [wellKnownAgents.socks, wellKnownAgents.socks], + socks4a: [wellKnownAgents.socks, wellKnownAgents.socks], + socks5: [wellKnownAgents.socks, wellKnownAgents.socks], + socks5h: [wellKnownAgents.socks, wellKnownAgents.socks], + 'pac+data': [wellKnownAgents.pac, wellKnownAgents.pac], + 'pac+file': [wellKnownAgents.pac, wellKnownAgents.pac], + 'pac+ftp': [wellKnownAgents.pac, wellKnownAgents.pac], + 'pac+http': [wellKnownAgents.pac, wellKnownAgents.pac], + 'pac+https': [wellKnownAgents.pac, wellKnownAgents.pac], +}; +function isValidProtocol(v) { + return Object.keys(exports.proxies).includes(v); +} +/** + * Uses the appropriate `Agent` subclass based off of the "proxy" + * environment variables that are currently set. + * + * An LRU cache is used, to prevent unnecessary creation of proxy + * `http.Agent` instances. + */ +class ProxyAgent extends agent_base_1.Agent { + constructor(opts) { + super(opts); + /** + * Cache for `Agent` instances. + */ + this.cache = new lru_cache_1.default({ + max: 20, + dispose: (agent) => agent.destroy(), + }); + debug('Creating new ProxyAgent instance: %o', opts); + this.connectOpts = opts; + this.httpAgent = opts?.httpAgent || new http.Agent(opts); + this.httpsAgent = + opts?.httpsAgent || new https.Agent(opts); + this.getProxyForUrl = opts?.getProxyForUrl || proxy_from_env_1.getProxyForUrl; + } + async connect(req, opts) { + const { secureEndpoint } = opts; + const isWebSocket = req.getHeader('upgrade') === 'websocket'; + const protocol = secureEndpoint + ? isWebSocket + ? 'wss:' + : 'https:' + : isWebSocket + ? 'ws:' + : 'http:'; + const host = req.getHeader('host'); + const url = new url_1.URL(req.path, `${protocol}//${host}`).href; + const proxy = await this.getProxyForUrl(url, req); + if (!proxy) { + debug('Proxy not enabled for URL: %o', url); + return secureEndpoint ? this.httpsAgent : this.httpAgent; + } + debug('Request URL: %o', url); + debug('Proxy URL: %o', proxy); + // attempt to get a cached `http.Agent` instance first + const cacheKey = `${protocol}+${proxy}`; + let agent = this.cache.get(cacheKey); + if (!agent) { + const proxyUrl = new url_1.URL(proxy); + const proxyProto = proxyUrl.protocol.replace(':', ''); + if (!isValidProtocol(proxyProto)) { + throw new Error(`Unsupported protocol for proxy URL: ${proxy}`); + } + const ctor = await exports.proxies[proxyProto][secureEndpoint || isWebSocket ? 1 : 0](); + agent = new ctor(proxy, this.connectOpts); + this.cache.set(cacheKey, agent); + } + else { + debug('Cache hit for proxy URL: %o', proxy); + } + return agent; + } + destroy() { + for (const agent of this.cache.values()) { + agent.destroy(); + } + super.destroy(); + } +} +exports.ProxyAgent = ProxyAgent; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/proxy-agent/dist/index.js.map b/node_modules/proxy-agent/dist/index.js.map new file mode 100644 index 0000000..bb47b5c --- /dev/null +++ b/node_modules/proxy-agent/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,2CAA6B;AAC7B,6CAA+B;AAC/B,6BAA0B;AAC1B,0DAAiC;AACjC,2CAAqD;AACrD,kDAAgC;AAChC,mDAAqE;AAYrE,MAAM,KAAK,GAAG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,IAAI,CAAC,WAAW,CAAC,CAAC;YAC1C,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;SAChC;aAAM;YACN,KAAK,CAAC,6BAA6B,EAAE,KAAK,CAAC,CAAC;SAC5C;QAED,OAAO,KAAK,CAAC;IACd,CAAC;IAED,OAAO;QACN,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,EAAE;YACxC,KAAK,CAAC,OAAO,EAAE,CAAC;SAChB;QACD,KAAK,CAAC,OAAO,EAAE,CAAC;IACjB,CAAC;CACD;AA5ED,gCA4EC"} \ No newline at end of file diff --git a/node_modules/proxy-agent/package.json b/node_modules/proxy-agent/package.json new file mode 100644 index 0000000..3113ac9 --- /dev/null +++ b/node_modules/proxy-agent/package.json @@ -0,0 +1,60 @@ +{ + "name": "proxy-agent", + "version": "6.5.0", + "description": "Maps proxy protocols to `http.Agent` implementations", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "dist" + ], + "engines": { + "node": ">= 14" + }, + "repository": { + "type": "git", + "url": "https://github.com/TooTallNate/proxy-agents.git", + "directory": "packages/proxy-agent" + }, + "keywords": [ + "http", + "https", + "socks", + "agent", + "mapping", + "proxy" + ], + "author": "Nathan Rajlich (http://n8.io/)", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "^4.3.4", + "http-proxy-agent": "^7.0.1", + "https-proxy-agent": "^7.0.6", + "lru-cache": "^7.14.1", + "pac-proxy-agent": "^7.1.0", + "proxy-from-env": "^1.1.0", + "socks-proxy-agent": "^8.0.5" + }, + "devDependencies": { + "@types/agent-base": "^4.2.0", + "@types/debug": "^4.1.7", + "@types/jest": "^29.5.1", + "@types/node": "^14.18.45", + "@types/proxy-from-env": "^1.0.1", + "@types/ws": "^8.5.4", + "async-listen": "^3.0.0", + "jest": "^29.5.0", + "socksv5": "github:TooTallNate/socksv5#fix/dstSock-close-event", + "ts-jest": "^29.1.0", + "typescript": "^5.0.4", + "ws": "^8.13.0", + "proxy": "2.2.0", + "tsconfig": "0.0.0" + }, + "scripts": { + "build": "tsc", + "test": "jest --env node --verbose --bail", + "lint": "eslint . --ext .ts", + "pack": "node ../../scripts/pack.mjs" + } +} \ No newline at end of file diff --git a/node_modules/proxy-from-env/.eslintrc b/node_modules/proxy-from-env/.eslintrc new file mode 100644 index 0000000..a51449b --- /dev/null +++ b/node_modules/proxy-from-env/.eslintrc @@ -0,0 +1,29 @@ +{ + "env": { + "node": true + }, + "rules": { + "array-bracket-spacing": [2, "never"], + "block-scoped-var": 2, + "brace-style": [2, "1tbs"], + "camelcase": 1, + "computed-property-spacing": [2, "never"], + "curly": 2, + "eol-last": 2, + "eqeqeq": [2, "smart"], + "max-depth": [1, 3], + "max-len": [1, 80], + "max-statements": [1, 15], + "new-cap": 1, + "no-extend-native": 2, + "no-mixed-spaces-and-tabs": 2, + "no-trailing-spaces": 2, + "no-unused-vars": 1, + "no-use-before-define": [2, "nofunc"], + "object-curly-spacing": [2, "never"], + "quotes": [2, "single", "avoid-escape"], + "semi": [2, "always"], + "keyword-spacing": [2, {"before": true, "after": true}], + "space-unary-ops": 2 + } +} diff --git a/node_modules/proxy-from-env/.travis.yml b/node_modules/proxy-from-env/.travis.yml new file mode 100644 index 0000000..64a05f9 --- /dev/null +++ b/node_modules/proxy-from-env/.travis.yml @@ -0,0 +1,10 @@ +language: node_js +node_js: + - node + - lts/* +script: + - npm run lint + # test-coverage will also run the tests, but does not print helpful output upon test failure. + # So we also run the tests separately. + - npm run test + - npm run test-coverage && cat coverage/lcov.info | ./node_modules/.bin/coveralls && rm -rf coverage diff --git a/node_modules/proxy-from-env/LICENSE b/node_modules/proxy-from-env/LICENSE new file mode 100644 index 0000000..8f25097 --- /dev/null +++ b/node_modules/proxy-from-env/LICENSE @@ -0,0 +1,20 @@ +The MIT License + +Copyright (C) 2016-2018 Rob Wu + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/proxy-from-env/README.md b/node_modules/proxy-from-env/README.md new file mode 100644 index 0000000..e82520c --- /dev/null +++ b/node_modules/proxy-from-env/README.md @@ -0,0 +1,131 @@ +# proxy-from-env + +[![Build Status](https://travis-ci.org/Rob--W/proxy-from-env.svg?branch=master)](https://travis-ci.org/Rob--W/proxy-from-env) +[![Coverage Status](https://coveralls.io/repos/github/Rob--W/proxy-from-env/badge.svg?branch=master)](https://coveralls.io/github/Rob--W/proxy-from-env?branch=master) + +`proxy-from-env` is a Node.js package that exports a function (`getProxyForUrl`) +that takes an input URL (a string or +[`url.parse`](https://nodejs.org/docs/latest/api/url.html#url_url_parsing)'s +return value) and returns the desired proxy URL (also a string) based on +standard proxy environment variables. If no proxy is set, an empty string is +returned. + +It is your responsibility to actually proxy the request using the given URL. + +Installation: + +```sh +npm install proxy-from-env +``` + +## Example +This example shows how the data for a URL can be fetched via the +[`http` module](https://nodejs.org/api/http.html), in a proxy-aware way. + +```javascript +var http = require('http'); +var parseUrl = require('url').parse; +var getProxyForUrl = require('proxy-from-env').getProxyForUrl; + +var some_url = 'http://example.com/something'; + +// // Example, if there is a proxy server at 10.0.0.1:1234, then setting the +// // http_proxy environment variable causes the request to go through a proxy. +// process.env.http_proxy = 'http://10.0.0.1:1234'; +// +// // But if the host to be proxied is listed in NO_PROXY, then the request is +// // not proxied (but a direct request is made). +// process.env.no_proxy = 'example.com'; + +var proxy_url = getProxyForUrl(some_url); // <-- Our magic. +if (proxy_url) { + // Should be proxied through proxy_url. + var parsed_some_url = parseUrl(some_url); + var parsed_proxy_url = parseUrl(proxy_url); + // A HTTP proxy is quite simple. It is similar to a normal request, except the + // path is an absolute URL, and the proxied URL's host is put in the header + // instead of the server's actual host. + httpOptions = { + protocol: parsed_proxy_url.protocol, + hostname: parsed_proxy_url.hostname, + port: parsed_proxy_url.port, + path: parsed_some_url.href, + headers: { + Host: parsed_some_url.host, // = host name + optional port. + }, + }; +} else { + // Direct request. + httpOptions = some_url; +} +http.get(httpOptions, function(res) { + var responses = []; + res.on('data', function(chunk) { responses.push(chunk); }); + res.on('end', function() { console.log(responses.join('')); }); +}); + +``` + +## Environment variables +The environment variables can be specified in lowercase or uppercase, with the +lowercase name having precedence over the uppercase variant. A variable that is +not set has the same meaning as a variable that is set but has no value. + +### NO\_PROXY + +`NO_PROXY` is a list of host names (optionally with a port). If the input URL +matches any of the entries in `NO_PROXY`, then the input URL should be fetched +by a direct request (i.e. without a proxy). + +Matching follows the following rules: + +- `NO_PROXY=*` disables all proxies. +- Space and commas may be used to separate the entries in the `NO_PROXY` list. +- If `NO_PROXY` does not contain any entries, then proxies are never disabled. +- If a port is added after the host name, then the ports must match. If the URL + does not have an explicit port name, the protocol's default port is used. +- Generally, the proxy is only disabled if the host name is an exact match for + an entry in the `NO_PROXY` list. The only exceptions are entries that start + with a dot or with a wildcard; then the proxy is disabled if the host name + ends with the entry. + +See `test.js` for examples of what should match and what does not. + +### \*\_PROXY + +The environment variable used for the proxy depends on the protocol of the URL. +For example, `https://example.com` uses the "https" protocol, and therefore the +proxy to be used is `HTTPS_PROXY` (_NOT_ `HTTP_PROXY`, which is _only_ used for +http:-URLs). + +The library is not limited to http(s), other schemes such as +`FTP_PROXY` (ftp:), +`WSS_PROXY` (wss:), +`WS_PROXY` (ws:) +are also supported. + +If present, `ALL_PROXY` is used as fallback if there is no other match. + + +## External resources +The exact way of parsing the environment variables is not codified in any +standard. This library is designed to be compatible with formats as expected by +existing software. +The following resources were used to determine the desired behavior: + +- cURL: + https://curl.haxx.se/docs/manpage.html#ENVIRONMENT + https://github.com/curl/curl/blob/4af40b3646d3b09f68e419f7ca866ff395d1f897/lib/url.c#L4446-L4514 + https://github.com/curl/curl/blob/4af40b3646d3b09f68e419f7ca866ff395d1f897/lib/url.c#L4608-L4638 + +- wget: + https://www.gnu.org/software/wget/manual/wget.html#Proxies + http://git.savannah.gnu.org/cgit/wget.git/tree/src/init.c?id=636a5f9a1c508aa39e35a3a8e9e54520a284d93d#n383 + http://git.savannah.gnu.org/cgit/wget.git/tree/src/retr.c?id=93c1517c4071c4288ba5a4b038e7634e4c6b5482#n1278 + +- W3: + https://www.w3.org/Daemon/User/Proxies/ProxyClients.html + +- Python's urllib: + https://github.com/python/cpython/blob/936135bb97fe04223aa30ca6e98eac8f3ed6b349/Lib/urllib/request.py#L755-L782 + https://github.com/python/cpython/blob/936135bb97fe04223aa30ca6e98eac8f3ed6b349/Lib/urllib/request.py#L2444-L2479 diff --git a/node_modules/proxy-from-env/index.js b/node_modules/proxy-from-env/index.js new file mode 100644 index 0000000..df75004 --- /dev/null +++ b/node_modules/proxy-from-env/index.js @@ -0,0 +1,108 @@ +'use strict'; + +var parseUrl = require('url').parse; + +var DEFAULT_PORTS = { + ftp: 21, + gopher: 70, + http: 80, + https: 443, + ws: 80, + wss: 443, +}; + +var stringEndsWith = String.prototype.endsWith || function(s) { + return s.length <= this.length && + this.indexOf(s, this.length - s.length) !== -1; +}; + +/** + * @param {string|object} url - The URL, or the result from url.parse. + * @return {string} The URL of the proxy that should handle the request to the + * given URL. If no proxy is set, this will be an empty string. + */ +function getProxyForUrl(url) { + var parsedUrl = typeof url === 'string' ? parseUrl(url) : url || {}; + var proto = parsedUrl.protocol; + var hostname = parsedUrl.host; + var port = parsedUrl.port; + if (typeof hostname !== 'string' || !hostname || typeof proto !== 'string') { + return ''; // Don't proxy URLs without a valid scheme or host. + } + + proto = proto.split(':', 1)[0]; + // Stripping ports in this way instead of using parsedUrl.hostname to make + // sure that the brackets around IPv6 addresses are kept. + hostname = hostname.replace(/:\d*$/, ''); + port = parseInt(port) || DEFAULT_PORTS[proto] || 0; + if (!shouldProxy(hostname, port)) { + return ''; // Don't proxy URLs that match NO_PROXY. + } + + var proxy = + getEnv('npm_config_' + proto + '_proxy') || + getEnv(proto + '_proxy') || + getEnv('npm_config_proxy') || + getEnv('all_proxy'); + if (proxy && proxy.indexOf('://') === -1) { + // Missing scheme in proxy, default to the requested URL's scheme. + proxy = proto + '://' + proxy; + } + return proxy; +} + +/** + * Determines whether a given URL should be proxied. + * + * @param {string} hostname - The host name of the URL. + * @param {number} port - The effective port of the URL. + * @returns {boolean} Whether the given URL should be proxied. + * @private + */ +function shouldProxy(hostname, port) { + var NO_PROXY = + (getEnv('npm_config_no_proxy') || getEnv('no_proxy')).toLowerCase(); + if (!NO_PROXY) { + return true; // Always proxy if NO_PROXY is not set. + } + if (NO_PROXY === '*') { + return false; // Never proxy if wildcard is set. + } + + return NO_PROXY.split(/[,\s]/).every(function(proxy) { + if (!proxy) { + return true; // Skip zero-length hosts. + } + var parsedProxy = proxy.match(/^(.+):(\d+)$/); + var parsedProxyHostname = parsedProxy ? parsedProxy[1] : proxy; + var parsedProxyPort = parsedProxy ? parseInt(parsedProxy[2]) : 0; + if (parsedProxyPort && parsedProxyPort !== port) { + return true; // Skip if ports don't match. + } + + if (!/^[.*]/.test(parsedProxyHostname)) { + // No wildcards, so stop proxying if there is an exact match. + return hostname !== parsedProxyHostname; + } + + if (parsedProxyHostname.charAt(0) === '*') { + // Remove leading wildcard. + parsedProxyHostname = parsedProxyHostname.slice(1); + } + // Stop proxying if the hostname ends with the no_proxy host. + return !stringEndsWith.call(hostname, parsedProxyHostname); + }); +} + +/** + * Get the value for an environment variable. + * + * @param {string} key - The name of the environment variable. + * @return {string} The value of the environment variable. + * @private + */ +function getEnv(key) { + return process.env[key.toLowerCase()] || process.env[key.toUpperCase()] || ''; +} + +exports.getProxyForUrl = getProxyForUrl; diff --git a/node_modules/proxy-from-env/package.json b/node_modules/proxy-from-env/package.json new file mode 100644 index 0000000..be2b845 --- /dev/null +++ b/node_modules/proxy-from-env/package.json @@ -0,0 +1,34 @@ +{ + "name": "proxy-from-env", + "version": "1.1.0", + "description": "Offers getProxyForUrl to get the proxy URL for a URL, respecting the *_PROXY (e.g. HTTP_PROXY) and NO_PROXY environment variables.", + "main": "index.js", + "scripts": { + "lint": "eslint *.js", + "test": "mocha ./test.js --reporter spec", + "test-coverage": "istanbul cover ./node_modules/.bin/_mocha -- --reporter spec" + }, + "repository": { + "type": "git", + "url": "https://github.com/Rob--W/proxy-from-env.git" + }, + "keywords": [ + "proxy", + "http_proxy", + "https_proxy", + "no_proxy", + "environment" + ], + "author": "Rob Wu (https://robwu.nl/)", + "license": "MIT", + "bugs": { + "url": "https://github.com/Rob--W/proxy-from-env/issues" + }, + "homepage": "https://github.com/Rob--W/proxy-from-env#readme", + "devDependencies": { + "coveralls": "^3.0.9", + "eslint": "^6.8.0", + "istanbul": "^0.4.5", + "mocha": "^7.1.0" + } +} diff --git a/node_modules/proxy-from-env/test.js b/node_modules/proxy-from-env/test.js new file mode 100644 index 0000000..abf6542 --- /dev/null +++ b/node_modules/proxy-from-env/test.js @@ -0,0 +1,483 @@ +/* eslint max-statements:0 */ +'use strict'; + +var assert = require('assert'); +var parseUrl = require('url').parse; + +var getProxyForUrl = require('./').getProxyForUrl; + +// Runs the callback with process.env temporarily set to env. +function runWithEnv(env, callback) { + var originalEnv = process.env; + process.env = env; + try { + callback(); + } finally { + process.env = originalEnv; + } +} + +// Defines a test case that checks whether getProxyForUrl(input) === expected. +function testProxyUrl(env, expected, input) { + assert(typeof env === 'object' && env !== null); + // Copy object to make sure that the in param does not get modified between + // the call of this function and the use of it below. + env = JSON.parse(JSON.stringify(env)); + + var title = 'getProxyForUrl(' + JSON.stringify(input) + ')' + + ' === ' + JSON.stringify(expected); + + // Save call stack for later use. + var stack = {}; + Error.captureStackTrace(stack, testProxyUrl); + // Only use the last stack frame because that shows where this function is + // called, and that is sufficient for our purpose. No need to flood the logs + // with an uninteresting stack trace. + stack = stack.stack.split('\n', 2)[1]; + + it(title, function() { + var actual; + runWithEnv(env, function() { + actual = getProxyForUrl(input); + }); + if (expected === actual) { + return; // Good! + } + try { + assert.strictEqual(expected, actual); // Create a formatted error message. + // Should not happen because previously we determined expected !== actual. + throw new Error('assert.strictEqual passed. This is impossible!'); + } catch (e) { + // Use the original stack trace, so we can see a helpful line number. + e.stack = e.message + stack; + throw e; + } + }); +} + +describe('getProxyForUrl', function() { + describe('No proxy variables', function() { + var env = {}; + testProxyUrl(env, '', 'http://example.com'); + testProxyUrl(env, '', 'https://example.com'); + testProxyUrl(env, '', 'ftp://example.com'); + }); + + describe('Invalid URLs', function() { + var env = {}; + env.ALL_PROXY = 'http://unexpected.proxy'; + testProxyUrl(env, '', 'bogus'); + testProxyUrl(env, '', '//example.com'); + testProxyUrl(env, '', '://example.com'); + testProxyUrl(env, '', '://'); + testProxyUrl(env, '', '/path'); + testProxyUrl(env, '', ''); + testProxyUrl(env, '', 'http:'); + testProxyUrl(env, '', 'http:/'); + testProxyUrl(env, '', 'http://'); + testProxyUrl(env, '', 'prototype://'); + testProxyUrl(env, '', 'hasOwnProperty://'); + testProxyUrl(env, '', '__proto__://'); + testProxyUrl(env, '', undefined); + testProxyUrl(env, '', null); + testProxyUrl(env, '', {}); + testProxyUrl(env, '', {host: 'x', protocol: 1}); + testProxyUrl(env, '', {host: 1, protocol: 'x'}); + }); + + describe('http_proxy and HTTP_PROXY', function() { + var env = {}; + env.HTTP_PROXY = 'http://http-proxy'; + + testProxyUrl(env, '', 'https://example'); + testProxyUrl(env, 'http://http-proxy', 'http://example'); + testProxyUrl(env, 'http://http-proxy', parseUrl('http://example')); + + // eslint-disable-next-line camelcase + env.http_proxy = 'http://priority'; + testProxyUrl(env, 'http://priority', 'http://example'); + }); + + describe('http_proxy with non-sensical value', function() { + var env = {}; + // Crazy values should be passed as-is. It is the responsibility of the + // one who launches the application that the value makes sense. + // TODO: Should we be stricter and perform validation? + env.HTTP_PROXY = 'Crazy \n!() { ::// }'; + testProxyUrl(env, 'Crazy \n!() { ::// }', 'http://wow'); + + // The implementation assumes that the HTTP_PROXY environment variable is + // somewhat reasonable, and if the scheme is missing, it is added. + // Garbage in, garbage out some would say... + env.HTTP_PROXY = 'crazy without colon slash slash'; + testProxyUrl(env, 'http://crazy without colon slash slash', 'http://wow'); + }); + + describe('https_proxy and HTTPS_PROXY', function() { + var env = {}; + // Assert that there is no fall back to http_proxy + env.HTTP_PROXY = 'http://unexpected.proxy'; + testProxyUrl(env, '', 'https://example'); + + env.HTTPS_PROXY = 'http://https-proxy'; + testProxyUrl(env, 'http://https-proxy', 'https://example'); + + // eslint-disable-next-line camelcase + env.https_proxy = 'http://priority'; + testProxyUrl(env, 'http://priority', 'https://example'); + }); + + describe('ftp_proxy', function() { + var env = {}; + // Something else than http_proxy / https, as a sanity check. + env.FTP_PROXY = 'http://ftp-proxy'; + + testProxyUrl(env, 'http://ftp-proxy', 'ftp://example'); + testProxyUrl(env, '', 'ftps://example'); + }); + + describe('all_proxy', function() { + var env = {}; + env.ALL_PROXY = 'http://catch-all'; + testProxyUrl(env, 'http://catch-all', 'https://example'); + + // eslint-disable-next-line camelcase + env.all_proxy = 'http://priority'; + testProxyUrl(env, 'http://priority', 'https://example'); + }); + + describe('all_proxy without scheme', function() { + var env = {}; + env.ALL_PROXY = 'noscheme'; + testProxyUrl(env, 'http://noscheme', 'http://example'); + testProxyUrl(env, 'https://noscheme', 'https://example'); + + // The module does not impose restrictions on the scheme. + testProxyUrl(env, 'bogus-scheme://noscheme', 'bogus-scheme://example'); + + // But the URL should still be valid. + testProxyUrl(env, '', 'bogus'); + }); + + describe('no_proxy empty', function() { + var env = {}; + env.HTTPS_PROXY = 'http://proxy'; + + // NO_PROXY set but empty. + env.NO_PROXY = ''; + testProxyUrl(env, 'http://proxy', 'https://example'); + + // No entries in NO_PROXY (comma). + env.NO_PROXY = ','; + testProxyUrl(env, 'http://proxy', 'https://example'); + + // No entries in NO_PROXY (whitespace). + env.NO_PROXY = ' '; + testProxyUrl(env, 'http://proxy', 'https://example'); + + // No entries in NO_PROXY (multiple whitespace / commas). + env.NO_PROXY = ',\t,,,\n, ,\r'; + testProxyUrl(env, 'http://proxy', 'https://example'); + }); + + describe('no_proxy=example (single host)', function() { + var env = {}; + env.HTTP_PROXY = 'http://proxy'; + + env.NO_PROXY = 'example'; + testProxyUrl(env, '', 'http://example'); + testProxyUrl(env, '', 'http://example:80'); + testProxyUrl(env, '', 'http://example:0'); + testProxyUrl(env, '', 'http://example:1337'); + testProxyUrl(env, 'http://proxy', 'http://sub.example'); + testProxyUrl(env, 'http://proxy', 'http://prefexample'); + testProxyUrl(env, 'http://proxy', 'http://example.no'); + testProxyUrl(env, 'http://proxy', 'http://a.b.example'); + testProxyUrl(env, 'http://proxy', 'http://host/example'); + }); + + describe('no_proxy=sub.example (subdomain)', function() { + var env = {}; + env.HTTP_PROXY = 'http://proxy'; + + env.NO_PROXY = 'sub.example'; + testProxyUrl(env, 'http://proxy', 'http://example'); + testProxyUrl(env, 'http://proxy', 'http://example:80'); + testProxyUrl(env, 'http://proxy', 'http://example:0'); + testProxyUrl(env, 'http://proxy', 'http://example:1337'); + testProxyUrl(env, '', 'http://sub.example'); + testProxyUrl(env, 'http://proxy', 'http://no.sub.example'); + testProxyUrl(env, 'http://proxy', 'http://sub-example'); + testProxyUrl(env, 'http://proxy', 'http://example.sub'); + }); + + describe('no_proxy=example:80 (host + port)', function() { + var env = {}; + env.HTTP_PROXY = 'http://proxy'; + + env.NO_PROXY = 'example:80'; + testProxyUrl(env, '', 'http://example'); + testProxyUrl(env, '', 'http://example:80'); + testProxyUrl(env, '', 'http://example:0'); + testProxyUrl(env, 'http://proxy', 'http://example:1337'); + testProxyUrl(env, 'http://proxy', 'http://sub.example'); + testProxyUrl(env, 'http://proxy', 'http://prefexample'); + testProxyUrl(env, 'http://proxy', 'http://example.no'); + testProxyUrl(env, 'http://proxy', 'http://a.b.example'); + }); + + describe('no_proxy=.example (host suffix)', function() { + var env = {}; + env.HTTP_PROXY = 'http://proxy'; + + env.NO_PROXY = '.example'; + testProxyUrl(env, 'http://proxy', 'http://example'); + testProxyUrl(env, 'http://proxy', 'http://example:80'); + testProxyUrl(env, 'http://proxy', 'http://example:1337'); + testProxyUrl(env, '', 'http://sub.example'); + testProxyUrl(env, '', 'http://sub.example:80'); + testProxyUrl(env, '', 'http://sub.example:1337'); + testProxyUrl(env, 'http://proxy', 'http://prefexample'); + testProxyUrl(env, 'http://proxy', 'http://example.no'); + testProxyUrl(env, '', 'http://a.b.example'); + }); + + describe('no_proxy=*', function() { + var env = {}; + env.HTTP_PROXY = 'http://proxy'; + env.NO_PROXY = '*'; + testProxyUrl(env, '', 'http://example.com'); + }); + + describe('no_proxy=*.example (host suffix with *.)', function() { + var env = {}; + env.HTTP_PROXY = 'http://proxy'; + + env.NO_PROXY = '*.example'; + testProxyUrl(env, 'http://proxy', 'http://example'); + testProxyUrl(env, 'http://proxy', 'http://example:80'); + testProxyUrl(env, 'http://proxy', 'http://example:1337'); + testProxyUrl(env, '', 'http://sub.example'); + testProxyUrl(env, '', 'http://sub.example:80'); + testProxyUrl(env, '', 'http://sub.example:1337'); + testProxyUrl(env, 'http://proxy', 'http://prefexample'); + testProxyUrl(env, 'http://proxy', 'http://example.no'); + testProxyUrl(env, '', 'http://a.b.example'); + }); + + describe('no_proxy=*example (substring suffix)', function() { + var env = {}; + env.HTTP_PROXY = 'http://proxy'; + + env.NO_PROXY = '*example'; + testProxyUrl(env, '', 'http://example'); + testProxyUrl(env, '', 'http://example:80'); + testProxyUrl(env, '', 'http://example:1337'); + testProxyUrl(env, '', 'http://sub.example'); + testProxyUrl(env, '', 'http://sub.example:80'); + testProxyUrl(env, '', 'http://sub.example:1337'); + testProxyUrl(env, '', 'http://prefexample'); + testProxyUrl(env, '', 'http://a.b.example'); + testProxyUrl(env, 'http://proxy', 'http://example.no'); + testProxyUrl(env, 'http://proxy', 'http://host/example'); + }); + + describe('no_proxy=.*example (arbitrary wildcards are NOT supported)', + function() { + var env = {}; + env.HTTP_PROXY = 'http://proxy'; + + env.NO_PROXY = '.*example'; + testProxyUrl(env, 'http://proxy', 'http://example'); + testProxyUrl(env, 'http://proxy', 'http://sub.example'); + testProxyUrl(env, 'http://proxy', 'http://sub.example'); + testProxyUrl(env, 'http://proxy', 'http://prefexample'); + testProxyUrl(env, 'http://proxy', 'http://x.prefexample'); + testProxyUrl(env, 'http://proxy', 'http://a.b.example'); + }); + + describe('no_proxy=[::1],[::2]:80,10.0.0.1,10.0.0.2:80 (IP addresses)', + function() { + var env = {}; + env.HTTP_PROXY = 'http://proxy'; + + env.NO_PROXY = '[::1],[::2]:80,10.0.0.1,10.0.0.2:80'; + testProxyUrl(env, '', 'http://[::1]/'); + testProxyUrl(env, '', 'http://[::1]:80/'); + testProxyUrl(env, '', 'http://[::1]:1337/'); + + testProxyUrl(env, '', 'http://[::2]/'); + testProxyUrl(env, '', 'http://[::2]:80/'); + testProxyUrl(env, 'http://proxy', 'http://[::2]:1337/'); + + testProxyUrl(env, '', 'http://10.0.0.1/'); + testProxyUrl(env, '', 'http://10.0.0.1:80/'); + testProxyUrl(env, '', 'http://10.0.0.1:1337/'); + + testProxyUrl(env, '', 'http://10.0.0.2/'); + testProxyUrl(env, '', 'http://10.0.0.2:80/'); + testProxyUrl(env, 'http://proxy', 'http://10.0.0.2:1337/'); + }); + + describe('no_proxy=127.0.0.1/32 (CIDR is NOT supported)', function() { + var env = {}; + env.HTTP_PROXY = 'http://proxy'; + + env.NO_PROXY = '127.0.0.1/32'; + testProxyUrl(env, 'http://proxy', 'http://127.0.0.1'); + testProxyUrl(env, 'http://proxy', 'http://127.0.0.1/32'); + }); + + describe('no_proxy=127.0.0.1 does NOT match localhost', function() { + var env = {}; + env.HTTP_PROXY = 'http://proxy'; + + env.NO_PROXY = '127.0.0.1'; + testProxyUrl(env, '', 'http://127.0.0.1'); + // We're not performing DNS queries, so this shouldn't match. + testProxyUrl(env, 'http://proxy', 'http://localhost'); + }); + + describe('no_proxy with protocols that have a default port', function() { + var env = {}; + env.WS_PROXY = 'http://ws'; + env.WSS_PROXY = 'http://wss'; + env.HTTP_PROXY = 'http://http'; + env.HTTPS_PROXY = 'http://https'; + env.GOPHER_PROXY = 'http://gopher'; + env.FTP_PROXY = 'http://ftp'; + env.ALL_PROXY = 'http://all'; + + env.NO_PROXY = 'xxx:21,xxx:70,xxx:80,xxx:443'; + + testProxyUrl(env, '', 'http://xxx'); + testProxyUrl(env, '', 'http://xxx:80'); + testProxyUrl(env, 'http://http', 'http://xxx:1337'); + + testProxyUrl(env, '', 'ws://xxx'); + testProxyUrl(env, '', 'ws://xxx:80'); + testProxyUrl(env, 'http://ws', 'ws://xxx:1337'); + + testProxyUrl(env, '', 'https://xxx'); + testProxyUrl(env, '', 'https://xxx:443'); + testProxyUrl(env, 'http://https', 'https://xxx:1337'); + + testProxyUrl(env, '', 'wss://xxx'); + testProxyUrl(env, '', 'wss://xxx:443'); + testProxyUrl(env, 'http://wss', 'wss://xxx:1337'); + + testProxyUrl(env, '', 'gopher://xxx'); + testProxyUrl(env, '', 'gopher://xxx:70'); + testProxyUrl(env, 'http://gopher', 'gopher://xxx:1337'); + + testProxyUrl(env, '', 'ftp://xxx'); + testProxyUrl(env, '', 'ftp://xxx:21'); + testProxyUrl(env, 'http://ftp', 'ftp://xxx:1337'); + }); + + describe('no_proxy should not be case-sensitive', function() { + var env = {}; + env.HTTP_PROXY = 'http://proxy'; + env.NO_PROXY = 'XXX,YYY,ZzZ'; + + testProxyUrl(env, '', 'http://xxx'); + testProxyUrl(env, '', 'http://XXX'); + testProxyUrl(env, '', 'http://yyy'); + testProxyUrl(env, '', 'http://YYY'); + testProxyUrl(env, '', 'http://ZzZ'); + testProxyUrl(env, '', 'http://zZz'); + }); + + describe('NPM proxy configuration', function() { + describe('npm_config_http_proxy should work', function() { + var env = {}; + // eslint-disable-next-line camelcase + env.npm_config_http_proxy = 'http://http-proxy'; + + testProxyUrl(env, '', 'https://example'); + testProxyUrl(env, 'http://http-proxy', 'http://example'); + + // eslint-disable-next-line camelcase + env.npm_config_http_proxy = 'http://priority'; + testProxyUrl(env, 'http://priority', 'http://example'); + }); + // eslint-disable-next-line max-len + describe('npm_config_http_proxy should take precedence over HTTP_PROXY and npm_config_proxy', function() { + var env = {}; + // eslint-disable-next-line camelcase + env.npm_config_http_proxy = 'http://http-proxy'; + // eslint-disable-next-line camelcase + env.npm_config_proxy = 'http://unexpected-proxy'; + env.HTTP_PROXY = 'http://unexpected-proxy'; + + testProxyUrl(env, 'http://http-proxy', 'http://example'); + }); + describe('npm_config_https_proxy should work', function() { + var env = {}; + // eslint-disable-next-line camelcase + env.npm_config_http_proxy = 'http://unexpected.proxy'; + testProxyUrl(env, '', 'https://example'); + + // eslint-disable-next-line camelcase + env.npm_config_https_proxy = 'http://https-proxy'; + testProxyUrl(env, 'http://https-proxy', 'https://example'); + + // eslint-disable-next-line camelcase + env.npm_config_https_proxy = 'http://priority'; + testProxyUrl(env, 'http://priority', 'https://example'); + }); + // eslint-disable-next-line max-len + describe('npm_config_https_proxy should take precedence over HTTPS_PROXY and npm_config_proxy', function() { + var env = {}; + // eslint-disable-next-line camelcase + env.npm_config_https_proxy = 'http://https-proxy'; + // eslint-disable-next-line camelcase + env.npm_config_proxy = 'http://unexpected-proxy'; + env.HTTPS_PROXY = 'http://unexpected-proxy'; + + testProxyUrl(env, 'http://https-proxy', 'https://example'); + }); + describe('npm_config_proxy should work', function() { + var env = {}; + // eslint-disable-next-line camelcase + env.npm_config_proxy = 'http://http-proxy'; + testProxyUrl(env, 'http://http-proxy', 'http://example'); + testProxyUrl(env, 'http://http-proxy', 'https://example'); + + // eslint-disable-next-line camelcase + env.npm_config_proxy = 'http://priority'; + testProxyUrl(env, 'http://priority', 'http://example'); + testProxyUrl(env, 'http://priority', 'https://example'); + }); + // eslint-disable-next-line max-len + describe('HTTP_PROXY and HTTPS_PROXY should take precedence over npm_config_proxy', function() { + var env = {}; + env.HTTP_PROXY = 'http://http-proxy'; + env.HTTPS_PROXY = 'http://https-proxy'; + // eslint-disable-next-line camelcase + env.npm_config_proxy = 'http://unexpected-proxy'; + testProxyUrl(env, 'http://http-proxy', 'http://example'); + testProxyUrl(env, 'http://https-proxy', 'https://example'); + }); + describe('npm_config_no_proxy should work', function() { + var env = {}; + env.HTTP_PROXY = 'http://proxy'; + // eslint-disable-next-line camelcase + env.npm_config_no_proxy = 'example'; + + testProxyUrl(env, '', 'http://example'); + testProxyUrl(env, 'http://proxy', 'http://otherwebsite'); + }); + // eslint-disable-next-line max-len + describe('npm_config_no_proxy should take precedence over NO_PROXY', function() { + var env = {}; + env.HTTP_PROXY = 'http://proxy'; + env.NO_PROXY = 'otherwebsite'; + // eslint-disable-next-line camelcase + env.npm_config_no_proxy = 'example'; + + testProxyUrl(env, '', 'http://example'); + testProxyUrl(env, 'http://proxy', 'http://otherwebsite'); + }); + }); +}); diff --git a/node_modules/pump/.github/FUNDING.yml b/node_modules/pump/.github/FUNDING.yml new file mode 100644 index 0000000..f6c9139 --- /dev/null +++ b/node_modules/pump/.github/FUNDING.yml @@ -0,0 +1,2 @@ +github: mafintosh +tidelift: "npm/pump" diff --git a/node_modules/pump/.travis.yml b/node_modules/pump/.travis.yml new file mode 100644 index 0000000..17f9433 --- /dev/null +++ b/node_modules/pump/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - "0.10" + +script: "npm test" diff --git a/node_modules/pump/LICENSE b/node_modules/pump/LICENSE new file mode 100644 index 0000000..757562e --- /dev/null +++ b/node_modules/pump/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Mathias Buus + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/pump/README.md b/node_modules/pump/README.md new file mode 100644 index 0000000..5dcd8a5 --- /dev/null +++ b/node_modules/pump/README.md @@ -0,0 +1,74 @@ +# pump + +pump is a small node module that pipes streams together and destroys all of them if one of them closes. + +``` +npm install pump +``` + +[![build status](http://img.shields.io/travis/mafintosh/pump.svg?style=flat)](http://travis-ci.org/mafintosh/pump) + +## What problem does it solve? + +When using standard `source.pipe(dest)` source will _not_ be destroyed if dest emits close or an error. +You are also not able to provide a callback to tell when then pipe has finished. + +pump does these two things for you + +## Usage + +Simply pass the streams you want to pipe together to pump and add an optional callback + +``` js +var pump = require('pump') +var fs = require('fs') + +var source = fs.createReadStream('/dev/random') +var dest = fs.createWriteStream('/dev/null') + +pump(source, dest, function(err) { + console.log('pipe finished', err) +}) + +setTimeout(function() { + dest.destroy() // when dest is closed pump will destroy source +}, 1000) +``` + +You can use pump to pipe more than two streams together as well + +``` js +var transform = someTransformStream() + +pump(source, transform, anotherTransform, dest, function(err) { + console.log('pipe finished', err) +}) +``` + +If `source`, `transform`, `anotherTransform` or `dest` closes all of them will be destroyed. + +Similarly to `stream.pipe()`, `pump()` returns the last stream passed in, so you can do: + +``` +return pump(s1, s2) // returns s2 +``` + +Note that `pump` attaches error handlers to the streams to do internal error handling, so if `s2` emits an +error in the above scenario, it will not trigger a `proccess.on('uncaughtException')` if you do not listen for it. + +If you want to return a stream that combines *both* s1 and s2 to a single stream use +[pumpify](https://github.com/mafintosh/pumpify) instead. + +## License + +MIT + +## Related + +`pump` is part of the [mississippi stream utility collection](https://github.com/maxogden/mississippi) which includes more useful stream modules similar to this one. + +## For enterprise + +Available as part of the Tidelift Subscription. + +The maintainers of pump 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-pump?utm_source=npm-pump&utm_medium=referral&utm_campaign=enterprise) diff --git a/node_modules/pump/SECURITY.md b/node_modules/pump/SECURITY.md new file mode 100644 index 0000000..da9c516 --- /dev/null +++ b/node_modules/pump/SECURITY.md @@ -0,0 +1,5 @@ +## Security contact information + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure. diff --git a/node_modules/pump/empty.js b/node_modules/pump/empty.js new file mode 100644 index 0000000..7209432 --- /dev/null +++ b/node_modules/pump/empty.js @@ -0,0 +1 @@ +module.exports = null diff --git a/node_modules/pump/index.js b/node_modules/pump/index.js new file mode 100644 index 0000000..712c076 --- /dev/null +++ b/node_modules/pump/index.js @@ -0,0 +1,86 @@ +var once = require('once') +var eos = require('end-of-stream') +var fs + +try { + fs = require('fs') // we only need fs to get the ReadStream and WriteStream prototypes +} catch (e) {} + +var noop = function () {} +var ancient = typeof process === 'undefined' ? false : /^v?\.0/.test(process.version) + +var isFn = function (fn) { + return typeof fn === 'function' +} + +var isFS = function (stream) { + if (!ancient) return false // newer node version do not need to care about fs is a special way + if (!fs) return false // browser + return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close) +} + +var isRequest = function (stream) { + return stream.setHeader && isFn(stream.abort) +} + +var destroyer = function (stream, reading, writing, callback) { + callback = once(callback) + + var closed = false + stream.on('close', function () { + closed = true + }) + + eos(stream, {readable: reading, writable: writing}, function (err) { + if (err) return callback(err) + closed = true + callback() + }) + + var destroyed = false + return function (err) { + if (closed) return + if (destroyed) return + destroyed = true + + if (isFS(stream)) return stream.close(noop) // use close for fs streams to avoid fd leaks + if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want + + if (isFn(stream.destroy)) return stream.destroy() + + callback(err || new Error('stream was destroyed')) + } +} + +var call = function (fn) { + fn() +} + +var pipe = function (from, to) { + return from.pipe(to) +} + +var pump = function () { + var streams = Array.prototype.slice.call(arguments) + var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop + + if (Array.isArray(streams[0])) streams = streams[0] + if (streams.length < 2) throw new Error('pump requires two streams per minimum') + + var error + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1 + var writing = i > 0 + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err + if (err) destroys.forEach(call) + if (reading) return + destroys.forEach(call) + callback(error) + }) + }) + + return streams.reduce(pipe) +} + +module.exports = pump diff --git a/node_modules/pump/package.json b/node_modules/pump/package.json new file mode 100644 index 0000000..8d4795e --- /dev/null +++ b/node_modules/pump/package.json @@ -0,0 +1,30 @@ +{ + "name": "pump", + "version": "3.0.4", + "repository": "git://github.com/mafintosh/pump.git", + "license": "MIT", + "description": "pipe streams together and close all of them if one of them closes", + "browser": { + "fs": false + }, + "imports": { + "fs": { + "bare": "./empty.js", + "default": "fs" + } + }, + "keywords": [ + "streams", + "pipe", + "destroy", + "callback" + ], + "author": "Mathias Buus Madsen ", + "dependencies": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + }, + "scripts": { + "test": "node test-browser.js && node test-node.js" + } +} diff --git a/node_modules/pump/test-browser.js b/node_modules/pump/test-browser.js new file mode 100644 index 0000000..9a06c8a --- /dev/null +++ b/node_modules/pump/test-browser.js @@ -0,0 +1,66 @@ +var stream = require('stream') +var pump = require('./index') + +var rs = new stream.Readable() +var ws = new stream.Writable() + +rs._read = function (size) { + this.push(Buffer(size).fill('abc')) +} + +ws._write = function (chunk, encoding, cb) { + setTimeout(function () { + cb() + }, 100) +} + +var toHex = function () { + var reverse = new (require('stream').Transform)() + + reverse._transform = function (chunk, enc, callback) { + reverse.push(chunk.toString('hex')) + callback() + } + + return reverse +} + +var wsClosed = false +var rsClosed = false +var callbackCalled = false + +var check = function () { + if (wsClosed && rsClosed && callbackCalled) { + console.log('test-browser.js passes') + clearTimeout(timeout) + } +} + +ws.on('finish', function () { + wsClosed = true + check() +}) + +rs.on('end', function () { + rsClosed = true + check() +}) + +var res = pump(rs, toHex(), toHex(), toHex(), ws, function () { + callbackCalled = true + check() +}) + +if (res !== ws) { + throw new Error('should return last stream') +} + +setTimeout(function () { + rs.push(null) + rs.emit('close') +}, 1000) + +var timeout = setTimeout(function () { + check() + throw new Error('timeout') +}, 5000) diff --git a/node_modules/pump/test-node.js b/node_modules/pump/test-node.js new file mode 100644 index 0000000..561251a --- /dev/null +++ b/node_modules/pump/test-node.js @@ -0,0 +1,53 @@ +var pump = require('./index') + +var rs = require('fs').createReadStream('/dev/random') +var ws = require('fs').createWriteStream('/dev/null') + +var toHex = function () { + var reverse = new (require('stream').Transform)() + + reverse._transform = function (chunk, enc, callback) { + reverse.push(chunk.toString('hex')) + callback() + } + + return reverse +} + +var wsClosed = false +var rsClosed = false +var callbackCalled = false + +var check = function () { + if (wsClosed && rsClosed && callbackCalled) { + console.log('test-node.js passes') + clearTimeout(timeout) + } +} + +ws.on('close', function () { + wsClosed = true + check() +}) + +rs.on('close', function () { + rsClosed = true + check() +}) + +var res = pump(rs, toHex(), toHex(), toHex(), ws, function () { + callbackCalled = true + check() +}) + +if (res !== ws) { + throw new Error('should return last stream') +} + +setTimeout(function () { + rs.destroy() +}, 1000) + +var timeout = setTimeout(function () { + throw new Error('timeout') +}, 5000) diff --git a/node_modules/puppeteer-core/README.md b/node_modules/puppeteer-core/README.md new file mode 100644 index 0000000..1ec9733 --- /dev/null +++ b/node_modules/puppeteer-core/README.md @@ -0,0 +1,62 @@ +# Puppeteer + +[![build](https://github.com/puppeteer/puppeteer/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/puppeteer/puppeteer/actions/workflows/ci.yml) +[![npm puppeteer package](https://img.shields.io/npm/v/puppeteer.svg)](https://npmjs.org/package/puppeteer) + + + +> Puppeteer is a JavaScript library which provides a high-level API to control +> Chrome or Firefox over the +> [DevTools Protocol](https://chromedevtools.github.io/devtools-protocol/) or [WebDriver BiDi](https://pptr.dev/webdriver-bidi). +> Puppeteer runs in the headless (no visible UI) by default + +## [Get started](https://pptr.dev/docs) | [API](https://pptr.dev/api) | [FAQ](https://pptr.dev/faq) | [Contributing](https://pptr.dev/contributing) | [Troubleshooting](https://pptr.dev/troubleshooting) + +## Installation + +```bash npm2yarn +npm i puppeteer # Downloads compatible Chrome during installation. +npm i puppeteer-core # Alternatively, install as a library, without downloading Chrome. +``` + +## MCP + +Install [`chrome-devtools-mcp`](https://github.com/ChromeDevTools/chrome-devtools-mcp), +a Puppeteer-based MCP server for browser automation and debugging. + +## Example + +```ts +import puppeteer from 'puppeteer'; +// Or import puppeteer from 'puppeteer-core'; + +// Launch the browser and open a new blank page. +const browser = await puppeteer.launch(); +const page = await browser.newPage(); + +// Navigate the page to a URL. +await page.goto('https://developer.chrome.com/'); + +// Set screen size. +await page.setViewport({width: 1080, height: 1024}); + +// Open the search menu using the keyboard. +await page.keyboard.press('/'); + +// Type into search box using accessible input name. +await page.locator('::-p-aria(Search)').fill('automate beyond recorder'); + +// Wait and click on first result. +await page.locator('.devsite-result-item-link').click(); + +// Locate the full title with a unique string. +const textSelector = await page + .locator('::-p-text(Customize and automate)') + .waitHandle(); +const fullTitle = await textSelector?.evaluate(el => el.textContent); + +// Print the full title. +console.log('The title of this blog post is "%s".', fullTitle); + +await browser.close(); +``` diff --git a/node_modules/puppeteer-core/lib/cjs/puppeteer/api/BluetoothEmulation.d.ts b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/BluetoothEmulation.d.ts new file mode 100644 index 0000000..a29a3e3 --- /dev/null +++ b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/BluetoothEmulation.d.ts @@ -0,0 +1,96 @@ +/** + * @license + * Copyright 2025 Google Inc. + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * @public + * Emulated bluetooth adapter state. + */ +export type AdapterState = 'absent' | 'powered-off' | 'powered-on'; +/** + * @public + * Represents the simulated bluetooth peripheral's manufacturer data. + */ +export interface BluetoothManufacturerData { + /** + * The company identifier, as defined by the {@link https://www.bluetooth.com/specifications/assigned-numbers/company-identifiers/|Bluetooth SIG}. + */ + key: number; + /** + * The manufacturer-specific data as a base64-encoded string. + */ + data: string; +} +/** + * @public + * A bluetooth peripheral to be simulated. + */ +export interface PreconnectedPeripheral { + address: string; + name: string; + manufacturerData: BluetoothManufacturerData[]; + knownServiceUuids: string[]; +} +/** + * Exposes the bluetooth emulation abilities. + * + * @remarks {@link https://webbluetoothcg.github.io/web-bluetooth/#simulated-bluetooth-adapter|Web Bluetooth specification} + * requires the emulated adapters should be isolated per top-level navigable. However, + * at the moment Chromium's bluetooth emulation implementation is tight to the browser + * context, not the page. This means the bluetooth emulation exposed from different pages + * of the same browser context would interfere their states. + * + * @example + * + * ```ts + * await page.bluetooth.emulateAdapter('powered-on'); + * await page.bluetooth.simulatePreconnectedPeripheral({ + * address: '09:09:09:09:09:09', + * name: 'SOME_NAME', + * manufacturerData: [ + * { + * key: 17, + * data: 'AP8BAX8=', + * }, + * ], + * knownServiceUuids: ['12345678-1234-5678-9abc-def123456789'], + * }); + * await page.bluetooth.disableEmulation(); + * ``` + * + * @experimental + * @public + */ +export interface BluetoothEmulation { + /** + * Emulate Bluetooth adapter. Required for bluetooth simulations + * See {@link https://webbluetoothcg.github.io/web-bluetooth/#bluetooth-simulateAdapter-command|bluetooth.simulateAdapter}. + * + * @param state - The desired bluetooth adapter state. + * @param leSupported - Mark if the adapter supports low-energy bluetooth. + * + * @experimental + * @public + */ + emulateAdapter(state: AdapterState, leSupported?: boolean): Promise; + /** + * Disable emulated bluetooth adapter. + * See {@link https://webbluetoothcg.github.io/web-bluetooth/#bluetooth-disableSimulation-command|bluetooth.disableSimulation}. + * + * @experimental + * @public + */ + disableEmulation(): Promise; + /** + * Simulated preconnected Bluetooth Peripheral. + * See {@link https://webbluetoothcg.github.io/web-bluetooth/#bluetooth-simulateconnectedperipheral-command|bluetooth.simulatePreconnectedPeripheral}. + * + * @param preconnectedPeripheral - The peripheral to simulate. + * + * @experimental + * @public + */ + simulatePreconnectedPeripheral(preconnectedPeripheral: PreconnectedPeripheral): Promise; +} +//# sourceMappingURL=BluetoothEmulation.d.ts.map \ No newline at end of file diff --git a/node_modules/puppeteer-core/lib/cjs/puppeteer/api/BluetoothEmulation.d.ts.map b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/BluetoothEmulation.d.ts.map new file mode 100644 index 0000000..ee896a7 --- /dev/null +++ b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/BluetoothEmulation.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"BluetoothEmulation.d.ts","sourceRoot":"","sources":["../../../../src/api/BluetoothEmulation.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH;;;GAGG;AACH,MAAM,MAAM,YAAY,GAAG,QAAQ,GAAG,aAAa,GAAG,YAAY,CAAC;AAEnE;;;GAGG;AACH,MAAM,WAAW,yBAAyB;IACxC;;OAEG;IACH,GAAG,EAAE,MAAM,CAAC;IACZ;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;CACd;AAED;;;GAGG;AACH,MAAM,WAAW,sBAAsB;IACrC,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,CAAC;IACb,gBAAgB,EAAE,yBAAyB,EAAE,CAAC;IAC9C,iBAAiB,EAAE,MAAM,EAAE,CAAC;CAC7B;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,MAAM,WAAW,kBAAkB;IACjC;;;;;;;;;OASG;IACH,cAAc,CAAC,KAAK,EAAE,YAAY,EAAE,WAAW,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAE1E;;;;;;OAMG;IACH,gBAAgB,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAElC;;;;;;;;OAQG;IACH,8BAA8B,CAC5B,sBAAsB,EAAE,sBAAsB,GAC7C,OAAO,CAAC,IAAI,CAAC,CAAC;CAClB"} \ No newline at end of file diff --git a/node_modules/puppeteer-core/lib/cjs/puppeteer/api/BluetoothEmulation.js b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/BluetoothEmulation.js new file mode 100644 index 0000000..598d289 --- /dev/null +++ b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/BluetoothEmulation.js @@ -0,0 +1,8 @@ +"use strict"; +/** + * @license + * Copyright 2025 Google Inc. + * SPDX-License-Identifier: Apache-2.0 + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=BluetoothEmulation.js.map \ No newline at end of file diff --git a/node_modules/puppeteer-core/lib/cjs/puppeteer/api/BluetoothEmulation.js.map b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/BluetoothEmulation.js.map new file mode 100644 index 0000000..3ce338e --- /dev/null +++ b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/BluetoothEmulation.js.map @@ -0,0 +1 @@ +{"version":3,"file":"BluetoothEmulation.js","sourceRoot":"","sources":["../../../../src/api/BluetoothEmulation.ts"],"names":[],"mappings":";AAAA;;;;GAIG"} \ No newline at end of file diff --git a/node_modules/puppeteer-core/lib/cjs/puppeteer/api/Browser.d.ts b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/Browser.d.ts new file mode 100644 index 0000000..1ba4678 --- /dev/null +++ b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/Browser.d.ts @@ -0,0 +1,549 @@ +/// +/** + * @license + * Copyright 2017 Google Inc. + * SPDX-License-Identifier: Apache-2.0 + */ +import type { ChildProcess } from 'node:child_process'; +import type { Protocol } from 'devtools-protocol'; +import type { ProtocolType } from '../common/ConnectOptions.js'; +import type { Cookie, CookieData, DeleteCookiesRequest } from '../common/Cookie.js'; +import type { DownloadBehavior } from '../common/DownloadBehavior.js'; +import { EventEmitter, type EventType } from '../common/EventEmitter.js'; +import { asyncDisposeSymbol, disposeSymbol } from '../util/disposable.js'; +import type { BrowserContext } from './BrowserContext.js'; +import type { Page } from './Page.js'; +import type { Target } from './Target.js'; +/** + * @public + */ +export interface BrowserContextOptions { + /** + * Proxy server with optional port to use for all requests. + * Username and password can be set in `Page.authenticate`. + */ + proxyServer?: string; + /** + * Bypass the proxy for the given list of hosts. + */ + proxyBypassList?: string[]; + /** + * Behavior definition for when downloading a file. + * + * @remarks + * If not set, the default behavior will be used. + */ + downloadBehavior?: DownloadBehavior; +} +/** + * @internal + */ +export type BrowserCloseCallback = () => Promise | void; +/** + * @public + */ +export type TargetFilterCallback = (target: Target) => boolean; +/** + * @internal + */ +export type IsPageTargetCallback = (target: Target) => boolean; +/** + * @internal + */ +export declare const WEB_PERMISSION_TO_PROTOCOL_PERMISSION: Map; +/** + * @public + * @deprecated in favor of {@link PermissionDescriptor}. + */ +export type Permission = 'accelerometer' | 'ambient-light-sensor' | 'background-sync' | 'camera' | 'clipboard-read' | 'clipboard-sanitized-write' | 'clipboard-write' | 'geolocation' | 'gyroscope' | 'idle-detection' | 'keyboard-lock' | 'magnetometer' | 'microphone' | 'midi-sysex' | 'midi' | 'notifications' | 'payment-handler' | 'persistent-storage' | 'pointer-lock'; +/** + * @public + */ +export interface PermissionDescriptor { + name: string; + userVisibleOnly?: boolean; + sysex?: boolean; + panTiltZoom?: boolean; + allowWithoutSanitization?: boolean; +} +/** + * @public + */ +export type PermissionState = 'granted' | 'denied' | 'prompt'; +/** + * @public + */ +export interface WaitForTargetOptions { + /** + * Maximum wait time in milliseconds. Pass `0` to disable the timeout. + * + * @defaultValue `30_000` + */ + timeout?: number; + /** + * A signal object that allows you to cancel a waitFor call. + */ + signal?: AbortSignal; +} +/** + * All the events a {@link Browser | browser instance} may emit. + * + * @public + */ +export declare const enum BrowserEvent { + /** + * Emitted when Puppeteer gets disconnected from the browser instance. This + * might happen because either: + * + * - The browser closes/crashes or + * - {@link Browser.disconnect} was called. + */ + Disconnected = "disconnected", + /** + * Emitted when the URL of a target changes. Contains a {@link Target} + * instance. + * + * @remarks Note that this includes target changes in all browser + * contexts. + */ + TargetChanged = "targetchanged", + /** + * Emitted when a target is created, for example when a new page is opened by + * {@link https://developer.mozilla.org/en-US/docs/Web/API/Window/open | window.open} + * or by {@link Browser.newPage | browser.newPage} + * + * Contains a {@link Target} instance. + * + * @remarks Note that this includes target creations in all browser + * contexts. + */ + TargetCreated = "targetcreated", + /** + * Emitted when a target is destroyed, for example when a page is closed. + * Contains a {@link Target} instance. + * + * @remarks Note that this includes target destructions in all browser + * contexts. + */ + TargetDestroyed = "targetdestroyed", + /** + * @internal + */ + TargetDiscovered = "targetdiscovered" +} +/** + * @public + */ +export interface BrowserEvents extends Record { + [BrowserEvent.Disconnected]: undefined; + [BrowserEvent.TargetCreated]: Target; + [BrowserEvent.TargetDestroyed]: Target; + [BrowserEvent.TargetChanged]: Target; + /** + * @internal + */ + [BrowserEvent.TargetDiscovered]: Protocol.Target.TargetInfo; +} +/** + * @public + * @experimental + */ +export interface DebugInfo { + pendingProtocolErrors: Error[]; +} +/** + * @public + */ +export type WindowState = 'normal' | 'minimized' | 'maximized' | 'fullscreen'; +/** + * @public + */ +export interface WindowBounds { + left?: number; + top?: number; + width?: number; + height?: number; + windowState?: WindowState; +} +/** + * @public + */ +export type WindowId = string; +/** + * @public + */ +export type CreatePageOptions = ({ + type?: 'tab'; +} | { + type: 'window'; + windowBounds?: WindowBounds; +}) & { + /** + * Whether to create the page in the background. + * + * @defaultValue `false` + */ + background?: boolean; +}; +/** + * @public + */ +export interface ScreenOrientation { + angle: number; + type: string; +} +/** + * @public + */ +export interface ScreenInfo { + left: number; + top: number; + width: number; + height: number; + availLeft: number; + availTop: number; + availWidth: number; + availHeight: number; + devicePixelRatio: number; + colorDepth: number; + orientation: ScreenOrientation; + isExtended: boolean; + isInternal: boolean; + isPrimary: boolean; + label: string; + id: string; +} +/** + * @public + */ +export interface WorkAreaInsets { + top?: number; + left?: number; + bottom?: number; + right?: number; +} +/** + * @public + */ +export interface AddScreenParams { + left: number; + top: number; + width: number; + height: number; + workAreaInsets?: WorkAreaInsets; + devicePixelRatio?: number; + rotation?: number; + colorDepth?: number; + label?: string; + isInternal?: boolean; +} +/** + * {@link Browser} represents a browser instance that is either: + * + * - connected to via {@link Puppeteer.connect} or + * - launched by {@link PuppeteerNode.launch}. + * + * {@link Browser} {@link EventEmitter.emit | emits} various events which are + * documented in the {@link BrowserEvent} enum. + * + * @example Using a {@link Browser} to create a {@link Page}: + * + * ```ts + * import puppeteer from 'puppeteer'; + * + * const browser = await puppeteer.launch(); + * const page = await browser.newPage(); + * await page.goto('https://example.com'); + * await browser.close(); + * ``` + * + * @example Disconnecting from and reconnecting to a {@link Browser}: + * + * ```ts + * import puppeteer from 'puppeteer'; + * + * const browser = await puppeteer.launch(); + * // Store the endpoint to be able to reconnect to the browser. + * const browserWSEndpoint = browser.wsEndpoint(); + * // Disconnect puppeteer from the browser. + * await browser.disconnect(); + * + * // Use the endpoint to reestablish a connection + * const browser2 = await puppeteer.connect({browserWSEndpoint}); + * // Close the browser. + * await browser2.close(); + * ``` + * + * @public + */ +export declare abstract class Browser extends EventEmitter { + /** + * @internal + */ + constructor(); + /** + * Gets the associated + * {@link https://nodejs.org/api/child_process.html#class-childprocess | ChildProcess}. + * + * @returns `null` if this instance was connected to via + * {@link Puppeteer.connect}. + */ + abstract process(): ChildProcess | null; + /** + * Creates a new {@link BrowserContext | browser context}. + * + * This won't share cookies/cache with other {@link BrowserContext | browser contexts}. + * + * @example + * + * ```ts + * import puppeteer from 'puppeteer'; + * + * const browser = await puppeteer.launch(); + * // Create a new browser context. + * const context = await browser.createBrowserContext(); + * // Create a new page in a pristine context. + * const page = await context.newPage(); + * // Do stuff + * await page.goto('https://example.com'); + * ``` + */ + abstract createBrowserContext(options?: BrowserContextOptions): Promise; + /** + * Gets a list of open {@link BrowserContext | browser contexts}. + * + * In a newly-created {@link Browser | browser}, this will return a single + * instance of {@link BrowserContext}. + */ + abstract browserContexts(): BrowserContext[]; + /** + * Gets the default {@link BrowserContext | browser context}. + * + * @remarks The default {@link BrowserContext | browser context} cannot be + * closed. + */ + abstract defaultBrowserContext(): BrowserContext; + /** + * Gets the WebSocket URL to connect to this {@link Browser | browser}. + * + * This is usually used with {@link Puppeteer.connect}. + * + * You can find the debugger URL (`webSocketDebuggerUrl`) from + * `http://HOST:PORT/json/version`. + * + * See {@link https://chromedevtools.github.io/devtools-protocol/#how-do-i-access-the-browser-target | browser endpoint} + * for more information. + * + * @remarks The format is always `ws://HOST:PORT/devtools/browser/`. + */ + abstract wsEndpoint(): string; + /** + * Creates a new {@link Page | page} in the + * {@link Browser.defaultBrowserContext | default browser context}. + */ + abstract newPage(options?: CreatePageOptions): Promise; + /** + * Gets the specified window {@link WindowBounds | bounds}. + */ + abstract getWindowBounds(windowId: WindowId): Promise; + /** + * Sets the specified window {@link WindowBounds | bounds}. + */ + abstract setWindowBounds(windowId: WindowId, windowBounds: WindowBounds): Promise; + /** + * Gets all active {@link Target | targets}. + * + * In case of multiple {@link BrowserContext | browser contexts}, this returns + * all {@link Target | targets} in all + * {@link BrowserContext | browser contexts}. + */ + abstract targets(): Target[]; + /** + * Gets the {@link Target | target} associated with the + * {@link Browser.defaultBrowserContext | default browser context}). + */ + abstract target(): Target; + /** + * Waits until a {@link Target | target} matching the given `predicate` + * appears and returns it. + * + * This will look all open {@link BrowserContext | browser contexts}. + * + * @example Finding a target for a page opened via `window.open`: + * + * ```ts + * await page.evaluate(() => window.open('https://www.example.com/')); + * const newWindowTarget = await browser.waitForTarget( + * target => target.url() === 'https://www.example.com/', + * ); + * ``` + */ + waitForTarget(predicate: (x: Target) => boolean | Promise, options?: WaitForTargetOptions): Promise; + /** + * Gets a list of all open {@link Page | pages} inside this {@link Browser}. + * + * If there are multiple {@link BrowserContext | browser contexts}, this + * returns all {@link Page | pages} in all + * {@link BrowserContext | browser contexts}. + * + * @param includeAll - experimental, setting to true includes all kinds of pages. + * + * @remarks Non-visible {@link Page | pages}, such as `"background_page"`, + * will not be listed here. You can find them using {@link Target.page}. + */ + pages(includeAll?: boolean): Promise; + /** + * Gets a string representing this {@link Browser | browser's} name and + * version. + * + * For headless browser, this is similar to `"HeadlessChrome/61.0.3153.0"`. For + * non-headless or new-headless, this is similar to `"Chrome/61.0.3153.0"`. For + * Firefox, it is similar to `"Firefox/116.0a1"`. + * + * The format of {@link Browser.version} might change with future releases of + * browsers. + */ + abstract version(): Promise; + /** + * Gets this {@link Browser | browser's} original user agent. + * + * {@link Page | Pages} can override the user agent with + * {@link Page.(setUserAgent:2) }. + * + */ + abstract userAgent(): Promise; + /** + * Closes this {@link Browser | browser} and all associated + * {@link Page | pages}. + */ + abstract close(): Promise; + /** + * Disconnects Puppeteer from this {@link Browser | browser}, but leaves the + * process running. + */ + abstract disconnect(): Promise; + /** + * Returns all cookies in the default {@link BrowserContext}. + * + * @remarks + * + * Shortcut for + * {@link BrowserContext.cookies | browser.defaultBrowserContext().cookies()}. + */ + cookies(): Promise; + /** + * Sets cookies in the default {@link BrowserContext}. + * + * @remarks + * + * Shortcut for + * {@link BrowserContext.setCookie | browser.defaultBrowserContext().setCookie()}. + */ + setCookie(...cookies: CookieData[]): Promise; + /** + * Removes cookies from the default {@link BrowserContext}. + * + * @remarks + * + * Shortcut for + * {@link BrowserContext.deleteCookie | browser.defaultBrowserContext().deleteCookie()}. + */ + deleteCookie(...cookies: Cookie[]): Promise; + /** + * Deletes cookies matching the provided filters from the default + * {@link BrowserContext}. + * + * @remarks + * + * Shortcut for + * {@link BrowserContext.deleteMatchingCookies | + * browser.defaultBrowserContext().deleteMatchingCookies()}. + */ + deleteMatchingCookies(...filters: DeleteCookiesRequest[]): Promise; + /** + * Sets the permission for a specific origin in the default + * {@link BrowserContext}. + * + * @remarks + * + * Shortcut for + * {@link BrowserContext.setPermission | + * browser.defaultBrowserContext().setPermission()}. + * + * @param origin - The origin to set the permission for. + * @param permission - The permission descriptor. + * @param state - The state of the permission. + * + * @public + */ + setPermission(origin: string, ...permissions: Array<{ + permission: PermissionDescriptor; + state: PermissionState; + }>): Promise; + /** + * Installs an extension and returns the ID. In Chrome, this is only + * available if the browser was created using `pipe: true` and the + * `--enable-unsafe-extension-debugging` flag is set. + */ + abstract installExtension(path: string): Promise; + /** + * Uninstalls an extension. In Chrome, this is only available if the browser + * was created using `pipe: true` and the + * `--enable-unsafe-extension-debugging` flag is set. + */ + abstract uninstallExtension(id: string): Promise; + /** + * Gets a list of {@link ScreenInfo | screen information objects}. + */ + abstract screens(): Promise; + /** + * Adds a new screen, returns the added {@link ScreenInfo | screen information object}. + * + * @remarks + * + * Only supported in headless mode. + */ + abstract addScreen(params: AddScreenParams): Promise; + /** + * Removes a screen. + * + * @remarks + * + * Only supported in headless mode. Fails if the primary screen id is specified. + */ + abstract removeScreen(screenId: string): Promise; + /** + * Whether Puppeteer is connected to this {@link Browser | browser}. + * + * @deprecated Use {@link Browser | Browser.connected}. + */ + isConnected(): boolean; + /** + * Whether Puppeteer is connected to this {@link Browser | browser}. + */ + abstract get connected(): boolean; + /** @internal */ + [disposeSymbol](): void; + /** @internal */ + [asyncDisposeSymbol](): Promise; + /** + * @internal + */ + abstract get protocol(): ProtocolType; + /** + * Get debug information from Puppeteer. + * + * @remarks + * + * Currently, includes pending protocol calls. In the future, we might add more info. + * + * @public + * @experimental + */ + abstract get debugInfo(): DebugInfo; + /** + * @internal + */ + abstract isNetworkEnabled(): boolean; +} +//# sourceMappingURL=Browser.d.ts.map \ No newline at end of file diff --git a/node_modules/puppeteer-core/lib/cjs/puppeteer/api/Browser.d.ts.map b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/Browser.d.ts.map new file mode 100644 index 0000000..2c809c1 --- /dev/null +++ b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/Browser.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Browser.d.ts","sourceRoot":"","sources":["../../../../src/api/Browser.ts"],"names":[],"mappings":";AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAC,YAAY,EAAC,MAAM,oBAAoB,CAAC;AAErD,OAAO,KAAK,EAAC,QAAQ,EAAC,MAAM,mBAAmB,CAAC;AAQhD,OAAO,KAAK,EAAC,YAAY,EAAC,MAAM,6BAA6B,CAAC;AAC9D,OAAO,KAAK,EACV,MAAM,EACN,UAAU,EACV,oBAAoB,EACrB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,KAAK,EAAC,gBAAgB,EAAC,MAAM,+BAA+B,CAAC;AACpE,OAAO,EAAC,YAAY,EAAE,KAAK,SAAS,EAAC,MAAM,2BAA2B,CAAC;AAQvE,OAAO,EAAC,kBAAkB,EAAE,aAAa,EAAC,MAAM,uBAAuB,CAAC;AAExE,OAAO,KAAK,EAAC,cAAc,EAAC,MAAM,qBAAqB,CAAC;AACxD,OAAO,KAAK,EAAC,IAAI,EAAC,MAAM,WAAW,CAAC;AACpC,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,aAAa,CAAC;AACxC;;GAEG;AACH,MAAM,WAAW,qBAAqB;IACpC;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;OAEG;IACH,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;IAC3B;;;;;OAKG;IACH,gBAAgB,CAAC,EAAE,gBAAgB,CAAC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SAAS,IAAI,OAAO,CAAC;IAElC,gBAAgB;IACP,CAAC,aAAa,CAAC,IAAI,IAAI;IAOhC,gBAAgB;IAChB,CAAC,kBAAkB,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC;IAOrC;;OAEG;IACH,QAAQ,KAAK,QAAQ,IAAI,YAAY,CAAC;IAEtC;;;;;;;;;OASG;IACH,QAAQ,KAAK,SAAS,IAAI,SAAS,CAAC;IAEpC;;OAEG;IACH,QAAQ,CAAC,gBAAgB,IAAI,OAAO;CACrC"} \ No newline at end of file diff --git a/node_modules/puppeteer-core/lib/cjs/puppeteer/api/Browser.js b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/Browser.js new file mode 100644 index 0000000..7467ccc --- /dev/null +++ b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/Browser.js @@ -0,0 +1,208 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Browser = exports.WEB_PERMISSION_TO_PROTOCOL_PERMISSION = void 0; +const rxjs_js_1 = require("../../third_party/rxjs/rxjs.js"); +const EventEmitter_js_1 = require("../common/EventEmitter.js"); +const util_js_1 = require("../common/util.js"); +const disposable_js_1 = require("../util/disposable.js"); +/** + * @internal + */ +exports.WEB_PERMISSION_TO_PROTOCOL_PERMISSION = new Map([ + ['accelerometer', 'sensors'], + ['ambient-light-sensor', 'sensors'], + ['background-sync', 'backgroundSync'], + ['camera', 'videoCapture'], + ['clipboard-read', 'clipboardReadWrite'], + ['clipboard-sanitized-write', 'clipboardSanitizedWrite'], + ['clipboard-write', 'clipboardReadWrite'], + ['geolocation', 'geolocation'], + ['gyroscope', 'sensors'], + ['idle-detection', 'idleDetection'], + ['keyboard-lock', 'keyboardLock'], + ['magnetometer', 'sensors'], + ['microphone', 'audioCapture'], + ['midi', 'midi'], + ['notifications', 'notifications'], + ['payment-handler', 'paymentHandler'], + ['persistent-storage', 'durableStorage'], + ['pointer-lock', 'pointerLock'], + // chrome-specific permissions we have. + ['midi-sysex', 'midiSysex'], +]); +/** + * {@link Browser} represents a browser instance that is either: + * + * - connected to via {@link Puppeteer.connect} or + * - launched by {@link PuppeteerNode.launch}. + * + * {@link Browser} {@link EventEmitter.emit | emits} various events which are + * documented in the {@link BrowserEvent} enum. + * + * @example Using a {@link Browser} to create a {@link Page}: + * + * ```ts + * import puppeteer from 'puppeteer'; + * + * const browser = await puppeteer.launch(); + * const page = await browser.newPage(); + * await page.goto('https://example.com'); + * await browser.close(); + * ``` + * + * @example Disconnecting from and reconnecting to a {@link Browser}: + * + * ```ts + * import puppeteer from 'puppeteer'; + * + * const browser = await puppeteer.launch(); + * // Store the endpoint to be able to reconnect to the browser. + * const browserWSEndpoint = browser.wsEndpoint(); + * // Disconnect puppeteer from the browser. + * await browser.disconnect(); + * + * // Use the endpoint to reestablish a connection + * const browser2 = await puppeteer.connect({browserWSEndpoint}); + * // Close the browser. + * await browser2.close(); + * ``` + * + * @public + */ +class Browser extends EventEmitter_js_1.EventEmitter { + /** + * @internal + */ + constructor() { + super(); + } + /** + * Waits until a {@link Target | target} matching the given `predicate` + * appears and returns it. + * + * This will look all open {@link BrowserContext | browser contexts}. + * + * @example Finding a target for a page opened via `window.open`: + * + * ```ts + * await page.evaluate(() => window.open('https://www.example.com/')); + * const newWindowTarget = await browser.waitForTarget( + * target => target.url() === 'https://www.example.com/', + * ); + * ``` + */ + async waitForTarget(predicate, options = {}) { + const { timeout: ms = 30000, signal } = options; + return await (0, rxjs_js_1.firstValueFrom)((0, rxjs_js_1.merge)((0, util_js_1.fromEmitterEvent)(this, "targetcreated" /* BrowserEvent.TargetCreated */), (0, util_js_1.fromEmitterEvent)(this, "targetchanged" /* BrowserEvent.TargetChanged */), (0, rxjs_js_1.from)(this.targets())).pipe((0, util_js_1.filterAsync)(predicate), (0, rxjs_js_1.raceWith)((0, util_js_1.fromAbortSignal)(signal), (0, util_js_1.timeout)(ms)))); + } + /** + * Gets a list of all open {@link Page | pages} inside this {@link Browser}. + * + * If there are multiple {@link BrowserContext | browser contexts}, this + * returns all {@link Page | pages} in all + * {@link BrowserContext | browser contexts}. + * + * @param includeAll - experimental, setting to true includes all kinds of pages. + * + * @remarks Non-visible {@link Page | pages}, such as `"background_page"`, + * will not be listed here. You can find them using {@link Target.page}. + */ + async pages(includeAll = false) { + const contextPages = await Promise.all(this.browserContexts().map(context => { + return context.pages(includeAll); + })); + // Flatten array. + return contextPages.reduce((acc, x) => { + return acc.concat(x); + }, []); + } + /** + * Returns all cookies in the default {@link BrowserContext}. + * + * @remarks + * + * Shortcut for + * {@link BrowserContext.cookies | browser.defaultBrowserContext().cookies()}. + */ + async cookies() { + return await this.defaultBrowserContext().cookies(); + } + /** + * Sets cookies in the default {@link BrowserContext}. + * + * @remarks + * + * Shortcut for + * {@link BrowserContext.setCookie | browser.defaultBrowserContext().setCookie()}. + */ + async setCookie(...cookies) { + return await this.defaultBrowserContext().setCookie(...cookies); + } + /** + * Removes cookies from the default {@link BrowserContext}. + * + * @remarks + * + * Shortcut for + * {@link BrowserContext.deleteCookie | browser.defaultBrowserContext().deleteCookie()}. + */ + async deleteCookie(...cookies) { + return await this.defaultBrowserContext().deleteCookie(...cookies); + } + /** + * Deletes cookies matching the provided filters from the default + * {@link BrowserContext}. + * + * @remarks + * + * Shortcut for + * {@link BrowserContext.deleteMatchingCookies | + * browser.defaultBrowserContext().deleteMatchingCookies()}. + */ + async deleteMatchingCookies(...filters) { + return await this.defaultBrowserContext().deleteMatchingCookies(...filters); + } + /** + * Sets the permission for a specific origin in the default + * {@link BrowserContext}. + * + * @remarks + * + * Shortcut for + * {@link BrowserContext.setPermission | + * browser.defaultBrowserContext().setPermission()}. + * + * @param origin - The origin to set the permission for. + * @param permission - The permission descriptor. + * @param state - The state of the permission. + * + * @public + */ + async setPermission(origin, ...permissions) { + return await this.defaultBrowserContext().setPermission(origin, ...permissions); + } + /** + * Whether Puppeteer is connected to this {@link Browser | browser}. + * + * @deprecated Use {@link Browser | Browser.connected}. + */ + isConnected() { + return this.connected; + } + /** @internal */ + [disposable_js_1.disposeSymbol]() { + if (this.process()) { + return void this.close().catch(util_js_1.debugError); + } + return void this.disconnect().catch(util_js_1.debugError); + } + /** @internal */ + [disposable_js_1.asyncDisposeSymbol]() { + if (this.process()) { + return this.close(); + } + return this.disconnect(); + } +} +exports.Browser = Browser; +//# sourceMappingURL=Browser.js.map \ No newline at end of file diff --git a/node_modules/puppeteer-core/lib/cjs/puppeteer/api/Browser.js.map b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/Browser.js.map new file mode 100644 index 0000000..9a169da --- /dev/null +++ b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/Browser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Browser.js","sourceRoot":"","sources":["../../../../src/api/Browser.ts"],"names":[],"mappings":";;;AAUA,4DAKwC;AAQxC,+DAAuE;AACvE,+CAM2B;AAC3B,yDAAwE;AA0CxE;;GAEG;AACU,QAAA,qCAAqC,GAAG,IAAI,GAAG,CAG1D;IACA,CAAC,eAAe,EAAE,SAAS,CAAC;IAC5B,CAAC,sBAAsB,EAAE,SAAS,CAAC;IACnC,CAAC,iBAAiB,EAAE,gBAAgB,CAAC;IACrC,CAAC,QAAQ,EAAE,cAAc,CAAC;IAC1B,CAAC,gBAAgB,EAAE,oBAAoB,CAAC;IACxC,CAAC,2BAA2B,EAAE,yBAAyB,CAAC;IACxD,CAAC,iBAAiB,EAAE,oBAAoB,CAAC;IACzC,CAAC,aAAa,EAAE,aAAa,CAAC;IAC9B,CAAC,WAAW,EAAE,SAAS,CAAC;IACxB,CAAC,gBAAgB,EAAE,eAAe,CAAC;IACnC,CAAC,eAAe,EAAE,cAAc,CAAC;IACjC,CAAC,cAAc,EAAE,SAAS,CAAC;IAC3B,CAAC,YAAY,EAAE,cAAc,CAAC;IAC9B,CAAC,MAAM,EAAE,MAAM,CAAC;IAChB,CAAC,eAAe,EAAE,eAAe,CAAC;IAClC,CAAC,iBAAiB,EAAE,gBAAgB,CAAC;IACrC,CAAC,oBAAo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AI,CAAC,OAAO,EAAE,EAAE,CAAC;YACnB,OAAO,IAAI,CAAC,KAAK,EAAE,CAAC;QACtB,CAAC;QACD,OAAO,IAAI,CAAC,UAAU,EAAE,CAAC;IAC3B,CAAC;CAuBF;AA5WD,0BA4WC"} \ No newline at end of file diff --git a/node_modules/puppeteer-core/lib/cjs/puppeteer/api/BrowserContext.d.ts b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/BrowserContext.d.ts new file mode 100644 index 0000000..b593337 --- /dev/null +++ b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/BrowserContext.d.ts @@ -0,0 +1,230 @@ +/** + * @license + * Copyright 2017 Google Inc. + * SPDX-License-Identifier: Apache-2.0 + */ +import type { Cookie, CookieData, DeleteCookiesRequest } from '../common/Cookie.js'; +import { EventEmitter, type EventType } from '../common/EventEmitter.js'; +import { asyncDisposeSymbol, disposeSymbol } from '../util/disposable.js'; +import { Mutex } from '../util/Mutex.js'; +import type { Browser, CreatePageOptions, Permission, PermissionDescriptor, PermissionState, WaitForTargetOptions } from './Browser.js'; +import type { Page } from './Page.js'; +import type { Target } from './Target.js'; +/** + * @public + */ +export declare const enum BrowserContextEvent { + /** + * Emitted when the url of a target inside the browser context changes. + * Contains a {@link Target} instance. + */ + TargetChanged = "targetchanged", + /** + * Emitted when a target is created within the browser context, for example + * when a new page is opened by + * {@link https://developer.mozilla.org/en-US/docs/Web/API/Window/open | window.open} + * or by {@link BrowserContext.newPage | browserContext.newPage} + * + * Contains a {@link Target} instance. + */ + TargetCreated = "targetcreated", + /** + * Emitted when a target is destroyed within the browser context, for example + * when a page is closed. Contains a {@link Target} instance. + */ + TargetDestroyed = "targetdestroyed" +} +/** + * @public + */ +export interface BrowserContextEvents extends Record { + [BrowserContextEvent.TargetChanged]: Target; + [BrowserContextEvent.TargetCreated]: Target; + [BrowserContextEvent.TargetDestroyed]: Target; +} +/** + * {@link BrowserContext} represents individual user contexts within a + * {@link Browser | browser}. + * + * When a {@link Browser | browser} is launched, it has at least one default + * {@link BrowserContext | browser context}. Others can be created + * using {@link Browser.createBrowserContext}. Each context has isolated storage + * (cookies/localStorage/etc.) + * + * {@link BrowserContext} {@link EventEmitter | emits} various events which are + * documented in the {@link BrowserContextEvent} enum. + * + * If a {@link Page | page} opens another {@link Page | page}, e.g. using + * `window.open`, the popup will belong to the parent {@link Page.browserContext + * | page's browser context}. + * + * @example Creating a new {@link BrowserContext | browser context}: + * + * ```ts + * // Create a new browser context + * const context = await browser.createBrowserContext(); + * // Create a new page inside context. + * const page = await context.newPage(); + * // ... do stuff with page ... + * await page.goto('https://example.com'); + * // Dispose context once it's no longer needed. + * await context.close(); + * ``` + * + * @remarks + * + * In Chrome all non-default contexts are incognito, + * and {@link Browser.defaultBrowserContext | default browser context} + * might be incognito if you provide the `--incognito` argument when launching + * the browser. + * + * @public + */ +export declare abstract class BrowserContext extends EventEmitter { + #private; + /** + * @internal + */ + constructor(); + /** + * Gets all active {@link Target | targets} inside this + * {@link BrowserContext | browser context}. + */ + abstract targets(): Target[]; + /** + * @internal + */ + startScreenshot(): Promise>; + /** + * @internal + */ + waitForScreenshotOperations(): Promise> | undefined; + /** + * Waits until a {@link Target | target} matching the given `predicate` + * appears and returns it. + * + * This will look all open {@link BrowserContext | browser contexts}. + * + * @example Finding a target for a page opened via `window.open`: + * + * ```ts + * await page.evaluate(() => window.open('https://www.example.com/')); + * const newWindowTarget = await browserContext.waitForTarget( + * target => target.url() === 'https://www.example.com/', + * ); + * ``` + */ + waitForTarget(predicate: (x: Target) => boolean | Promise, options?: WaitForTargetOptions): Promise; + /** + * Gets a list of all open {@link Page | pages} inside this + * {@link BrowserContext | browser context}. + * + * @param includeAll - experimental, setting to true includes all kinds of pages. + * + * @remarks Non-visible {@link Page | pages}, such as `"background_page"`, + * will not be listed here. You can find them using {@link Target.page}. + */ + abstract pages(includeAll?: boolean): Promise; + /** + * Grants this {@link BrowserContext | browser context} the given + * `permissions` within the given `origin`. + * + * @example Overriding permissions in the + * {@link Browser.defaultBrowserContext | default browser context}: + * + * ```ts + * const context = browser.defaultBrowserContext(); + * await context.overridePermissions('https://html5demos.com', [ + * 'geolocation', + * ]); + * ``` + * + * @param origin - The origin to grant permissions to, e.g. + * "https://example.com". + * @param permissions - An array of permissions to grant. All permissions that + * are not listed here will be automatically denied. + * + * @deprecated in favor of {@link BrowserContext.setPermission}. + */ + abstract overridePermissions(origin: string, permissions: Permission[]): Promise; + /** + * Sets the permission for a specific origin. + * + * @param origin - The origin to set the permission for. + * @param permission - The permission descriptor. + * @param state - The state of the permission. + * + * @public + */ + abstract setPermission(origin: string | '*', ...permissions: Array<{ + permission: PermissionDescriptor; + state: PermissionState; + }>): Promise; + /** + * Clears all permission overrides for this + * {@link BrowserContext | browser context}. + * + * @example Clearing overridden permissions in the + * {@link Browser.defaultBrowserContext | default browser context}: + * + * ```ts + * const context = browser.defaultBrowserContext(); + * context.overridePermissions('https://example.com', ['clipboard-read']); + * // do stuff .. + * context.clearPermissionOverrides(); + * ``` + */ + abstract clearPermissionOverrides(): Promise; + /** + * Creates a new {@link Page | page} in this + * {@link BrowserContext | browser context}. + */ + abstract newPage(options?: CreatePageOptions): Promise; + /** + * Gets the {@link Browser | browser} associated with this + * {@link BrowserContext | browser context}. + */ + abstract browser(): Browser; + /** + * Closes this {@link BrowserContext | browser context} and all associated + * {@link Page | pages}. + * + * @remarks The + * {@link Browser.defaultBrowserContext | default browser context} cannot be + * closed. + */ + abstract close(): Promise; + /** + * Gets all cookies in the browser context. + */ + abstract cookies(): Promise; + /** + * Sets a cookie in the browser context. + */ + abstract setCookie(...cookies: CookieData[]): Promise; + /** + * Removes cookie in this browser context. + * + * @param cookies - Complete {@link Cookie | cookie} object to be removed. + */ + deleteCookie(...cookies: Cookie[]): Promise; + /** + * Deletes cookies matching the provided filters in this browser context. + * + * @param filters - {@link DeleteCookiesRequest} + */ + deleteMatchingCookies(...filters: DeleteCookiesRequest[]): Promise; + /** + * Whether this {@link BrowserContext | browser context} is closed. + */ + get closed(): boolean; + /** + * Identifier for this {@link BrowserContext | browser context}. + */ + get id(): string | undefined; + /** @internal */ + [disposeSymbol](): void; + /** @internal */ + [asyncDisposeSymbol](): Promise; +} +//# sourceMappingURL=BrowserContext.d.ts.map \ No newline at end of file diff --git a/node_modules/puppeteer-core/lib/cjs/puppeteer/api/BrowserContext.d.ts.map b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/BrowserContext.d.ts.map new file mode 100644 index 0000000..b6ad52d --- /dev/null +++ b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/BrowserContext.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"BrowserContext.d.ts","sourceRoot":"","sources":["../../../../src/api/BrowserContext.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAQH,OAAO,KAAK,EACV,MAAM,EACN,UAAU,EACV,oBAAoB,EACrB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAC,YAAY,EAAE,KAAK,SAAS,EAAC,MAAM,2BAA2B,CAAC;AAOvE,OAAO,EAAC,kBAAkB,EAAE,aAAa,EAAC,MAAM,uBAAuB,CAAC;AACxE,OAAO,EAAC,KAAK,EAAC,MAAM,kBAAkB,CAAC;AAEvC,OAAO,KAAK,EACV,OAAO,EACP,iBAAiB,EACjB,UAAU,EACV,oBAAoB,EACpB,eAAe,EACf,oBAAoB,EACrB,MAAM,cAAc,CAAC;AACtB,OAAO,KAAK,EAAC,IAAI,EAAC,MAAM,WAAW,CAAC;AACpC,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,aAAa,CAAC;AAExC;;GAEG;AACH,0BAAkB,mBAAmB;IACnC;;;OAGG;IACH,aAAa,kBAAkB;IAE/B;;;;;;;OAOG;IACH,aAAa,kBAAkB;IAC/B;;;OAGG;IACH,eAAe,oBAAoB;CACpC;AAED;;GAEG;AACH,MAAM,WAAW,oBAAqB,SAAQ,MAAM,CAAC,SAAS,EAAE,OAAO,CAAC;IACtE,CAAC,mBAAmB,CAAC,aAAa,CAAC,EAAE,MA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,OAAO,CAAC,IAAI,CAAC;IAElD;;;OAGG;IACH,QAAQ,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,iBAAiB,GAAG,OAAO,CAAC,IAAI,CAAC;IAE5D;;;OAGG;IACH,QAAQ,CAAC,OAAO,IAAI,OAAO;IAE3B;;;;;;;OAOG;IACH,QAAQ,CAAC,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAE/B;;OAEG;IACH,QAAQ,CAAC,OAAO,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;IAErC;;OAEG;IACH,QAAQ,CAAC,SAAS,CAAC,GAAG,OAAO,EAAE,UAAU,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAE3D;;;;OAIG;IACG,YAAY,CAAC,GAAG,OAAO,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAWvD;;;;OAIG;IACG,qBAAqB,CACzB,GAAG,OAAO,EAAE,oBAAoB,EAAE,GACjC,OAAO,CAAC,IAAI,CAAC;IAiDhB;;OAEG;IACH,IAAI,MAAM,IAAI,OAAO,CAEpB;IAED;;OAEG;IACH,IAAI,EAAE,IAAI,MAAM,GAAG,SAAS,CAE3B;IAED,gBAAgB;IACP,CAAC,aAAa,CAAC,IAAI,IAAI;IAIhC,gBAAgB;IAChB,CAAC,kBAAkB,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC;CAGtC"} \ No newline at end of file diff --git a/node_modules/puppeteer-core/lib/cjs/puppeteer/api/BrowserContext.js b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/BrowserContext.js new file mode 100644 index 0000000..f7d6177 --- /dev/null +++ b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/BrowserContext.js @@ -0,0 +1,186 @@ +"use strict"; +/** + * @license + * Copyright 2017 Google Inc. + * SPDX-License-Identifier: Apache-2.0 + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BrowserContext = void 0; +const rxjs_js_1 = require("../../third_party/rxjs/rxjs.js"); +const EventEmitter_js_1 = require("../common/EventEmitter.js"); +const util_js_1 = require("../common/util.js"); +const disposable_js_1 = require("../util/disposable.js"); +const Mutex_js_1 = require("../util/Mutex.js"); +/** + * {@link BrowserContext} represents individual user contexts within a + * {@link Browser | browser}. + * + * When a {@link Browser | browser} is launched, it has at least one default + * {@link BrowserContext | browser context}. Others can be created + * using {@link Browser.createBrowserContext}. Each context has isolated storage + * (cookies/localStorage/etc.) + * + * {@link BrowserContext} {@link EventEmitter | emits} various events which are + * documented in the {@link BrowserContextEvent} enum. + * + * If a {@link Page | page} opens another {@link Page | page}, e.g. using + * `window.open`, the popup will belong to the parent {@link Page.browserContext + * | page's browser context}. + * + * @example Creating a new {@link BrowserContext | browser context}: + * + * ```ts + * // Create a new browser context + * const context = await browser.createBrowserContext(); + * // Create a new page inside context. + * const page = await context.newPage(); + * // ... do stuff with page ... + * await page.goto('https://example.com'); + * // Dispose context once it's no longer needed. + * await context.close(); + * ``` + * + * @remarks + * + * In Chrome all non-default contexts are incognito, + * and {@link Browser.defaultBrowserContext | default browser context} + * might be incognito if you provide the `--incognito` argument when launching + * the browser. + * + * @public + */ +class BrowserContext extends EventEmitter_js_1.EventEmitter { + /** + * @internal + */ + constructor() { + super(); + } + /** + * If defined, indicates an ongoing screenshot opereation. + */ + #pageScreenshotMutex; + #screenshotOperationsCount = 0; + /** + * @internal + */ + startScreenshot() { + const mutex = this.#pageScreenshotMutex || new Mutex_js_1.Mutex(); + this.#pageScreenshotMutex = mutex; + this.#screenshotOperationsCount++; + return mutex.acquire(() => { + this.#screenshotOperationsCount--; + if (this.#screenshotOperationsCount === 0) { + // Remove the mutex to indicate no ongoing screenshot operation. + this.#pageScreenshotMutex = undefined; + } + }); + } + /** + * @internal + */ + waitForScreenshotOperations() { + return this.#pageScreenshotMutex?.acquire(); + } + /** + * Waits until a {@link Target | target} matching the given `predicate` + * appears and returns it. + * + * This will look all open {@link BrowserContext | browser contexts}. + * + * @example Finding a target for a page opened via `window.open`: + * + * ```ts + * await page.evaluate(() => window.open('https://www.example.com/')); + * const newWindowTarget = await browserContext.waitForTarget( + * target => target.url() === 'https://www.example.com/', + * ); + * ``` + */ + async waitForTarget(predicate, options = {}) { + const { timeout: ms = 30000 } = options; + return await (0, rxjs_js_1.firstValueFrom)((0, rxjs_js_1.merge)((0, util_js_1.fromEmitterEvent)(this, "targetcreated" /* BrowserContextEvent.TargetCreated */), (0, util_js_1.fromEmitterEvent)(this, "targetchanged" /* BrowserContextEvent.TargetChanged */), (0, rxjs_js_1.from)(this.targets())).pipe((0, util_js_1.filterAsync)(predicate), (0, rxjs_js_1.raceWith)((0, util_js_1.timeout)(ms)))); + } + /** + * Removes cookie in this browser context. + * + * @param cookies - Complete {@link Cookie | cookie} object to be removed. + */ + async deleteCookie(...cookies) { + return await this.setCookie(...cookies.map(cookie => { + return { + ...cookie, + expires: 1, + }; + })); + } + /** + * Deletes cookies matching the provided filters in this browser context. + * + * @param filters - {@link DeleteCookiesRequest} + */ + async deleteMatchingCookies(...filters) { + const cookies = await this.cookies(); + const cookiesToDelete = cookies.filter(cookie => { + return filters.some(filter => { + if (filter.name === cookie.name) { + if (filter.domain !== undefined && filter.domain === cookie.domain) { + return true; + } + if (filter.path !== undefined && filter.path === cookie.path) { + return true; + } + if (filter.partitionKey !== undefined && + cookie.partitionKey !== undefined) { + if (typeof cookie.partitionKey !== 'object') { + throw new Error('Unexpected string partition key'); + } + if (typeof filter.partitionKey === 'string') { + if (filter.partitionKey === cookie.partitionKey?.sourceOrigin) { + return true; + } + } + else { + if (filter.partitionKey.sourceOrigin === + cookie.partitionKey?.sourceOrigin) { + return true; + } + } + } + if (filter.url !== undefined) { + const url = new URL(filter.url); + if (url.hostname === cookie.domain && + url.pathname === cookie.path) { + return true; + } + } + return true; + } + return false; + }); + }); + await this.deleteCookie(...cookiesToDelete); + } + /** + * Whether this {@link BrowserContext | browser context} is closed. + */ + get closed() { + return !this.browser().browserContexts().includes(this); + } + /** + * Identifier for this {@link BrowserContext | browser context}. + */ + get id() { + return undefined; + } + /** @internal */ + [disposable_js_1.disposeSymbol]() { + return void this.close().catch(util_js_1.debugError); + } + /** @internal */ + [disposable_js_1.asyncDisposeSymbol]() { + return this.close(); + } +} +exports.BrowserContext = BrowserContext; +//# sourceMappingURL=BrowserContext.js.map \ No newline at end of file diff --git a/node_modules/puppeteer-core/lib/cjs/puppeteer/api/BrowserContext.js.map b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/BrowserContext.js.map new file mode 100644 index 0000000..120404b --- /dev/null +++ b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/BrowserContext.js.map @@ -0,0 +1 @@ +{"version":3,"file":"BrowserContext.js","sourceRoot":"","sources":["../../../../src/api/BrowserContext.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;;AAEH,4DAKwC;AAMxC,+DAAuE;AACvE,+CAK2B;AAC3B,yDAAwE;AACxE,+CAAuC;AAgDvC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AAEH,MAAsB,cAAe,SAAQ,8BAAkC;IAC7E;;OAEG;IACH;QACE,KAAK,EAAE,CAAC;IACV,CAAC;IAQD;;OAEG;IACH,oBAAoB,CAAS;IAC7B,0BAA0B,GAAG,CAAC,CAAC;IAE/B;;OAEG;IACH,eAAe;QACb,MAAM,KAAK,GAAG,IAAI,CAAC,oBAAoB,IAAI,IAAI,gBAAK,EAAE,CAAC;QACvD,IAAI,CAAC,oBAAoB,GAAG,KAAK,CAAC;QAClC,IAAI,CAAC,0BAA0B,EAAE,CAAC;QAClC,OAAO,KAAK,CAAC,OAAO,CAAC,GAAG,EAAE;YACxB,IAAI,CAAC,0BAA0B,EAAE,CAAC;YAClC,IAAI,IAAI,CAAC,0BAA0B,KAAK,CAAC,EAAE,CAAC;gBAC1C,gEAAgE;gBAChE,IAAI,CAAC,oBAAoB,GAAG,SAAS,CAAC;YACxC,CAAC;QACH,CAAC,CAAC,CAAC;IACL,CAAC;IAED;;OAEG;IACH,2BAA2B;QAG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H,IAAI,MAAM;QACR,OAAO,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,eAAe,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IAC1D,CAAC;IAED;;OAEG;IACH,IAAI,EAAE;QACJ,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,gBAAgB;IACP,CAAC,6BAAa,CAAC;QACtB,OAAO,KAAK,IAAI,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,oBAAU,CAAC,CAAC;IAC7C,CAAC;IAED,gBAAgB;IAChB,CAAC,kCAAkB,CAAC;QAClB,OAAO,IAAI,CAAC,KAAK,EAAE,CAAC;IACtB,CAAC;CACF;AA/QD,wCA+QC"} \ No newline at end of file diff --git a/node_modules/puppeteer-core/lib/cjs/puppeteer/api/CDPSession.d.ts b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/CDPSession.d.ts new file mode 100644 index 0000000..52fba58 --- /dev/null +++ b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/CDPSession.d.ts @@ -0,0 +1,116 @@ +/** + * @license + * Copyright 2024 Google Inc. + * SPDX-License-Identifier: Apache-2.0 + */ +import type { ProtocolMapping } from 'devtools-protocol/types/protocol-mapping.js'; +import type { Connection } from '../cdp/Connection.js'; +import { EventEmitter, type EventType } from '../common/EventEmitter.js'; +/** + * @public + */ +export type CDPEvents = { + [Property in keyof ProtocolMapping.Events]: ProtocolMapping.Events[Property][0]; +}; +/** + * Events that the CDPSession class emits. + * + * @public + */ +export declare namespace CDPSessionEvent { + /** @internal */ + const Disconnected: unique symbol; + /** @internal */ + const Swapped: unique symbol; + /** + * Emitted when the session is ready to be configured during the auto-attach + * process. Right after the event is handled, the session will be resumed. + * + * @internal + */ + const Ready: unique symbol; + const SessionAttached: "sessionattached"; + const SessionDetached: "sessiondetached"; +} +/** + * @public + */ +export interface CDPSessionEvents extends CDPEvents, Record { + /** @internal */ + [CDPSessionEvent.Disconnected]: undefined; + /** @internal */ + [CDPSessionEvent.Swapped]: CDPSession; + /** @internal */ + [CDPSessionEvent.Ready]: CDPSession; + [CDPSessionEvent.SessionAttached]: CDPSession; + [CDPSessionEvent.SessionDetached]: CDPSession; +} +/** + * @public + */ +export interface CommandOptions { + timeout: number; +} +/** + * The `CDPSession` instances are used to talk raw Chrome Devtools Protocol. + * + * @remarks + * + * Protocol methods can be called with {@link CDPSession.send} method and protocol + * events can be subscribed to with `CDPSession.on` method. + * + * Useful links: {@link https://chromedevtools.github.io/devtools-protocol/ | DevTools Protocol Viewer} + * and {@link https://github.com/aslushnikov/getting-started-with-cdp/blob/HEAD/README.md | Getting Started with DevTools Protocol}. + * + * @example + * + * ```ts + * const client = await page.createCDPSession(); + * await client.send('Animation.enable'); + * client.on('Animation.animationCreated', () => + * console.log('Animation created!'), + * ); + * const response = await client.send('Animation.getPlaybackRate'); + * console.log('playback rate is ' + response.playbackRate); + * await client.send('Animation.setPlaybackRate', { + * playbackRate: response.playbackRate / 2, + * }); + * ``` + * + * @public + */ +export declare abstract class CDPSession extends EventEmitter { + /** + * @internal + */ + constructor(); + /** + * The underlying connection for this session, if any. + * + * @public + */ + abstract connection(): Connection | undefined; + /** + * True if the session has been detached, false otherwise. + * + * @public + */ + abstract get detached(): boolean; + /** + * Parent session in terms of CDP's auto-attach mechanism. + * + * @internal + */ + parentSession(): CDPSession | undefined; + abstract send(method: T, params?: ProtocolMapping.Commands[T]['paramsType'][0], options?: CommandOptions): Promise; + /** + * Detaches the cdpSession from the target. Once detached, the cdpSession object + * won't emit any events and can't be used to send messages. + */ + abstract detach(): Promise; + /** + * Returns the session's id. + */ + abstract id(): string; +} +//# sourceMappingURL=CDPSession.d.ts.map \ No newline at end of file diff --git a/node_modules/puppeteer-core/lib/cjs/puppeteer/api/CDPSession.d.ts.map b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/CDPSession.d.ts.map new file mode 100644 index 0000000..857febc --- /dev/null +++ b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/CDPSession.d.ts.map @@ -0,0 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2BG;AACH,8BAAsB,UAAW,SAAQ,YAAY,CAAC,gBAAgB,CAAC;IACrE;;OAEG;;IAKH;;;;OAIG;IACH,QAAQ,CAAC,UAAU,IAAI,UAAU,GAAG,SAAS;IAE7C;;;;OAIG;IACH,QAAQ,KAAK,QAAQ,IAAI,OAAO,CAAC;IAEjC;;;;OAIG;IACH,aAAa,IAAI,UAAU,GAAG,SAAS;IAIvC,QAAQ,CAAC,IAAI,CAAC,CAAC,SAAS,MAAM,eAAe,CAAC,QAAQ,EACpD,MAAM,EAAE,CAAC,EACT,MAAM,CAAC,EAAE,eAAe,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,EACrD,OAAO,CAAC,EAAE,cAAc,GACvB,OAAO,CAAC,eAAe,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC;IAErD;;;OAGG;IACH,QAAQ,CAAC,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC;IAEhC;;OAEG;IACH,QAAQ,CAAC,EAAE,IAAI,MAAM;CACtB"} \ No newline at end of file diff --git a/node_modules/puppeteer-core/lib/cjs/puppeteer/api/CDPSession.js b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/CDPSession.js new file mode 100644 index 0000000..c1fa3af --- /dev/null +++ b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/CDPSession.js @@ -0,0 +1,72 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CDPSession = exports.CDPSessionEvent = void 0; +const EventEmitter_js_1 = require("../common/EventEmitter.js"); +/** + * Events that the CDPSession class emits. + * + * @public + */ +// eslint-disable-next-line @typescript-eslint/no-namespace +var CDPSessionEvent; +(function (CDPSessionEvent) { + /** @internal */ + CDPSessionEvent.Disconnected = Symbol('CDPSession.Disconnected'); + /** @internal */ + CDPSessionEvent.Swapped = Symbol('CDPSession.Swapped'); + /** + * Emitted when the session is ready to be configured during the auto-attach + * process. Right after the event is handled, the session will be resumed. + * + * @internal + */ + CDPSessionEvent.Ready = Symbol('CDPSession.Ready'); + CDPSessionEvent.SessionAttached = 'sessionattached'; + CDPSessionEvent.SessionDetached = 'sessiondetached'; +})(CDPSessionEvent || (exports.CDPSessionEvent = CDPSessionEvent = {})); +/** + * The `CDPSession` instances are used to talk raw Chrome Devtools Protocol. + * + * @remarks + * + * Protocol methods can be called with {@link CDPSession.send} method and protocol + * events can be subscribed to with `CDPSession.on` method. + * + * Useful links: {@link https://chromedevtools.github.io/devtools-protocol/ | DevTools Protocol Viewer} + * and {@link https://github.com/aslushnikov/getting-started-with-cdp/blob/HEAD/README.md | Getting Started with DevTools Protocol}. + * + * @example + * + * ```ts + * const client = await page.createCDPSession(); + * await client.send('Animation.enable'); + * client.on('Animation.animationCreated', () => + * console.log('Animation created!'), + * ); + * const response = await client.send('Animation.getPlaybackRate'); + * console.log('playback rate is ' + response.playbackRate); + * await client.send('Animation.setPlaybackRate', { + * playbackRate: response.playbackRate / 2, + * }); + * ``` + * + * @public + */ +class CDPSession extends EventEmitter_js_1.EventEmitter { + /** + * @internal + */ + constructor() { + super(); + } + /** + * Parent session in terms of CDP's auto-attach mechanism. + * + * @internal + */ + parentSession() { + return undefined; + } +} +exports.CDPSession = CDPSession; +//# sourceMappingURL=CDPSession.js.map \ No newline at end of file diff --git a/node_modules/puppeteer-core/lib/cjs/puppeteer/api/CDPSession.js.map b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/CDPSession.js.map new file mode 100644 index 0000000..556a0f6 --- /dev/null +++ b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/CDPSession.js.map @@ -0,0 +1 @@ +{"version":3,"file":"CDPSession.js","sourceRoot":"","sources":["../../../../src/api/CDPSession.ts"],"names":[],"mappings":";;;AAQA,+DAAuE;AASvE;;;;GAIG;AACH,2DAA2D;AAC3D,IAAiB,eAAe,CAc/B;AAdD,WAAiB,eAAe;IAC9B,gBAAgB;IACH,4BAAY,GAAG,MAAM,CAAC,yBAAyB,CAAC,CAAC;IAC9D,gBAAgB;IACH,uBAAO,GAAG,MAAM,CAAC,oBAAoB,CAAC,CAAC;IACpD;;;;;OAKG;IACU,qBAAK,GAAG,MAAM,CAAC,kBAAkB,CAAC,CAAC;IACnC,+BAAe,GAAG,iBAA0B,CAAC;IAC7C,+BAAe,GAAG,iBAA0B,CAAC;AAC5D,CAAC,EAdgB,eAAe,+BAAf,eAAe,QAc/B;AAwBD;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,MAAsB,UAAW,SAAQ,8BAA8B;IACrE;;OAEG;IACH;QACE,KAAK,EAAE,CAAC;IACV,CAAC;IAgBD;;;;OAIG;IACH,aAAa;QACX,OAAO,SAAS,CAAC;IACnB,CAAC;CAkBF;AA/CD,gCA+CC"} \ No newline at end of file diff --git a/node_modules/puppeteer-core/lib/cjs/puppeteer/api/DeviceRequestPrompt.d.ts b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/DeviceRequestPrompt.d.ts new file mode 100644 index 0000000..26e1ca0 --- /dev/null +++ b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/DeviceRequestPrompt.d.ts @@ -0,0 +1,62 @@ +/** + * @license + * Copyright 2025 Google Inc. + * SPDX-License-Identifier: Apache-2.0 + */ +import type { WaitTimeoutOptions } from './Page.js'; +/** + * Device in a request prompt. + * + * @public + */ +export interface DeviceRequestPromptDevice { + /** + * Device id during a prompt. + */ + id: string; + /** + * Device name as it appears in a prompt. + */ + name: string; +} +/** + * Device request prompts let you respond to the page requesting for a device + * through an API like WebBluetooth. + * + * @remarks + * `DeviceRequestPrompt` instances are returned via the + * {@link Page.waitForDevicePrompt} method. + * + * @example + * + * ```ts + * const [devicePrompt] = Promise.all([ + * page.waitForDevicePrompt(), + * page.click('#connect-bluetooth'), + * ]); + * await devicePrompt.select( + * await devicePrompt.waitForDevice(({name}) => name.includes('My Device')), + * ); + * ``` + * + * @public + */ +export declare abstract class DeviceRequestPrompt { + /** + * Current list of selectable devices. + */ + readonly devices: DeviceRequestPromptDevice[]; + /** + * Resolve to the first device in the prompt matching a filter. + */ + abstract waitForDevice(filter: (device: DeviceRequestPromptDevice) => boolean, options?: WaitTimeoutOptions): Promise; + /** + * Select a device in the prompt's list. + */ + abstract select(device: DeviceRequestPromptDevice): Promise; + /** + * Cancel the prompt. + */ + abstract cancel(): Promise; +} +//# sourceMappingURL=DeviceRequestPrompt.d.ts.map \ No newline at end of file diff --git a/node_modules/puppeteer-core/lib/cjs/puppeteer/api/DeviceRequestPrompt.d.ts.map b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/DeviceRequestPrompt.d.ts.map new file mode 100644 index 0000000..c2d7cc1 --- /dev/null +++ b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/DeviceRequestPrompt.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"DeviceRequestPrompt.d.ts","sourceRoot":"","sources":["../../../../src/api/DeviceRequestPrompt.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAC,kBAAkB,EAAC,MAAM,WAAW,CAAC;AAElD;;;;GAIG;AACH,MAAM,WAAW,yBAAyB;IACxC;;OAEG;IACH,EAAE,EAAE,MAAM,CAAC;IAEX;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;CACd;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,8BAAsB,mBAAmB;IACvC;;OAEG;IACH,QAAQ,CAAC,OAAO,EAAE,yBAAyB,EAAE,CAAM;IAEnD;;OAEG;IACH,QAAQ,CAAC,aAAa,CACpB,MAAM,EAAE,CAAC,MAAM,EAAE,yBAAyB,KAAK,OAAO,EACtD,OAAO,CAAC,EAAE,kBAAkB,GAC3B,OAAO,CAAC,yBAAyB,CAAC;IAErC;;OAEG;IACH,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,yBAAyB,GAAG,OAAO,CAAC,IAAI,CAAC;IAEjE;;OAEG;IACH,QAAQ,CAAC,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC;CACjC"} \ No newline at end of file diff --git a/node_modules/puppeteer-core/lib/cjs/puppeteer/api/DeviceRequestPrompt.js b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/DeviceRequestPrompt.js new file mode 100644 index 0000000..4a1d409 --- /dev/null +++ b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/DeviceRequestPrompt.js @@ -0,0 +1,38 @@ +"use strict"; +/** + * @license + * Copyright 2025 Google Inc. + * SPDX-License-Identifier: Apache-2.0 + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DeviceRequestPrompt = void 0; +/** + * Device request prompts let you respond to the page requesting for a device + * through an API like WebBluetooth. + * + * @remarks + * `DeviceRequestPrompt` instances are returned via the + * {@link Page.waitForDevicePrompt} method. + * + * @example + * + * ```ts + * const [devicePrompt] = Promise.all([ + * page.waitForDevicePrompt(), + * page.click('#connect-bluetooth'), + * ]); + * await devicePrompt.select( + * await devicePrompt.waitForDevice(({name}) => name.includes('My Device')), + * ); + * ``` + * + * @public + */ +class DeviceRequestPrompt { + /** + * Current list of selectable devices. + */ + devices = []; +} +exports.DeviceRequestPrompt = DeviceRequestPrompt; +//# sourceMappingURL=DeviceRequestPrompt.js.map \ No newline at end of file diff --git a/node_modules/puppeteer-core/lib/cjs/puppeteer/api/DeviceRequestPrompt.js.map b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/DeviceRequestPrompt.js.map new file mode 100644 index 0000000..77e6a61 --- /dev/null +++ b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/DeviceRequestPrompt.js.map @@ -0,0 +1 @@ +{"version":3,"file":"DeviceRequestPrompt.js","sourceRoot":"","sources":["../../../../src/api/DeviceRequestPrompt.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;;AAqBH;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAsB,mBAAmB;IACvC;;OAEG;IACM,OAAO,GAAgC,EAAE,CAAC;CAmBpD;AAvBD,kDAuBC"} \ No newline at end of file diff --git a/node_modules/puppeteer-core/lib/cjs/puppeteer/api/Dialog.d.ts b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/Dialog.d.ts new file mode 100644 index 0000000..4fb2bc3 --- /dev/null +++ b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/Dialog.d.ts @@ -0,0 +1,72 @@ +/** + * @license + * Copyright 2017 Google Inc. + * SPDX-License-Identifier: Apache-2.0 + */ +import type { Protocol } from 'devtools-protocol'; +/** + * Dialog instances are dispatched by the {@link Page} via the `dialog` event. + * + * @remarks + * + * @example + * + * ```ts + * import puppeteer from 'puppeteer'; + * + * const browser = await puppeteer.launch(); + * const page = await browser.newPage(); + * page.on('dialog', async dialog => { + * console.log(dialog.message()); + * await dialog.dismiss(); + * await browser.close(); + * }); + * await page.evaluate(() => alert('1')); + * ``` + * + * @public + */ +export declare abstract class Dialog { + #private; + /** + * @internal + */ + protected handled: boolean; + /** + * @internal + */ + constructor(type: Protocol.Page.DialogType, message: string, defaultValue?: string); + /** + * The type of the dialog. + */ + type(): Protocol.Page.DialogType; + /** + * The message displayed in the dialog. + */ + message(): string; + /** + * The default value of the prompt, or an empty string if the dialog + * is not a `prompt`. + */ + defaultValue(): string; + /** + * @internal + */ + protected abstract handle(options: { + accept: boolean; + text?: string; + }): Promise; + /** + * A promise that resolves when the dialog has been accepted. + * + * @param promptText - optional text that will be entered in the dialog + * prompt. Has no effect if the dialog's type is not `prompt`. + * + */ + accept(promptText?: string): Promise; + /** + * A promise which will resolve once the dialog has been dismissed + */ + dismiss(): Promise; +} +//# sourceMappingURL=Dialog.d.ts.map \ No newline at end of file diff --git a/node_modules/puppeteer-core/lib/cjs/puppeteer/api/Dialog.d.ts.map b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/Dialog.d.ts.map new file mode 100644 index 0000000..d7bb57d --- /dev/null +++ b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/Dialog.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Dialog.d.ts","sourceRoot":"","sources":["../../../../src/api/Dialog.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAC,QAAQ,EAAC,MAAM,mBAAmB,CAAC;AAIhD;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,8BAAsB,MAAM;;IAI1B;;OAEG;IACH,SAAS,CAAC,OAAO,UAAS;IAE1B;;OAEG;gBAED,IAAI,EAAE,QAAQ,CAAC,IAAI,CAAC,UAAU,EAC9B,OAAO,EAAE,MAAM,EACf,YAAY,SAAK;IAOnB;;OAEG;IACH,IAAI,IAAI,QAAQ,CAAC,IAAI,CAAC,UAAU;IAIhC;;OAEG;IACH,OAAO,IAAI,MAAM;IAIjB;;;OAGG;IACH,YAAY,IAAI,MAAM;IAItB;;OAEG;IACH,SAAS,CAAC,QAAQ,CAAC,MAAM,CAAC,OAAO,EAAE;QACjC,MAAM,EAAE,OAAO,CAAC;QAChB,IAAI,CAAC,EAAE,MAAM,CAAC;KACf,GAAG,OAAO,CAAC,IAAI,CAAC;IAEjB;;;;;;OAMG;IACG,MAAM,CAAC,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAShD;;OAEG;IACG,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;CAO/B"} \ No newline at end of file diff --git a/node_modules/puppeteer-core/lib/cjs/puppeteer/api/Dialog.js b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/Dialog.js new file mode 100644 index 0000000..506a46d --- /dev/null +++ b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/Dialog.js @@ -0,0 +1,94 @@ +"use strict"; +/** + * @license + * Copyright 2017 Google Inc. + * SPDX-License-Identifier: Apache-2.0 + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Dialog = void 0; +const assert_js_1 = require("../util/assert.js"); +/** + * Dialog instances are dispatched by the {@link Page} via the `dialog` event. + * + * @remarks + * + * @example + * + * ```ts + * import puppeteer from 'puppeteer'; + * + * const browser = await puppeteer.launch(); + * const page = await browser.newPage(); + * page.on('dialog', async dialog => { + * console.log(dialog.message()); + * await dialog.dismiss(); + * await browser.close(); + * }); + * await page.evaluate(() => alert('1')); + * ``` + * + * @public + */ +class Dialog { + #type; + #message; + #defaultValue; + /** + * @internal + */ + handled = false; + /** + * @internal + */ + constructor(type, message, defaultValue = '') { + this.#type = type; + this.#message = message; + this.#defaultValue = defaultValue; + } + /** + * The type of the dialog. + */ + type() { + return this.#type; + } + /** + * The message displayed in the dialog. + */ + message() { + return this.#message; + } + /** + * The default value of the prompt, or an empty string if the dialog + * is not a `prompt`. + */ + defaultValue() { + return this.#defaultValue; + } + /** + * A promise that resolves when the dialog has been accepted. + * + * @param promptText - optional text that will be entered in the dialog + * prompt. Has no effect if the dialog's type is not `prompt`. + * + */ + async accept(promptText) { + (0, assert_js_1.assert)(!this.handled, 'Cannot accept dialog which is already handled!'); + this.handled = true; + await this.handle({ + accept: true, + text: promptText, + }); + } + /** + * A promise which will resolve once the dialog has been dismissed + */ + async dismiss() { + (0, assert_js_1.assert)(!this.handled, 'Cannot dismiss dialog which is already handled!'); + this.handled = true; + await this.handle({ + accept: false, + }); + } +} +exports.Dialog = Dialog; +//# sourceMappingURL=Dialog.js.map \ No newline at end of file diff --git a/node_modules/puppeteer-core/lib/cjs/puppeteer/api/Dialog.js.map b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/Dialog.js.map new file mode 100644 index 0000000..2569f06 --- /dev/null +++ b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/Dialog.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Dialog.js","sourceRoot":"","sources":["../../../../src/api/Dialog.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;;AAIH,iDAAyC;AAEzC;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAsB,MAAM;IAC1B,KAAK,CAA2B;IAChC,QAAQ,CAAS;IACjB,aAAa,CAAS;IACtB;;OAEG;IACO,OAAO,GAAG,KAAK,CAAC;IAE1B;;OAEG;IACH,YACE,IAA8B,EAC9B,OAAe,EACf,YAAY,GAAG,EAAE;QAEjB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QAClB,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;QACxB,IAAI,CAAC,aAAa,GAAG,YAAY,CAAC;IACpC,CAAC;IAED;;OAEG;IACH,IAAI;QACF,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;IAED;;OAEG;IACH,OAAO;QACL,OAAO,IAAI,CAAC,QAAQ,CAAC;IACvB,CAAC;IAED;;;OAGG;IACH,YAAY;QACV,OAAO,IAAI,CAAC,aAAa,CAAC;IAC5B,CAAC;IAUD;;;;;;OAMG;IACH,KAAK,CAAC,MAAM,CAAC,UAAmB;QAC9B,IAAA,kBAAM,EAAC,CAAC,IAAI,CAAC,OAAO,EAAE,gDAAgD,CAAC,CAAC;QACxE,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;QACpB,MAAM,IAAI,CAAC,MAAM,CAAC;YAChB,MAAM,EAAE,IAAI;YACZ,IAAI,EAAE,UAAU;SACjB,CAAC,CAAC;IACL,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,OAAO;QACX,IAAA,kBAAM,EAAC,CAAC,IAAI,CAAC,OAAO,EAAE,iDAAiD,CAAC,CAAC;QACzE,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;QACpB,MAAM,IAAI,CAAC,MAAM,CAAC;YAChB,MAAM,EAAE,KAAK;SACd,CAAC,CAAC;IACL,CAAC;CACF;AA9ED,wBA8EC"} \ No newline at end of file diff --git a/node_modules/puppeteer-core/lib/cjs/puppeteer/api/ElementHandle.d.ts b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/ElementHandle.d.ts new file mode 100644 index 0000000..09e4d43 --- /dev/null +++ b/node_modules/puppeteer-core/lib/cjs/puppeteer/api/ElementHandle.d.ts @@ -0,0 +1,666 @@ +/** + * @license + * Copyright 2023 Google Inc. + * SPDX-License-Identifier: Apache-2.0 + */ +import type { Protocol } from 'devtools-protocol'; +import type { Frame } from '../api/Frame.js'; +import type { AwaitableIterable, ElementFor, EvaluateFuncWith, HandleFor, HandleOr, NodeFor } from '../common/types.js'; +import type { KeyInput } from '../common/USKeyboardLayout.js'; +import { _isElementHandle } from './ElementHandleSymbol.js'; +import type { KeyboardTypeOptions, KeyPressOptions, MouseClickOptions, TouchHandle } from './Input.js'; +import { JSHandle } from './JSHandle.js'; +import type { Locator } from './locators/locators.js'; +import type { QueryOptions, ScreenshotOptions, WaitForSelectorOptions } from './Page.js'; +/** + * @public + */ +export type Quad = [Point, Point, Point, Point]; +/** + * @public + */ +export interface BoxModel { + content: Quad; + padding: Quad; + border: Quad; + margin: Quad; + width: number; + height: number; +} +/** + * @public + */ +export interface BoundingBox extends Point { + /** + * the width of the element in pixels. + */ + width: number; + /** + * the height of the element in pixels. + */ + height: number; +} +/** + * @public + */ +export interface Offset { + /** + * x-offset for the clickable point relative to the top-left corner of the border box. + */ + x: number; + /** + * y-offset for the clickable point relative to the top-left corner of the border box. + */ + y: number; +} +/** + * @public + */ +export interface ClickOptions extends MouseClickOptions { + /** + * Offset for the clickable point relative to the top-left corner of the border box. + */ + offset?: Offset; + /** + * An experimental debugging feature. If true, inserts an element into the + * page to highlight the click location for 10 seconds. Might not work on all + * pages and does not persist across navigations. + * + * @experimental + */ + debugHighlight?: boolean; +} +/** + * @public + */ +export interface Point { + x: number; + y: number; +} +/** + * @public + */ +export interface ElementScreenshotOptions extends ScreenshotOptions { + /** + * @defaultValue `true` + */ + scrollIntoView?: boolean; +} +/** + * A given method will have it's `this` replaced with an isolated version of + * `this` when decorated with this decorator. + * + * All changes of isolated `this` are reflected on the actual `this`. + * + * @internal + */ +export declare function bindIsolatedHandle>(target: (this: This, ...args: any[]) => Promise, _: unknown): typeof target; +/** + * ElementHandle represents an in-page DOM element. + * + * @remarks + * ElementHandles can be created with the {@link Page.$} method. + * + * ```ts + * import puppeteer from 'puppeteer'; + * + * const browser = await puppeteer.launch(); + * const page = await browser.newPage(); + * await page.goto('https://example.com'); + * const hrefElement = await page.$('a'); + * await hrefElement.click(); + * // ... + * ``` + * + * ElementHandle prevents the DOM element from being garbage-collected unless the + * handle is {@link JSHandle.dispose | disposed}. ElementHandles are auto-disposed + * when their associated frame is navigated away or the parent + * context gets destroyed. + * + * ElementHandle instances can be used as arguments in {@link Page.$eval} and + * {@link Page.evaluate} methods. + * + * If you're using TypeScript, ElementHandle takes a generic argument that + * denotes the type of element the handle is holding within. For example, if you + * have a handle to a `` element matching `selector`, the method + * throws an error. + * + * @example + * + * ```ts + * handle.select('blue'); // single selection + * handle.select('red', 'green', 'blue'); // multiple selections + * ``` + * + * @param values - Values of options to select. If the `` element, you can type it as + * `ElementHandle` and you get some nicer type checks. + * + * @public + */ +let ElementHandle = (() => { + let _classSuper = JSHandle_js_1.JSHandle; + let _instanceExtraInitializers = []; + let _getProperty_decorators; + let _getProperties_decorators; + let _jsonValue_decorators; + let _$_decorators; + let _$$_decorators; + let _private_$$_decorators; + let _private_$$_descriptor; + let _waitForSelector_decorators; + let _isVisible_decorators; + let _isHidden_decorators; + let _toElement_decorators; + let _clickablePoint_decorators; + let _hover_decorators; + let _click_decorators; + let _drag_decorators; + let _dragEnter_decorators; + let _dragOver_decorators; + let _drop_decorators; + let _dragAndDrop_decorators; + let _select_decorators; + let _tap_decorators; + let _touchStart_decorators; + let _touchMove_decorators; + let _touchEnd_decorators; + let _focus_decorators; + let _type_decorators; + let _press_decorators; + let _boundingBox_decorators; + let _boxModel_decorators; + let _screenshot_decorators; + let _isIntersectingViewport_decorators; + let _scrollIntoView_decorators; + let _asLocator_decorators; + return class ElementHandle extends _classSuper { + static { + const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0; + _getProperty_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle]; + _getProperties_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle]; + _jsonValue_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle]; + _$_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle]; + _$$_decorators = [(0, decorators_js_1.throwIfDisposed)()]; + _private_$$_decorators = [bindIsolatedHandle]; + _waitForSelector_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle]; + _isVisible_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle]; + _isHidden_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle]; + _toElement_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle]; + _clickablePoint_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle]; + _hover_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle]; + _click_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle]; + _drag_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle]; + _dragEnter_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle]; + _dragOver_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle]; + _drop_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle]; + _dragAndDrop_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle]; + _select_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle]; + _tap_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle]; + _touchStart_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle]; + _touchMove_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle]; + _touchEnd_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle]; + _focus_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle]; + _type_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle]; + _press_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle]; + _boundingBox_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle]; + _boxModel_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle]; + _screenshot_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle]; + _isIntersectingViewport_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle]; + _scrollIntoView_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle]; + _asLocator_decorators = [(0, decorators_js_1.throwIfDisposed)()]; + __esDecorate(this, null, _getProperty_decorators, { kind: "method", name: "getProperty", static: false, private: false, access: { has: obj => "getProperty" in obj, get: obj => obj.getProperty }, metadata: _metadata }, null, _instanceExtraInitializers); + __esDecorate(this, null, _getProperties_decorators, { kind: "method", name: "getProperties", static: false, private: false, access: { has: obj => "getProperties" in obj, get: obj => obj.getProperties }, metadata: _metadata }, null, _instanceExtraInitializers); + __esDecorate(this, null, _jsonValue_decorators, { kind: "method", name: "jsonValue", static: false, private: false, access: { has: obj => "jsonValue" in obj, get: obj => obj.jsonValue }, metadata: _metadata }, null, _instanceExtraInitializers); + __esDecorate(this, null, _$_decorators, { kind: "method", name: "$", static: false, private: false, access: { has: obj => "$" in obj, get: obj => obj.$ }, metadata: _metadata }, null, _instanceExtraInitializers); + __esDecorate(this, null, _$$_decorators, { kind: "method", name: "$$", static: false, private: false, access: { has: obj => "$$" in obj, get: obj => obj.$$ }, metadata: _metadata }, null, _instanceExtraInitializers); + __esDecorate(this, _private_$$_descriptor = { value: __setFunctionName(async function (selector) { + return await this.#$$impl(selector); + }, "#$$") }, _private_$$_decorators, { kind: "method", name: "#$$", static: false, private: true, access: { has: obj => #$$ in obj, get: obj => obj.#$$ }, metadata: _metadata }, null, _instanceExtraInitializers); + __esDecorate(this, null, _waitForSelector_decorators, { kind: "method", name: "waitForSelector", static: false, private: false, access: { has: obj => "waitForSelector" in obj, get: obj => obj.waitForSelector }, metadata: _metadata }, null, _instanceExtraInitializers); + __esDecorate(this, null, _isVisible_decorators, { kind: "method", name: "isVisible", static: false, private: false, access: { has: obj => "isVisible" in obj, get: obj => obj.isVisible }, metadata: _metadata }, null, _instanceExtraInitializers); + __esDecorate(this, null, _isHidden_decorators, { kind: "method", name: "isHidden", static: false, private: false, access: { has: obj => "isHidden" in obj, get: obj => obj.isHidden }, metadata: _metadata }, null, _instanceExtraInitializers); + __esDecorate(this, null, _toElement_decorators, { kind: "method", name: "toElement", static: false, private: false, access: { has: obj => "toElement" in obj, get: obj => obj.toElement }, metadata: _metadata }, null, _instanceExtraInitializers); + __esDecorate(this, null, _clickablePoint_decorators, { kind: "method", name: "clickablePoint", static: false, private: false, access: { has: obj => "clickablePoint" in obj, get: obj => obj.clickablePoint }, metadata: _metadata }, null, _instanceExtraInitializers); + __esDecorate(this, null, _hover_decorators, { kind: "method", name: "hover", static: false, private: false, access: { has: obj => "hover" in obj, get: obj => obj.hover }, metadata: _metadata }, null, _instanceExtraInitializers); + __esDecorate(this, null, _click_decorators, { kind: "method", name: "click", static: false, private: false, access: { has: obj => "click" in obj, get: obj => obj.click }, metadata: _metadata }, null, _instanceExtraInitializers); + __esDecorate(this, null, _drag_decorators, { kind: "method", name: "drag", static: false, private: false, access: { has: obj => "drag" in obj, get: obj => obj.drag }, metadata: _metadata }, null, _instanceExtraInitializers); + __esDecorate(this, null, _dragEnter_decorators, { kind: "method", name: "dragEnter", static: false, private: false, access: { has: obj => "dragEnter" in obj, get: obj => obj.dragEnter }, metadata: _metadata }, null, _instanceExtraInitializers); + __esDecorate(this, null, _dragOver_decorators, { kind: "method", name: "dragOver", static: false, private: false, access: { has: obj => "dragOver" in obj, get: obj => obj.dragOver }, metadata: _metadata }, null, _instanceExtraInitializers); + __esDecorate(this, null, _drop_decorators, { kind: "method", name: "drop", static: false, private: false, access: { has: obj => "drop" in obj, get: obj => obj.drop }, metadata: _metadata }, null, _instanceExtraInitializers); + __esDecorate(this, null, _dragAndDrop_decorators, { kind: "method", name: "dragAndDrop", static: false, private: false, access: { has: obj => "dragAndDrop" in obj, get: obj => obj.dragAndDrop }, metadata: _metadata }, null, _instanceExtraInitializers); + __esDecorate(this, null, _select_decorators, { kind: "method", name: "select", static: false, private: false, access: { has: obj => "select" in obj, get: obj => obj.select }, metadata: _metadata }, null, _instanceExtraInitializers); + __esDecorate(this, null, _tap_decorators, { kind: "method", name: "tap", static: false, private: false, access: { has: obj => "tap" in obj, get: obj => obj.tap }, metadata: _metadata }, null, _instanceExtraInitializers); + __esDecorate(this, null, _touchStart_decorators, { kind: "method", name: "touchStart", static: false, private: false, access: { has: obj => "touchStart" in obj, get: obj => obj.touchStart }, metadata: _metadata }, null, _instanceExtraInitializers); + __esDecorate(this, null, _touchMove_decorators, { kind: "method", name: "touchMove", static: false, private: false, access: { has: obj => "touchMove" in obj, get: obj => obj.touchMove }, metadata: _metadata }, null, _instanceExtraInitializers); + __esDecorate(this, null, _touchEnd_decorators, { kind: "method", name: "touchEnd", static: false, private: false, access: { has: obj => "touchEnd" in obj, get: obj => obj.touchEnd }, metadata: _metadata }, null, _instanceExtraInitializers); + __esDecorate(this, null, _focus_decorators, { kind: "method", name: "focus", static: false, private: false, access: { has: obj => "focus" in obj, get: obj => obj.focus }, metadata: _metadata }, null, _instanceExtraInitializers); + __esDecorate(this, null, _type_decorators, { kind: "method", name: "type", static: false, private: false, access: { has: obj => "type" in obj, get: obj => obj.type }, metadata: _metadata }, null, _instanceExtraInitializers); + __esDecorate(this, null, _press_decorators, { kind: "method", name: "press", static: false, private: false, access: { has: obj => "press" in obj, get: obj => obj.press }, metadata: _metadata }, null, _instanceExtraInitializers); + __esDecorate(this, null, _boundingBox_decorators, { kind: "method", name: "boundingBox", static: false, private: false, access: { has: obj => "boundingBox" in obj, get: obj => obj.boundingBox }, metadata: _metadata }, null, _instanceExtraInitializers); + __esDecorate(this, null, _boxModel_decorators, { kind: "method", name: "boxModel", static: false, private: false, access: { has: obj => "boxModel" in obj, get: obj => obj.boxModel }, metadata: _metadata }, null, _instanceExtraInitializers); + __esDecorate(this, null, _screenshot_decorators, { kind: "method", name: "screenshot", static: false, private: false, access: { has: obj => "screenshot" in obj, get: obj => obj.screenshot }, metadata: _metadata }, null, _instanceExtraInitializers); + __esDecorate(this, null, _isIntersectingViewport_decorators, { kind: "method", name: "isIntersectingViewport", static: false, private: false, access: { has: obj => "isIntersectingViewport" in obj, get: obj => obj.isIntersectingViewport }, metadata: _metadata }, null, _instanceExtraInitializers); + __esDecorate(this, null, _scrollIntoView_decorators, { kind: "method", name: "scrollIntoView", static: false, private: false, access: { has: obj => "scrollIntoView" in obj, get: obj => obj.scrollIntoView }, metadata: _metadata }, null, _instanceExtraInitializers); + __esDecorate(this, null, _asLocator_decorators, { kind: "method", name: "asLocator", static: false, private: false, access: { has: obj => "asLocator" in obj, get: obj => obj.asLocator }, metadata: _metadata }, null, _instanceExtraInitializers); + if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata }); + } + /** + * @internal + * Cached isolatedHandle to prevent + * trying to adopt it multiple times + */ + isolatedHandle = __runInitializers(this, _instanceExtraInitializers); + /** + * @internal + */ + handle; + /** + * @internal + */ + constructor(handle) { + super(); + this.handle = handle; + this[ElementHandleSymbol_js_1._isElementHandle] = true; + } + /** + * @internal + */ + get id() { + return this.handle.id; + } + /** + * @internal + */ + get disposed() { + return this.handle.disposed; + } + /** + * @internal + */ + async getProperty(propertyName) { + return await this.handle.getProperty(propertyName); + } + /** + * @internal + */ + async getProperties() { + return await this.handle.getProperties(); + } + /** + * @internal + */ + async evaluate(pageFunction, ...args) { + pageFunction = (0, util_js_1.withSourcePuppeteerURLIfNone)(this.evaluate.name, pageFunction); + return await this.handle.evaluate(pageFunction, ...args); + } + /** + * @internal + */ + async evaluateHandle(pageFunction, ...args) { + pageFunction = (0, util_js_1.withSourcePuppeteerURLIfNone)(this.evaluateHandle.name, pageFunction); + return await this.handle.evaluateHandle(pageFunction, ...args); + } + /** + * @internal + */ + async jsonValue() { + return await this.handle.jsonValue(); + } + /** + * @internal + */ + toString() { + return this.handle.toString(); + } + /** + * @internal + */ + remoteObject() { + return this.handle.remoteObject(); + } + /** + * @internal + */ + async dispose() { + await Promise.all([this.handle.dispose(), this.isolatedHandle?.dispose()]); + } + /** + * @internal + */ + asElement() { + return this; + } + /** + * Queries the current element for an element matching the given selector. + * + * @param selector - + * {@link https://pptr.dev/guides/page-interactions#selectors | selector} + * to query the page for. + * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | CSS selectors} + * can be passed as-is and a + * {@link https://pptr.dev/guides/page-interactions#non-css-selectors | Puppeteer-specific selector syntax} + * allows querying by + * {@link https://pptr.dev/guides/page-interactions#text-selectors--p-text | text}, + * {@link https://pptr.dev/guides/page-interactions#aria-selectors--p-aria | a11y role and name}, + * and + * {@link https://pptr.dev/guides/page-interactions#xpath-selectors--p-xpath | xpath} + * and + * {@link https://pptr.dev/guides/page-interactions#querying-elements-in-shadow-dom | combining these queries across shadow roots}. + * Alternatively, you can specify the selector type using a + * {@link https://pptr.dev/guides/page-interactions#prefixed-selector-syntax | prefix}. + * @returns A {@link ElementHandle | element handle} to the first element + * matching the given selector. Otherwise, `null`. + */ + async $(selector) { + const { updatedSelector, QueryHandler } = (0, GetQueryHandler_js_1.getQueryHandlerAndSelector)(selector); + return (await QueryHandler.queryOne(this, updatedSelector)); + } + /** + * Queries the current element for all elements matching the given selector. + * + * @param selector - + * {@link https://pptr.dev/guides/page-interactions#selectors | selector} + * to query the page for. + * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | CSS selectors} + * can be passed as-is and a + * {@link https://pptr.dev/guides/page-interactions#non-css-selectors | Puppeteer-specific selector syntax} + * allows querying by + * {@link https://pptr.dev/guides/page-interactions#text-selectors--p-text | text}, + * {@link https://pptr.dev/guides/page-interactions#aria-selectors--p-aria | a11y role and name}, + * and + * {@link https://pptr.dev/guides/page-interactions#xpath-selectors--p-xpath | xpath} + * and + * {@link https://pptr.dev/guides/page-interactions#querying-elements-in-shadow-dom | combining these queries across shadow roots}. + * Alternatively, you can specify the selector type using a + * {@link https://pptr.dev/guides/page-interactions#prefixed-selector-syntax | prefix}. + * @returns An array of {@link ElementHandle | element handles} that point to + * elements matching the given selector. + */ + async $$(selector, options) { + if (options?.isolate === false) { + return await this.#$$impl(selector); + } + return await this.#$$(selector); + } + /** + * Isolates {@link ElementHandle.$$} if needed. + * + * @internal + */ + get #$$() { return _private_$$_descriptor.value; } + /** + * Implementation for {@link ElementHandle.$$}. + * + * @internal + */ + async #$$impl(selector) { + const { updatedSelector, QueryHandler } = (0, GetQueryHandler_js_1.getQueryHandlerAndSelector)(selector); + return await AsyncIterableUtil_js_1.AsyncIterableUtil.collect(QueryHandler.queryAll(this, updatedSelector)); + } + /** + * Runs the given function on the first element matching the given selector in + * the current element. + * + * If the given function returns a promise, then this method will wait till + * the promise resolves. + * + * @example + * + * ```ts + * const tweetHandle = await page.$('.tweet'); + * expect(await tweetHandle.$eval('.like', node => node.innerText)).toBe( + * '100', + * ); + * expect(await tweetHandle.$eval('.retweets', node => node.innerText)).toBe( + * '10', + * ); + * ``` + * + * @param selector - + * {@link https://pptr.dev/guides/page-interactions#selectors | selector} + * to query the page for. + * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | CSS selectors} + * can be passed as-is and a + * {@link https://pptr.dev/guides/page-interactions#non-css-selectors | Puppeteer-specific selector syntax} + * allows querying by + * {@link https://pptr.dev/guides/page-interactions#text-selectors--p-text | text}, + * {@link https://pptr.dev/guides/page-interactions#aria-selectors--p-aria | a11y role and name}, + * and + * {@link https://pptr.dev/guides/page-interactions#xpath-selectors--p-xpath | xpath} + * and + * {@link https://pptr.dev/guides/page-interactions#querying-elements-in-shadow-dom | combining these queries across shadow roots}. + * Alternatively, you can specify the selector type using a + * {@link https://pptr.dev/guides/page-interactions#prefixed-selector-syntax | prefix}. + * @param pageFunction - The function to be evaluated in this element's page's + * context. The first element matching the selector will be passed in as the + * first argument. + * @param args - Additional arguments to pass to `pageFunction`. + * @returns A promise to the result of the function. + */ + async $eval(selector, pageFunction, ...args) { + const env_1 = { stack: [], error: void 0, hasError: false }; + try { + pageFunction = (0, util_js_1.withSourcePuppeteerURLIfNone)(this.$eval.name, pageFunction); + const elementHandle = __addDisposableResource(env_1, await this.$(selector), false); + if (!elementHandle) { + throw new Error(`Error: failed to find element matching selector "${selector}"`); + } + return await elementHandle.evaluate(pageFunction, ...args); + } + catch (e_1) { + env_1.error = e_1; + env_1.hasError = true; + } + finally { + __disposeResources(env_1); + } + } + /** + * Runs the given function on an array of elements matching the given selector + * in the current element. + * + * If the given function returns a promise, then this method will wait till + * the promise resolves. + * + * @example + * HTML: + * + * ```html + *
    + *
    Hello!
    + *
    Hi!
    + *
    + * ``` + * + * JavaScript: + * + * ```ts + * const feedHandle = await page.$('.feed'); + * + * const listOfTweets = await feedHandle.$$eval('.tweet', nodes => + * nodes.map(n => n.innerText), + * ); + * ``` + * + * @param selector - + * {@link https://pptr.dev/guides/page-interactions#selectors | selector} + * to query the page for. + * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | CSS selectors} + * can be passed as-is and a + * {@link https://pptr.dev/guides/page-interactions#non-css-selectors | Puppeteer-specific selector syntax} + * allows querying by + * {@link https://pptr.dev/guides/page-interactions#text-selectors--p-text | text}, + * {@link https://pptr.dev/guides/page-interactions#aria-selectors--p-aria | a11y role and name}, + * and + * {@link https://pptr.dev/guides/page-interactions#xpath-selectors--p-xpath | xpath} + * and + * {@link https://pptr.dev/guides/page-interactions#querying-elements-in-shadow-dom | combining these queries across shadow roots}. + * Alternatively, you can specify the selector type using a + * {@link https://pptr.dev/guides/page-interactions#prefixed-selector-syntax | prefix}. + * @param pageFunction - The function to be evaluated in the element's page's + * context. An array of elements matching the given selector will be passed to + * the function as its first argument. + * @param args - Additional arguments to pass to `pageFunction`. + * @returns A promise to the result of the function. + */ + async $$eval(selector, pageFunction, ...args) { + const env_2 = { stack: [], error: void 0, hasError: false }; + try { + pageFunction = (0, util_js_1.withSourcePuppeteerURLIfNone)(this.$$eval.name, pageFunction); + const results = await this.$$(selector); + const elements = __addDisposableResource(env_2, await this.evaluateHandle((_, ...elements) => { + return elements; + }, ...results), false); + const [result] = await Promise.all([ + elements.evaluate(pageFunction, ...args), + ...results.map(results => { + return results.dispose(); + }), + ]); + return result; + } + catch (e_2) { + env_2.error = e_2; + env_2.hasError = true; + } + finally { + __disposeResources(env_2); + } + } + /** + * Wait for an element matching the given selector to appear in the current + * element. + * + * Unlike {@link Frame.waitForSelector}, this method does not work across + * navigations or if the element is detached from DOM. + * + * @example + * + * ```ts + * import puppeteer from 'puppeteer'; + * + * const browser = await puppeteer.launch(); + * const page = await browser.newPage(); + * let currentURL; + * page + * .mainFrame() + * .waitForSelector('img') + * .then(() => console.log('First URL with image: ' + currentURL)); + * + * for (currentURL of [ + * 'https://example.com', + * 'https://google.com', + * 'https://bbc.com', + * ]) { + * await page.goto(currentURL); + * } + * await browser.close(); + * ``` + * + * @param selector - The selector to query and wait for. + * @param options - Options for customizing waiting behavior. + * @returns An element matching the given selector. + * @throws Throws if an element matching the given selector doesn't appear. + */ + async waitForSelector(selector, options = {}) { + const { updatedSelector, QueryHandler, polling } = (0, GetQueryHandler_js_1.getQueryHandlerAndSelector)(selector); + return (await QueryHandler.waitFor(this, updatedSelector, { + polling, + ...options, + })); + } + async #checkVisibility(visibility) { + return await this.evaluate(async (element, PuppeteerUtil, visibility) => { + return Boolean(PuppeteerUtil.checkVisibility(element, visibility)); + }, LazyArg_js_1.LazyArg.create(context => { + return context.puppeteerUtil; + }), visibility); + } + /** + * An element is considered to be visible if all of the following is + * true: + * + * - the element has + * {@link https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle | computed styles}. + * + * - the element has a non-empty + * {@link https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect | bounding client rect}. + * + * - the element's {@link https://developer.mozilla.org/en-US/docs/Web/CSS/visibility | visibility} + * is not `hidden` or `collapse`. + */ + async isVisible() { + return await this.#checkVisibility(true); + } + /** + * An element is considered to be hidden if at least one of the following is true: + * + * - the element has no + * {@link https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle | computed styles}. + * + * - the element has an empty + * {@link https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect | bounding client rect}. + * + * - the element's {@link https://developer.mozilla.org/en-US/docs/Web/CSS/visibility | visibility} + * is `hidden` or `collapse`. + */ + async isHidden() { + return await this.#checkVisibility(false); + } + /** + * Converts the current handle to the given element type. + * + * @example + * + * ```ts + * const element: ElementHandle = await page.$( + * '.class-name-of-anchor', + * ); + * // DO NOT DISPOSE `element`, this will be always be the same handle. + * const anchor: ElementHandle = + * await element.toElement('a'); + * ``` + * + * @param tagName - The tag name of the desired element type. + * @throws An error if the handle does not match. **The handle will not be + * automatically disposed.** + */ + async toElement(tagName) { + const isMatchingTagName = await this.evaluate((node, tagName) => { + return node.nodeName === tagName.toUpperCase(); + }, tagName); + if (!isMatchingTagName) { + throw new Error(`Element is not a(n) \`${tagName}\` element`); + } + return this; + } + /** + * Returns the middle point within an element unless a specific offset is provided. + */ + async clickablePoint(offset) { + const box = await this.#clickableBox(); + if (!box) { + throw new Error('Node is either not clickable or not an Element'); + } + if (offset !== undefined) { + return { + x: box.x + offset.x, + y: box.y + offset.y, + }; + } + return { + x: box.x + box.width / 2, + y: box.y + box.height / 2, + }; + } + /** + * This method scrolls element into view if needed, and then + * uses {@link Page.mouse} to hover over the center of the element. + * If the element is detached from DOM, the method throws an error. + */ + async hover() { + await this.scrollIntoViewIfNeeded(); + const { x, y } = await this.clickablePoint(); + await this.frame.page().mouse.move(x, y); + } + /** + * This method scrolls element into view if needed, and then + * uses {@link Page.mouse} to click in the center of the element. + * If the element is detached from DOM, the method throws an error. + */ + async click(options = {}) { + await this.scrollIntoViewIfNeeded(); + const { x, y } = await this.clickablePoint(options.offset); + try { + await this.frame.page().mouse.click(x, y, options); + } + finally { + if (options.debugHighlight) { + await this.frame.page().evaluate((x, y) => { + const highlight = document.createElement('div'); + highlight.innerHTML = ``; + highlight.addEventListener('animationend', () => { + highlight.remove(); + }, { once: true }); + document.body.append(highlight); + }, x, y); + } + } + } + /** + * Drags an element over the given element or point. + * + * @returns DEPRECATED. When drag interception is enabled, the drag payload is + * returned. + */ + async drag(target) { + await this.scrollIntoViewIfNeeded(); + const page = this.frame.page(); + if (page.isDragInterceptionEnabled()) { + const source = await this.clickablePoint(); + if (target instanceof ElementHandle) { + target = await target.clickablePoint(); + } + return await page.mouse.drag(source, target); + } + try { + if (!page._isDragging) { + page._isDragging = true; + await this.hover(); + await page.mouse.down(); + } + if (target instanceof ElementHandle) { + await target.hover(); + } + else { + await page.mouse.move(target.x, target.y); + } + } + catch (error) { + page._isDragging = false; + throw error; + } + } + /** + * @deprecated Do not use. `dragenter` will automatically be performed during dragging. + */ + async dragEnter(data = { items: [], dragOperationsMask: 1 }) { + const page = this.frame.page(); + await this.scrollIntoViewIfNeeded(); + const target = await this.clickablePoint(); + await page.mouse.dragEnter(target, data); + } + /** + * @deprecated Do not use. `dragover` will automatically be performed during dragging. + */ + async dragOver(data = { items: [], dragOperationsMask: 1 }) { + const page = this.frame.page(); + await this.scrollIntoViewIfNeeded(); + const target = await this.clickablePoint(); + await page.mouse.dragOver(target, data); + } + /** + * @internal + */ + async drop(dataOrElement = { + items: [], + dragOperationsMask: 1, + }) { + const page = this.frame.page(); + if ('items' in dataOrElement) { + await this.scrollIntoViewIfNeeded(); + const destination = await this.clickablePoint(); + await page.mouse.drop(destination, dataOrElement); + } + else { + // Note if the rest errors, we still want dragging off because the errors + // is most likely something implying the mouse is no longer dragging. + await dataOrElement.drag(this); + page._isDragging = false; + await page.mouse.up(); + } + } + /** + * @deprecated Use `ElementHandle.drop` instead. + */ + async dragAndDrop(target, options) { + const page = this.frame.page(); + (0, assert_js_1.assert)(page.isDragInterceptionEnabled(), 'Drag Interception is not enabled!'); + await this.scrollIntoViewIfNeeded(); + const startPoint = await this.clickablePoint(); + const targetPoint = await target.clickablePoint(); + await page.mouse.dragAndDrop(startPoint, targetPoint, options); + } + /** + * Triggers a `change` and `input` event once all the provided options have been + * selected. If there's no `` has the + * `multiple` attribute, all values are considered, otherwise only the first + * one is taken into account. + */ + async select(...values) { + for (const value of values) { + (0, assert_js_1.assert)((0, util_js_1.isString)(value), 'Values must be strings. Found value "' + + value + + '" of type "' + + typeof value + + '"'); + } + return await this.evaluate((element, vals) => { + const values = new Set(vals); + if (!(element instanceof HTMLSelectElement)) { + throw new Error('Element is not a = { + /** + * The Standard Schema properties. + */ + readonly "~standard": StandardSchemaV1.Props; +}; + +export declare namespace StandardSchemaV1 { + /** + * The Standard Schema properties interface. + */ + export interface Props { + /** + * The version number of the standard. + */ + readonly version: 1; + /** + * The vendor name of the schema library. + */ + readonly vendor: string; + /** + * Validates unknown input values. + */ + readonly validate: (value: unknown) => Result | Promise>; + /** + * Inferred types associated with the schema. + */ + readonly types?: Types | undefined; + } + + /** + * The result interface of the validate function. + */ + export type Result = SuccessResult | FailureResult; + + /** + * The result interface if validation succeeds. + */ + export interface SuccessResult { + /** + * The typed output value. + */ + readonly value: Output; + /** + * The non-existent issues. + */ + readonly issues?: undefined; + } + + /** + * The result interface if validation fails. + */ + export interface FailureResult { + /** + * The issues of failed validation. + */ + readonly issues: ReadonlyArray; + } + + /** + * The issue interface of the failure output. + */ + export interface Issue { + /** + * The error message of the issue. + */ + readonly message: string; + /** + * The path of the issue, if any. + */ + readonly path?: ReadonlyArray | undefined; + } + + /** + * The path segment interface of the issue. + */ + export interface PathSegment { + /** + * The key representing a path segment. + */ + readonly key: PropertyKey; + } + + /** + * The Standard Schema types interface. + */ + export interface Types { + /** + * The input type of the schema. + */ + readonly input: Input; + /** + * The output type of the schema. + */ + readonly output: Output; + } + + /** + * Infers the input type of a Standard Schema. + */ + export type InferInput = NonNullable["input"]; + + /** + * Infers the output type of a Standard Schema. + */ + export type InferOutput = NonNullable["output"]; + + // biome-ignore lint/complexity/noUselessEmptyExport: needed for granular visibility control of TS namespace + export {}; +} diff --git a/node_modules/zod/src/v3/tests/Mocker.ts b/node_modules/zod/src/v3/tests/Mocker.ts new file mode 100644 index 0000000..c9fbdd5 --- /dev/null +++ b/node_modules/zod/src/v3/tests/Mocker.ts @@ -0,0 +1,54 @@ +function getRandomInt(max: number) { + return Math.floor(Math.random() * Math.floor(max)); +} + +const testSymbol = Symbol("test"); + +export class Mocker { + pick = (...args: any[]): any => { + return args[getRandomInt(args.length)]; + }; + + get string(): string { + return Math.random().toString(36).substring(7); + } + get number(): number { + return Math.random() * 100; + } + get bigint(): bigint { + return BigInt(Math.floor(Math.random() * 10000)); + } + get boolean(): boolean { + return Math.random() < 0.5; + } + get date(): Date { + return new Date(Math.floor(Date.now() * Math.random())); + } + get symbol(): symbol { + return testSymbol; + } + get null(): null { + return null; + } + get undefined(): undefined { + return undefined; + } + get stringOptional(): string | undefined { + return this.pick(this.string, this.undefined); + } + get stringNullable(): string | null { + return this.pick(this.string, this.null); + } + get numberOptional(): number | undefined { + return this.pick(this.number, this.undefined); + } + get numberNullable(): number | null { + return this.pick(this.number, this.null); + } + get booleanOptional(): boolean | undefined { + return this.pick(this.boolean, this.undefined); + } + get booleanNullable(): boolean | null { + return this.pick(this.boolean, this.null); + } +} diff --git a/node_modules/zod/src/v3/tests/all-errors.test.ts b/node_modules/zod/src/v3/tests/all-errors.test.ts new file mode 100644 index 0000000..8fdf8f4 --- /dev/null +++ b/node_modules/zod/src/v3/tests/all-errors.test.ts @@ -0,0 +1,157 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; + +const Test = z.object({ + f1: z.number(), + f2: z.string().optional(), + f3: z.string().nullable(), + f4: z.array(z.object({ t: z.union([z.string(), z.boolean()]) })), +}); +type TestFlattenedErrors = z.inferFlattenedErrors; +type TestFormErrors = z.inferFlattenedErrors; + +test("default flattened errors type inference", () => { + type TestTypeErrors = { + formErrors: string[]; + fieldErrors: { [P in keyof z.TypeOf]?: string[] | undefined }; + }; + + util.assertEqual, TestTypeErrors>(true); + util.assertEqual, TestTypeErrors>(false); +}); + +test("custom flattened errors type inference", () => { + type ErrorType = { message: string; code: number }; + type TestTypeErrors = { + formErrors: ErrorType[]; + fieldErrors: { + [P in keyof z.TypeOf]?: ErrorType[] | undefined; + }; + }; + + util.assertEqual, TestTypeErrors>(false); + util.assertEqual, TestTypeErrors>(true); + util.assertEqual, TestTypeErrors>(false); +}); + +test("form errors type inference", () => { + type TestTypeErrors = { + formErrors: string[]; + fieldErrors: { [P in keyof z.TypeOf]?: string[] | undefined }; + }; + + util.assertEqual, TestTypeErrors>(true); +}); + +test(".flatten() type assertion", () => { + const parsed = Test.safeParse({}) as z.SafeParseError; + const validFlattenedErrors: TestFlattenedErrors = parsed.error.flatten(() => ({ message: "", code: 0 })); + // @ts-expect-error should fail assertion between `TestFlattenedErrors` and unmapped `flatten()`. + const invalidFlattenedErrors: TestFlattenedErrors = parsed.error.flatten(); + const validFormErrors: TestFormErrors = parsed.error.flatten(); + // @ts-expect-error should fail assertion between `TestFormErrors` and mapped `flatten()`. + const invalidFormErrors: TestFormErrors = parsed.error.flatten(() => ({ + message: "string", + code: 0, + })); + + [validFlattenedErrors, invalidFlattenedErrors, validFormErrors, invalidFormErrors]; +}); + +test(".formErrors type assertion", () => { + const parsed = Test.safeParse({}) as z.SafeParseError; + const validFormErrors: TestFormErrors = parsed.error.formErrors; + // @ts-expect-error should fail assertion between `TestFlattenedErrors` and `.formErrors`. + const invalidFlattenedErrors: TestFlattenedErrors = parsed.error.formErrors; + + [validFormErrors, invalidFlattenedErrors]; +}); + +test("all errors", () => { + const propertySchema = z.string(); + const schema = z + .object({ + a: propertySchema, + b: propertySchema, + }) + .refine( + (val) => { + return val.a === val.b; + }, + { message: "Must be equal" } + ); + + try { + schema.parse({ + a: "asdf", + b: "qwer", + }); + } catch (error) { + if (error instanceof z.ZodError) { + expect(error.flatten()).toEqual({ + formErrors: ["Must be equal"], + fieldErrors: {}, + }); + } + } + + try { + schema.parse({ + a: null, + b: null, + }); + } catch (_error) { + const error = _error as z.ZodError; + expect(error.flatten()).toEqual({ + formErrors: [], + fieldErrors: { + a: ["Expected string, received null"], + b: ["Expected string, received null"], + }, + }); + + expect(error.flatten((iss) => iss.message.toUpperCase())).toEqual({ + formErrors: [], + fieldErrors: { + a: ["EXPECTED STRING, RECEIVED NULL"], + b: ["EXPECTED STRING, RECEIVED NULL"], + }, + }); + // Test identity + + expect(error.flatten((i: z.ZodIssue) => i)).toEqual({ + formErrors: [], + fieldErrors: { + a: [ + { + code: "invalid_type", + expected: "string", + message: "Expected string, received null", + path: ["a"], + received: "null", + }, + ], + b: [ + { + code: "invalid_type", + expected: "string", + message: "Expected string, received null", + path: ["b"], + received: "null", + }, + ], + }, + }); + // Test mapping + expect(error.flatten((i: z.ZodIssue) => i.message.length)).toEqual({ + formErrors: [], + fieldErrors: { + a: ["Expected string, received null".length], + b: ["Expected string, received null".length], + }, + }); + } +}); diff --git a/node_modules/zod/src/v3/tests/anyunknown.test.ts b/node_modules/zod/src/v3/tests/anyunknown.test.ts new file mode 100644 index 0000000..49d07db --- /dev/null +++ b/node_modules/zod/src/v3/tests/anyunknown.test.ts @@ -0,0 +1,28 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; + +test("check any inference", () => { + const t1 = z.any(); + t1.optional(); + t1.nullable(); + type t1 = z.infer; + util.assertEqual(true); +}); + +test("check unknown inference", () => { + const t1 = z.unknown(); + t1.optional(); + t1.nullable(); + type t1 = z.infer; + util.assertEqual(true); +}); + +test("check never inference", () => { + const t1 = z.never(); + expect(() => t1.parse(undefined)).toThrow(); + expect(() => t1.parse("asdf")).toThrow(); + expect(() => t1.parse(null)).toThrow(); +}); diff --git a/node_modules/zod/src/v3/tests/array.test.ts b/node_modules/zod/src/v3/tests/array.test.ts new file mode 100644 index 0000000..df5b9d3 --- /dev/null +++ b/node_modules/zod/src/v3/tests/array.test.ts @@ -0,0 +1,71 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; + +const minTwo = z.string().array().min(2); +const maxTwo = z.string().array().max(2); +const justTwo = z.string().array().length(2); +const intNum = z.string().array().nonempty(); +const nonEmptyMax = z.string().array().nonempty().max(2); + +type t1 = z.infer; +util.assertEqual<[string, ...string[]], t1>(true); + +type t2 = z.infer; +util.assertEqual(true); + +test("passing validations", () => { + minTwo.parse(["a", "a"]); + minTwo.parse(["a", "a", "a"]); + maxTwo.parse(["a", "a"]); + maxTwo.parse(["a"]); + justTwo.parse(["a", "a"]); + intNum.parse(["a"]); + nonEmptyMax.parse(["a"]); +}); + +test("failing validations", () => { + expect(() => minTwo.parse(["a"])).toThrow(); + expect(() => maxTwo.parse(["a", "a", "a"])).toThrow(); + expect(() => justTwo.parse(["a"])).toThrow(); + expect(() => justTwo.parse(["a", "a", "a"])).toThrow(); + expect(() => intNum.parse([])).toThrow(); + expect(() => nonEmptyMax.parse([])).toThrow(); + expect(() => nonEmptyMax.parse(["a", "a", "a"])).toThrow(); +}); + +test("parse empty array in nonempty", () => { + expect(() => + z + .array(z.string()) + .nonempty() + .parse([] as any) + ).toThrow(); +}); + +test("get element", () => { + justTwo.element.parse("asdf"); + expect(() => justTwo.element.parse(12)).toThrow(); +}); + +test("continue parsing despite array size error", () => { + const schema = z.object({ + people: z.string().array().min(2), + }); + + const result = schema.safeParse({ + people: [123], + }); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues.length).toEqual(2); + } +}); + +test("parse should fail given sparse array", () => { + const schema = z.array(z.string()).nonempty().min(1).max(3); + + expect(() => schema.parse(new Array(3))).toThrow(); +}); diff --git a/node_modules/zod/src/v3/tests/async-parsing.test.ts b/node_modules/zod/src/v3/tests/async-parsing.test.ts new file mode 100644 index 0000000..01dbc4f --- /dev/null +++ b/node_modules/zod/src/v3/tests/async-parsing.test.ts @@ -0,0 +1,388 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +/// string +const stringSchema = z.string(); + +test("string async parse", async () => { + const goodData = "XXX"; + const badData = 12; + + const goodResult = await stringSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await stringSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// number +const numberSchema = z.number(); +test("number async parse", async () => { + const goodData = 1234.2353; + const badData = "1234"; + + const goodResult = await numberSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await numberSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// bigInt +const bigIntSchema = z.bigint(); +test("bigInt async parse", async () => { + const goodData = BigInt(145); + const badData = 134; + + const goodResult = await bigIntSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await bigIntSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// boolean +const booleanSchema = z.boolean(); +test("boolean async parse", async () => { + const goodData = true; + const badData = 1; + + const goodResult = await booleanSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await booleanSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// date +const dateSchema = z.date(); +test("date async parse", async () => { + const goodData = new Date(); + const badData = new Date().toISOString(); + + const goodResult = await dateSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await dateSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// undefined +const undefinedSchema = z.undefined(); +test("undefined async parse", async () => { + const goodData = undefined; + const badData = "XXX"; + + const goodResult = await undefinedSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(undefined); + + const badResult = await undefinedSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// null +const nullSchema = z.null(); +test("null async parse", async () => { + const goodData = null; + const badData = undefined; + + const goodResult = await nullSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await nullSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// any +const anySchema = z.any(); +test("any async parse", async () => { + const goodData = [{}]; + // const badData = 'XXX'; + + const goodResult = await anySchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + // const badResult = await anySchema.safeParseAsync(badData); + // expect(badResult.success).toBe(false); + // if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// unknown +const unknownSchema = z.unknown(); +test("unknown async parse", async () => { + const goodData = ["asdf", 124, () => {}]; + // const badData = 'XXX'; + + const goodResult = await unknownSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + // const badResult = await unknownSchema.safeParseAsync(badData); + // expect(badResult.success).toBe(false); + // if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// void +const voidSchema = z.void(); +test("void async parse", async () => { + const goodData = undefined; + const badData = 0; + + const goodResult = await voidSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await voidSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// array +const arraySchema = z.array(z.string()); +test("array async parse", async () => { + const goodData = ["XXX"]; + const badData = "XXX"; + + const goodResult = await arraySchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await arraySchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// object +const objectSchema = z.object({ string: z.string() }); +test("object async parse", async () => { + const goodData = { string: "XXX" }; + const badData = { string: 12 }; + + const goodResult = await objectSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await objectSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// union +const unionSchema = z.union([z.string(), z.undefined()]); +test("union async parse", async () => { + const goodData = undefined; + const badData = null; + + const goodResult = await unionSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await unionSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// record +const recordSchema = z.record(z.object({})); +test("record async parse", async () => { + const goodData = { adsf: {}, asdf: {} }; + const badData = [{}]; + + const goodResult = await recordSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await recordSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// function +const functionSchema = z.function(); +test("function async parse", async () => { + const goodData = () => {}; + const badData = "XXX"; + + const goodResult = await functionSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(typeof goodResult.data).toEqual("function"); + + const badResult = await functionSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// literal +const literalSchema = z.literal("asdf"); +test("literal async parse", async () => { + const goodData = "asdf"; + const badData = "asdff"; + + const goodResult = await literalSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await literalSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// enum +const enumSchema = z.enum(["fish", "whale"]); +test("enum async parse", async () => { + const goodData = "whale"; + const badData = "leopard"; + + const goodResult = await enumSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await enumSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// nativeEnum +enum nativeEnumTest { + asdf = "qwer", +} +// @ts-ignore +const nativeEnumSchema = z.nativeEnum(nativeEnumTest); +test("nativeEnum async parse", async () => { + const goodData = nativeEnumTest.asdf; + const badData = "asdf"; + + const goodResult = await nativeEnumSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await nativeEnumSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// promise +const promiseSchema = z.promise(z.number()); +test("promise async parse good", async () => { + const goodData = Promise.resolve(123); + + const goodResult = await promiseSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) { + expect(goodResult.data).toBeInstanceOf(Promise); + const data = await goodResult.data; + expect(data).toEqual(123); + // expect(goodResult.data).resolves.toEqual(124); + // return goodResult.data; + } else { + throw new Error("success should be true"); + } +}); + +test("promise async parse bad", async () => { + const badData = Promise.resolve("XXX"); + const badResult = await promiseSchema.safeParseAsync(badData); + expect(badResult.success).toBe(true); + if (badResult.success) { + await expect(badResult.data).rejects.toBeInstanceOf(z.ZodError); + } else { + throw new Error("success should be true"); + } +}); + +test("async validation non-empty strings", async () => { + const base = z.object({ + hello: z.string().refine((x) => x && x.length > 0), + foo: z.string().refine((x) => x && x.length > 0), + }); + + const testval = { hello: "", foo: "" }; + const result1 = base.safeParse(testval); + const result2 = base.safeParseAsync(testval); + + const r1 = result1; + await result2.then((r2) => { + if (r1.success === false && r2.success === false) expect(r1.error.issues.length).toBe(r2.error.issues.length); // <--- r1 has length 2, r2 has length 1 + }); +}); + +test("async validation multiple errors 1", async () => { + const base = z.object({ + hello: z.string(), + foo: z.number(), + }); + + const testval = { hello: 3, foo: "hello" }; + const result1 = base.safeParse(testval); + const result2 = base.safeParseAsync(testval); + + const r1 = result1; + await result2.then((r2) => { + if (r1.success === false && r2.success === false) expect(r2.error.issues.length).toBe(r1.error.issues.length); + }); +}); + +test("async validation multiple errors 2", async () => { + const base = (is_async?: boolean) => + z.object({ + hello: z.string(), + foo: z.object({ + bar: z.number().refine(is_async ? async () => false : () => false), + }), + }); + + const testval = { hello: 3, foo: { bar: 4 } }; + const result1 = base().safeParse(testval); + const result2 = base(true).safeParseAsync(testval); + + const r1 = result1; + await result2.then((r2) => { + if (r1.success === false && r2.success === false) expect(r2.error.issues.length).toBe(r1.error.issues.length); + }); +}); + +test("ensure early async failure prevents follow-up refinement checks", async () => { + let count = 0; + const base = z.object({ + hello: z.string(), + foo: z + .number() + .refine(async () => { + count++; + return true; + }) + .refine(async () => { + count++; + return true; + }, "Good"), + }); + + const testval = { hello: "bye", foo: 3 }; + const result = await base.safeParseAsync(testval); + if (result.success === false) { + expect(result.error.issues.length).toBe(1); + expect(count).toBe(1); + } + + // await result.then((r) => { + // if (r.success === false) expect(r.error.issues.length).toBe(1); + // expect(count).toBe(2); + // }); +}); diff --git a/node_modules/zod/src/v3/tests/async-refinements.test.ts b/node_modules/zod/src/v3/tests/async-refinements.test.ts new file mode 100644 index 0000000..509475d --- /dev/null +++ b/node_modules/zod/src/v3/tests/async-refinements.test.ts @@ -0,0 +1,46 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +test("parse async test", async () => { + const schema1 = z.string().refine(async (_val) => false); + expect(() => schema1.parse("asdf")).toThrow(); + + const schema2 = z.string().refine((_val) => Promise.resolve(true)); + return await expect(() => schema2.parse("asdf")).toThrow(); +}); + +test("parseAsync async test", async () => { + const schema1 = z.string().refine(async (_val) => true); + await schema1.parseAsync("asdf"); + + const schema2 = z.string().refine(async (_val) => false); + return await expect(schema2.parseAsync("asdf")).rejects.toBeDefined(); + // expect(async () => await schema2.parseAsync('asdf')).toThrow(); +}); + +test("parseAsync async test", async () => { + // expect.assertions(2); + + const schema1 = z.string().refine((_val) => Promise.resolve(true)); + const v1 = await schema1.parseAsync("asdf"); + expect(v1).toEqual("asdf"); + + const schema2 = z.string().refine((_val) => Promise.resolve(false)); + await expect(schema2.parseAsync("asdf")).rejects.toBeDefined(); + + const schema3 = z.string().refine((_val) => Promise.resolve(true)); + await expect(schema3.parseAsync("asdf")).resolves.toEqual("asdf"); + return await expect(schema3.parseAsync("qwer")).resolves.toEqual("qwer"); +}); + +test("parseAsync async with value", async () => { + const schema1 = z.string().refine(async (val) => { + return val.length > 5; + }); + await expect(schema1.parseAsync("asdf")).rejects.toBeDefined(); + + const v = await schema1.parseAsync("asdf123"); + return await expect(v).toEqual("asdf123"); +}); diff --git a/node_modules/zod/src/v3/tests/base.test.ts b/node_modules/zod/src/v3/tests/base.test.ts new file mode 100644 index 0000000..ab743d5 --- /dev/null +++ b/node_modules/zod/src/v3/tests/base.test.ts @@ -0,0 +1,29 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; + +test("type guard", () => { + const stringToNumber = z.string().transform((arg) => arg.length); + + const s1 = z.object({ + stringToNumber, + }); + type t1 = z.input; + + const data = { stringToNumber: "asdf" }; + const parsed = s1.safeParse(data); + if (parsed.success) { + util.assertEqual(true); + } +}); + +test("test this binding", () => { + const callback = (predicate: (val: string) => boolean) => { + return predicate("hello"); + }; + + expect(callback((value) => z.string().safeParse(value).success)).toBe(true); // true + expect(callback((value) => z.string().safeParse(value).success)).toBe(true); // true +}); diff --git a/node_modules/zod/src/v3/tests/bigint.test.ts b/node_modules/zod/src/v3/tests/bigint.test.ts new file mode 100644 index 0000000..9692f57 --- /dev/null +++ b/node_modules/zod/src/v3/tests/bigint.test.ts @@ -0,0 +1,55 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +const gtFive = z.bigint().gt(BigInt(5)); +const gteFive = z.bigint().gte(BigInt(5)); +const ltFive = z.bigint().lt(BigInt(5)); +const lteFive = z.bigint().lte(BigInt(5)); +const positive = z.bigint().positive(); +const negative = z.bigint().negative(); +const nonnegative = z.bigint().nonnegative(); +const nonpositive = z.bigint().nonpositive(); +const multipleOfFive = z.bigint().multipleOf(BigInt(5)); + +test("passing validations", () => { + z.bigint().parse(BigInt(1)); + z.bigint().parse(BigInt(0)); + z.bigint().parse(BigInt(-1)); + gtFive.parse(BigInt(6)); + gteFive.parse(BigInt(5)); + gteFive.parse(BigInt(6)); + ltFive.parse(BigInt(4)); + lteFive.parse(BigInt(5)); + lteFive.parse(BigInt(4)); + positive.parse(BigInt(3)); + negative.parse(BigInt(-2)); + nonnegative.parse(BigInt(0)); + nonnegative.parse(BigInt(7)); + nonpositive.parse(BigInt(0)); + nonpositive.parse(BigInt(-12)); + multipleOfFive.parse(BigInt(15)); +}); + +test("failing validations", () => { + expect(() => gtFive.parse(BigInt(5))).toThrow(); + expect(() => gteFive.parse(BigInt(4))).toThrow(); + expect(() => ltFive.parse(BigInt(5))).toThrow(); + expect(() => lteFive.parse(BigInt(6))).toThrow(); + expect(() => positive.parse(BigInt(0))).toThrow(); + expect(() => positive.parse(BigInt(-2))).toThrow(); + expect(() => negative.parse(BigInt(0))).toThrow(); + expect(() => negative.parse(BigInt(3))).toThrow(); + expect(() => nonnegative.parse(BigInt(-1))).toThrow(); + expect(() => nonpositive.parse(BigInt(1))).toThrow(); + expect(() => multipleOfFive.parse(BigInt(13))).toThrow(); +}); + +test("min max getters", () => { + expect(z.bigint().min(BigInt(5)).minValue).toEqual(BigInt(5)); + expect(z.bigint().min(BigInt(5)).min(BigInt(10)).minValue).toEqual(BigInt(10)); + + expect(z.bigint().max(BigInt(5)).maxValue).toEqual(BigInt(5)); + expect(z.bigint().max(BigInt(5)).max(BigInt(1)).maxValue).toEqual(BigInt(1)); +}); diff --git a/node_modules/zod/src/v3/tests/branded.test.ts b/node_modules/zod/src/v3/tests/branded.test.ts new file mode 100644 index 0000000..b19786c --- /dev/null +++ b/node_modules/zod/src/v3/tests/branded.test.ts @@ -0,0 +1,53 @@ +// @ts-ignore TS6133 +import { test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; + +test("branded types", () => { + const mySchema = z + .object({ + name: z.string(), + }) + .brand<"superschema">(); + + // simple branding + type MySchema = z.infer; + util.assertEqual(true); + + const doStuff = (arg: MySchema) => arg; + doStuff(mySchema.parse({ name: "hello there" })); + + // inheritance + const extendedSchema = mySchema.brand<"subschema">(); + type ExtendedSchema = z.infer; + util.assertEqual & z.BRAND<"subschema">>(true); + + doStuff(extendedSchema.parse({ name: "hello again" })); + + // number branding + const numberSchema = z.number().brand<42>(); + type NumberSchema = z.infer; + util.assertEqual(true); + + // symbol branding + const MyBrand: unique symbol = Symbol("hello"); + type MyBrand = typeof MyBrand; + const symbolBrand = z.number().brand<"sup">().brand(); + type SymbolBrand = z.infer; + // number & { [z.BRAND]: { sup: true, [MyBrand]: true } } + util.assertEqual & z.BRAND>(true); + + // keeping brands out of input types + const age = z.number().brand<"age">(); + + type Age = z.infer; + type AgeInput = z.input; + + util.assertEqual(false); + util.assertEqual(true); + util.assertEqual, Age>(true); + + // @ts-expect-error + doStuff({ name: "hello there!" }); +}); diff --git a/node_modules/zod/src/v3/tests/catch.test.ts b/node_modules/zod/src/v3/tests/catch.test.ts new file mode 100644 index 0000000..94d12aa --- /dev/null +++ b/node_modules/zod/src/v3/tests/catch.test.ts @@ -0,0 +1,220 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import { z } from "zod/v3"; +import { util } from "../helpers/util.js"; + +test("basic catch", () => { + expect(z.string().catch("default").parse(undefined)).toBe("default"); +}); + +test("catch fn does not run when parsing succeeds", () => { + let isCalled = false; + const cb = () => { + isCalled = true; + return "asdf"; + }; + expect(z.string().catch(cb).parse("test")).toBe("test"); + expect(isCalled).toEqual(false); +}); + +test("basic catch async", async () => { + const result = await z.string().catch("default").parseAsync(1243); + expect(result).toBe("default"); +}); + +test("catch replace wrong types", () => { + expect(z.string().catch("default").parse(true)).toBe("default"); + expect(z.string().catch("default").parse(true)).toBe("default"); + expect(z.string().catch("default").parse(15)).toBe("default"); + expect(z.string().catch("default").parse([])).toBe("default"); + expect(z.string().catch("default").parse(new Map())).toBe("default"); + expect(z.string().catch("default").parse(new Set())).toBe("default"); + expect(z.string().catch("default").parse({})).toBe("default"); +}); + +test("catch with transform", () => { + const stringWithDefault = z + .string() + .transform((val) => val.toUpperCase()) + .catch("default"); + expect(stringWithDefault.parse(undefined)).toBe("default"); + expect(stringWithDefault.parse(15)).toBe("default"); + expect(stringWithDefault).toBeInstanceOf(z.ZodCatch); + expect(stringWithDefault._def.innerType).toBeInstanceOf(z.ZodEffects); + expect(stringWithDefault._def.innerType._def.schema).toBeInstanceOf(z.ZodSchema); + + type inp = z.input; + util.assertEqual(true); + type out = z.output; + util.assertEqual(true); +}); + +test("catch on existing optional", () => { + const stringWithDefault = z.string().optional().catch("asdf"); + expect(stringWithDefault.parse(undefined)).toBe(undefined); + expect(stringWithDefault.parse(15)).toBe("asdf"); + expect(stringWithDefault).toBeInstanceOf(z.ZodCatch); + expect(stringWithDefault._def.innerType).toBeInstanceOf(z.ZodOptional); + expect(stringWithDefault._def.innerType._def.innerType).toBeInstanceOf(z.ZodString); + + type inp = z.input; + util.assertEqual(true); + type out = z.output; + util.assertEqual(true); +}); + +test("optional on catch", () => { + const stringWithDefault = z.string().catch("asdf").optional(); + + type inp = z.input; + util.assertEqual(true); + type out = z.output; + util.assertEqual(true); +}); + +test("complex chain example", () => { + const complex = z + .string() + .catch("asdf") + .transform((val) => val + "!") + .transform((val) => val.toUpperCase()) + .catch("qwer") + .removeCatch() + .optional() + .catch("asdfasdf"); + + expect(complex.parse("qwer")).toBe("QWER!"); + expect(complex.parse(15)).toBe("ASDF!"); + expect(complex.parse(true)).toBe("ASDF!"); +}); + +test("removeCatch", () => { + const stringWithRemovedDefault = z.string().catch("asdf").removeCatch(); + + type out = z.output; + util.assertEqual(true); +}); + +test("nested", () => { + const inner = z.string().catch("asdf"); + const outer = z.object({ inner }).catch({ + inner: "asdf", + }); + type input = z.input; + util.assertEqual(true); + type out = z.output; + util.assertEqual(true); + expect(outer.parse(undefined)).toEqual({ inner: "asdf" }); + expect(outer.parse({})).toEqual({ inner: "asdf" }); + expect(outer.parse({ inner: undefined })).toEqual({ inner: "asdf" }); +}); + +test("chained catch", () => { + const stringWithDefault = z.string().catch("inner").catch("outer"); + const result = stringWithDefault.parse(undefined); + expect(result).toEqual("inner"); + const resultDiff = stringWithDefault.parse(5); + expect(resultDiff).toEqual("inner"); +}); + +test("factory", () => { + z.ZodCatch.create(z.string(), { + catch: "asdf", + }).parse(undefined); +}); + +test("native enum", () => { + enum Fruits { + apple = "apple", + orange = "orange", + } + + const schema = z.object({ + fruit: z.nativeEnum(Fruits).catch(Fruits.apple), + }); + + expect(schema.parse({})).toEqual({ fruit: Fruits.apple }); + expect(schema.parse({ fruit: 15 })).toEqual({ fruit: Fruits.apple }); +}); + +test("enum", () => { + const schema = z.object({ + fruit: z.enum(["apple", "orange"]).catch("apple"), + }); + + expect(schema.parse({})).toEqual({ fruit: "apple" }); + expect(schema.parse({ fruit: true })).toEqual({ fruit: "apple" }); + expect(schema.parse({ fruit: 15 })).toEqual({ fruit: "apple" }); +}); + +test("reported issues with nested usage", () => { + const schema = z.object({ + string: z.string(), + obj: z.object({ + sub: z.object({ + lit: z.literal("a"), + subCatch: z.number().catch(23), + }), + midCatch: z.number().catch(42), + }), + number: z.number().catch(0), + bool: z.boolean(), + }); + + try { + schema.parse({ + string: {}, + obj: { + sub: { + lit: "b", + subCatch: "24", + }, + midCatch: 444, + }, + number: "", + bool: "yes", + }); + } catch (error) { + const issues = (error as z.ZodError).issues; + + expect(issues.length).toEqual(3); + expect(issues[0].message).toMatch("string"); + expect(issues[1].message).toMatch("literal"); + expect(issues[2].message).toMatch("boolean"); + } +}); + +test("catch error", () => { + let catchError: z.ZodError | undefined = undefined; + + const schema = z.object({ + age: z.number(), + name: z.string().catch((ctx) => { + catchError = ctx.error; + + return "John Doe"; + }), + }); + + const result = schema.safeParse({ + age: null, + name: null, + }); + + expect(result.success).toEqual(false); + expect(!result.success && result.error.issues.length).toEqual(1); + expect(!result.success && result.error.issues[0].message).toMatch("number"); + + expect(catchError).toBeInstanceOf(z.ZodError); + expect(catchError !== undefined && (catchError as z.ZodError).issues.length).toEqual(1); + expect(catchError !== undefined && (catchError as z.ZodError).issues[0].message).toMatch("string"); +}); + +test("ctx.input", () => { + const schema = z.string().catch((ctx) => { + return String(ctx.input); + }); + + expect(schema.parse(123)).toEqual("123"); +}); diff --git a/node_modules/zod/src/v3/tests/coerce.test.ts b/node_modules/zod/src/v3/tests/coerce.test.ts new file mode 100644 index 0000000..1f53004 --- /dev/null +++ b/node_modules/zod/src/v3/tests/coerce.test.ts @@ -0,0 +1,133 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +test("string coercion", () => { + const schema = z.coerce.string(); + expect(schema.parse("sup")).toEqual("sup"); + expect(schema.parse("")).toEqual(""); + expect(schema.parse(12)).toEqual("12"); + expect(schema.parse(0)).toEqual("0"); + expect(schema.parse(-12)).toEqual("-12"); + expect(schema.parse(3.14)).toEqual("3.14"); + expect(schema.parse(BigInt(15))).toEqual("15"); + expect(schema.parse(Number.NaN)).toEqual("NaN"); + expect(schema.parse(Number.POSITIVE_INFINITY)).toEqual("Infinity"); + expect(schema.parse(Number.NEGATIVE_INFINITY)).toEqual("-Infinity"); + expect(schema.parse(true)).toEqual("true"); + expect(schema.parse(false)).toEqual("false"); + expect(schema.parse(null)).toEqual("null"); + expect(schema.parse(undefined)).toEqual("undefined"); + expect(schema.parse({ hello: "world!" })).toEqual("[object Object]"); + expect(schema.parse(["item", "another_item"])).toEqual("item,another_item"); + expect(schema.parse([])).toEqual(""); + expect(schema.parse(new Date("2022-01-01T00:00:00.000Z"))).toEqual(new Date("2022-01-01T00:00:00.000Z").toString()); +}); + +test("number coercion", () => { + const schema = z.coerce.number(); + expect(schema.parse("12")).toEqual(12); + expect(schema.parse("0")).toEqual(0); + expect(schema.parse("-12")).toEqual(-12); + expect(schema.parse("3.14")).toEqual(3.14); + expect(schema.parse("")).toEqual(0); + expect(() => schema.parse("NOT_A_NUMBER")).toThrow(); // z.ZodError + expect(schema.parse(12)).toEqual(12); + expect(schema.parse(0)).toEqual(0); + expect(schema.parse(-12)).toEqual(-12); + expect(schema.parse(3.14)).toEqual(3.14); + expect(schema.parse(BigInt(15))).toEqual(15); + expect(() => schema.parse(Number.NaN)).toThrow(); // z.ZodError + expect(schema.parse(Number.POSITIVE_INFINITY)).toEqual(Number.POSITIVE_INFINITY); + expect(schema.parse(Number.NEGATIVE_INFINITY)).toEqual(Number.NEGATIVE_INFINITY); + expect(schema.parse(true)).toEqual(1); + expect(schema.parse(false)).toEqual(0); + expect(schema.parse(null)).toEqual(0); + expect(() => schema.parse(undefined)).toThrow(); // z.ZodError + expect(() => schema.parse({ hello: "world!" })).toThrow(); // z.ZodError + expect(() => schema.parse(["item", "another_item"])).toThrow(); // z.ZodError + expect(schema.parse([])).toEqual(0); + expect(schema.parse(new Date(1670139203496))).toEqual(1670139203496); +}); + +test("boolean coercion", () => { + const schema = z.coerce.boolean(); + expect(schema.parse("true")).toEqual(true); + expect(schema.parse("false")).toEqual(true); + expect(schema.parse("0")).toEqual(true); + expect(schema.parse("1")).toEqual(true); + expect(schema.parse("")).toEqual(false); + expect(schema.parse(1)).toEqual(true); + expect(schema.parse(0)).toEqual(false); + expect(schema.parse(-1)).toEqual(true); + expect(schema.parse(3.14)).toEqual(true); + expect(schema.parse(BigInt(15))).toEqual(true); + expect(schema.parse(Number.NaN)).toEqual(false); + expect(schema.parse(Number.POSITIVE_INFINITY)).toEqual(true); + expect(schema.parse(Number.NEGATIVE_INFINITY)).toEqual(true); + expect(schema.parse(true)).toEqual(true); + expect(schema.parse(false)).toEqual(false); + expect(schema.parse(null)).toEqual(false); + expect(schema.parse(undefined)).toEqual(false); + expect(schema.parse({ hello: "world!" })).toEqual(true); + expect(schema.parse(["item", "another_item"])).toEqual(true); + expect(schema.parse([])).toEqual(true); + expect(schema.parse(new Date(1670139203496))).toEqual(true); +}); + +test("bigint coercion", () => { + const schema = z.coerce.bigint(); + expect(schema.parse("5")).toEqual(BigInt(5)); + expect(schema.parse("0")).toEqual(BigInt(0)); + expect(schema.parse("-5")).toEqual(BigInt(-5)); + expect(() => schema.parse("3.14")).toThrow(); // not a z.ZodError! + expect(schema.parse("")).toEqual(BigInt(0)); + expect(() => schema.parse("NOT_A_NUMBER")).toThrow(); // not a z.ZodError! + expect(schema.parse(5)).toEqual(BigInt(5)); + expect(schema.parse(0)).toEqual(BigInt(0)); + expect(schema.parse(-5)).toEqual(BigInt(-5)); + expect(() => schema.parse(3.14)).toThrow(); // not a z.ZodError! + expect(schema.parse(BigInt(5))).toEqual(BigInt(5)); + expect(() => schema.parse(Number.NaN)).toThrow(); // not a z.ZodError! + expect(() => schema.parse(Number.POSITIVE_INFINITY)).toThrow(); // not a z.ZodError! + expect(() => schema.parse(Number.NEGATIVE_INFINITY)).toThrow(); // not a z.ZodError! + expect(schema.parse(true)).toEqual(BigInt(1)); + expect(schema.parse(false)).toEqual(BigInt(0)); + expect(() => schema.parse(null)).toThrow(); // not a z.ZodError! + expect(() => schema.parse(undefined)).toThrow(); // not a z.ZodError! + expect(() => schema.parse({ hello: "world!" })).toThrow(); // not a z.ZodError! + expect(() => schema.parse(["item", "another_item"])).toThrow(); // not a z.ZodError! + expect(schema.parse([])).toEqual(BigInt(0)); + expect(schema.parse(new Date(1670139203496))).toEqual(BigInt(1670139203496)); +}); + +test("date coercion", () => { + const schema = z.coerce.date(); + expect(schema.parse(new Date().toDateString())).toBeInstanceOf(Date); + expect(schema.parse(new Date().toISOString())).toBeInstanceOf(Date); + expect(schema.parse(new Date().toUTCString())).toBeInstanceOf(Date); + expect(schema.parse("5")).toBeInstanceOf(Date); + expect(schema.parse("2000-01-01")).toBeInstanceOf(Date); + // expect(schema.parse("0")).toBeInstanceOf(Date); + // expect(schema.parse("-5")).toBeInstanceOf(Date); + // expect(schema.parse("3.14")).toBeInstanceOf(Date); + expect(() => schema.parse("")).toThrow(); // z.ZodError + expect(() => schema.parse("NOT_A_DATE")).toThrow(); // z.ZodError + expect(schema.parse(5)).toBeInstanceOf(Date); + expect(schema.parse(0)).toBeInstanceOf(Date); + expect(schema.parse(-5)).toBeInstanceOf(Date); + expect(schema.parse(3.14)).toBeInstanceOf(Date); + expect(() => schema.parse(BigInt(5))).toThrow(); // not a z.ZodError! + expect(() => schema.parse(Number.NaN)).toThrow(); // z.ZodError + expect(() => schema.parse(Number.POSITIVE_INFINITY)).toThrow(); // z.ZodError + expect(() => schema.parse(Number.NEGATIVE_INFINITY)).toThrow(); // z.ZodError + expect(schema.parse(true)).toBeInstanceOf(Date); + expect(schema.parse(false)).toBeInstanceOf(Date); + expect(schema.parse(null)).toBeInstanceOf(Date); + expect(() => schema.parse(undefined)).toThrow(); // z.ZodError + expect(() => schema.parse({ hello: "world!" })).toThrow(); // z.ZodError + expect(() => schema.parse(["item", "another_item"])).toThrow(); // z.ZodError + expect(() => schema.parse([])).toThrow(); // z.ZodError + expect(schema.parse(new Date())).toBeInstanceOf(Date); +}); diff --git a/node_modules/zod/src/v3/tests/complex.test.ts b/node_modules/zod/src/v3/tests/complex.test.ts new file mode 100644 index 0000000..7807b2b --- /dev/null +++ b/node_modules/zod/src/v3/tests/complex.test.ts @@ -0,0 +1,56 @@ +import { test } from "vitest"; +import * as z from "zod/v3"; + +const crazySchema = z.object({ + tuple: z.tuple([ + z.string().nullable().optional(), + z.number().nullable().optional(), + z.boolean().nullable().optional(), + z.null().nullable().optional(), + z.undefined().nullable().optional(), + z.literal("1234").nullable().optional(), + ]), + merged: z + .object({ + k1: z.string().optional(), + }) + .merge(z.object({ k1: z.string().nullable(), k2: z.number() })), + union: z.array(z.union([z.literal("asdf"), z.literal(12)])).nonempty(), + array: z.array(z.number()), + // sumTransformer: z.transformer(z.array(z.number()), z.number(), (arg) => { + // return arg.reduce((a, b) => a + b, 0); + // }), + sumMinLength: z.array(z.number()).refine((arg) => arg.length > 5), + intersection: z.intersection(z.object({ p1: z.string().optional() }), z.object({ p1: z.number().optional() })), + enum: z.intersection(z.enum(["zero", "one"]), z.enum(["one", "two"])), + nonstrict: z.object({ points: z.number() }).nonstrict(), + numProm: z.promise(z.number()), + lenfun: z.function(z.tuple([z.string()]), z.boolean()), +}); + +// const asyncCrazySchema = crazySchema.extend({ +// // async_transform: z.transformer( +// // z.array(z.number()), +// // z.number(), +// // async (arg) => { +// // return arg.reduce((a, b) => a + b, 0); +// // } +// // ), +// async_refine: z.array(z.number()).refine(async (arg) => arg.length > 5), +// }); + +test("parse", () => { + crazySchema.parse({ + tuple: ["asdf", 1234, true, null, undefined, "1234"], + merged: { k1: "asdf", k2: 12 }, + union: ["asdf", 12, "asdf", 12, "asdf", 12], + array: [12, 15, 16], + // sumTransformer: [12, 15, 16], + sumMinLength: [12, 15, 16, 98, 24, 63], + intersection: {}, + enum: "one", + nonstrict: { points: 1234 }, + numProm: Promise.resolve(12), + lenfun: (x: string) => x.length, + }); +}); diff --git a/node_modules/zod/src/v3/tests/custom.test.ts b/node_modules/zod/src/v3/tests/custom.test.ts new file mode 100644 index 0000000..b24b676 --- /dev/null +++ b/node_modules/zod/src/v3/tests/custom.test.ts @@ -0,0 +1,31 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +test("passing validations", () => { + const example1 = z.custom((x) => typeof x === "number"); + example1.parse(1234); + expect(() => example1.parse({})).toThrow(); +}); + +test("string params", () => { + const example1 = z.custom((x) => typeof x !== "number", "customerr"); + const result = example1.safeParse(1234); + expect(result.success).toEqual(false); + // @ts-ignore + expect(JSON.stringify(result.error).includes("customerr")).toEqual(true); +}); + +test("async validations", async () => { + const example1 = z.custom(async (x) => { + return typeof x === "number"; + }); + const r1 = await example1.safeParseAsync(1234); + expect(r1.success).toEqual(true); + expect(r1.data).toEqual(1234); + + const r2 = await example1.safeParseAsync("asdf"); + expect(r2.success).toEqual(false); + expect(r2.error!.issues.length).toEqual(1); +}); diff --git a/node_modules/zod/src/v3/tests/date.test.ts b/node_modules/zod/src/v3/tests/date.test.ts new file mode 100644 index 0000000..c86dc84 --- /dev/null +++ b/node_modules/zod/src/v3/tests/date.test.ts @@ -0,0 +1,32 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +const beforeBenchmarkDate = new Date(2022, 10, 4); +const benchmarkDate = new Date(2022, 10, 5); +const afterBenchmarkDate = new Date(2022, 10, 6); + +const minCheck = z.date().min(benchmarkDate); +const maxCheck = z.date().max(benchmarkDate); + +test("passing validations", () => { + minCheck.parse(benchmarkDate); + minCheck.parse(afterBenchmarkDate); + + maxCheck.parse(benchmarkDate); + maxCheck.parse(beforeBenchmarkDate); +}); + +test("failing validations", () => { + expect(() => minCheck.parse(beforeBenchmarkDate)).toThrow(); + expect(() => maxCheck.parse(afterBenchmarkDate)).toThrow(); +}); + +test("min max getters", () => { + expect(minCheck.minDate).toEqual(benchmarkDate); + expect(minCheck.min(afterBenchmarkDate).minDate).toEqual(afterBenchmarkDate); + + expect(maxCheck.maxDate).toEqual(benchmarkDate); + expect(maxCheck.max(beforeBenchmarkDate).maxDate).toEqual(beforeBenchmarkDate); +}); diff --git a/node_modules/zod/src/v3/tests/deepmasking.test.ts b/node_modules/zod/src/v3/tests/deepmasking.test.ts new file mode 100644 index 0000000..d707e79 --- /dev/null +++ b/node_modules/zod/src/v3/tests/deepmasking.test.ts @@ -0,0 +1,186 @@ +// @ts-ignore TS6133 +import { test } from "vitest"; + +import * as z from "zod/v3"; + +test("test", () => { + z; +}); + +// const fish = z.object({ +// name: z.string(), +// props: z.object({ +// color: z.string(), +// numScales: z.number(), +// }), +// }); + +// const nonStrict = z +// .object({ +// name: z.string(), +// color: z.string(), +// }) +// .nonstrict(); + +// test('object pick type', () => { +// const modNonStrictFish = nonStrict.omit({ name: true }); +// modNonStrictFish.parse({ color: 'asdf' }); + +// const bad1 = () => fish.pick({ props: { unknown: true } } as any); +// const bad2 = () => fish.omit({ name: true, props: { unknown: true } } as any); + +// expect(bad1).toThrow(); +// expect(bad2).toThrow(); +// }); + +// test('f1', () => { +// const f1 = fish.pick(true); +// f1.parse({ name: 'a', props: { color: 'b', numScales: 3 } }); +// }); +// test('f2', () => { +// const f2 = fish.pick({ props: true }); +// f2.parse({ props: { color: 'asdf', numScales: 1 } }); +// const badcheck2 = () => f2.parse({ name: 'a', props: { color: 'b', numScales: 3 } } as any); +// expect(badcheck2).toThrow(); +// }); +// test('f3', () => { +// const f3 = fish.pick({ props: { color: true } }); +// f3.parse({ props: { color: 'b' } }); +// const badcheck3 = () => f3.parse({ name: 'a', props: { color: 'b', numScales: 3 } } as any); +// expect(badcheck3).toThrow(); +// }); +// test('f4', () => { +// const badcheck4 = () => fish.pick({ props: { color: true, unknown: true } }); +// expect(badcheck4).toThrow(); +// }); +// test('f6', () => { +// const f6 = fish.omit({ props: true }); +// const badcheck6 = () => f6.parse({ name: 'a', props: { color: 'b', numScales: 3 } } as any); +// f6.parse({ name: 'adsf' }); +// expect(badcheck6).toThrow(); +// }); +// test('f7', () => { +// const f7 = fish.omit({ props: { color: true } }); +// f7.parse({ name: 'a', props: { numScales: 3 } }); +// const badcheck7 = () => f7.parse({ name: 'a', props: { color: 'b', numScales: 3 } } as any); +// expect(badcheck7).toThrow(); +// }); +// test('f8', () => { +// const badcheck8 = () => fish.omit({ props: { color: true, unknown: true } }); +// expect(badcheck8).toThrow(); +// }); +// test('f9', () => { +// const f9 = nonStrict.pick(true); +// f9.parse({ name: 'a', color: 'asdf' }); +// }); +// test('f10', () => { +// const f10 = nonStrict.pick({ name: true }); +// f10.parse({ name: 'a' }); +// const val = f10.parse({ name: 'a', color: 'b' }); +// expect(val).toEqual({ name: 'a' }); +// }); +// test('f12', () => { +// const badfcheck12 = () => nonStrict.omit({ color: true, asdf: true }); +// expect(badfcheck12).toThrow(); +// }); + +// test('array masking', () => { +// const fishArray = z.array(fish); +// const modFishArray = fishArray.pick({ +// name: true, +// props: { +// numScales: true, +// }, +// }); + +// modFishArray.parse([{ name: 'fish', props: { numScales: 12 } }]); +// const bad1 = () => modFishArray.parse([{ name: 'fish', props: { numScales: 12, color: 'asdf' } }] as any); +// expect(bad1).toThrow(); +// }); + +// test('array masking', () => { +// const fishArray = z.array(fish); +// const fail = () => +// fishArray.pick({ +// name: true, +// props: { +// whatever: true, +// }, +// } as any); +// expect(fail).toThrow(); +// }); + +// test('array masking', () => { +// const fishArray = z.array(fish); +// const fail = () => +// fishArray.omit({ +// whateve: true, +// } as any); +// expect(fail).toThrow(); +// }); + +// test('array masking', () => { +// const fishArray = z.array(fish); +// const modFishList = fishArray.omit({ +// name: true, +// props: { +// color: true, +// }, +// }); + +// modFishList.parse([{ props: { numScales: 12 } }]); +// const fail = () => modFishList.parse([{ name: 'hello', props: { numScales: 12 } }] as any); +// expect(fail).toThrow(); +// }); + +// test('primitive array masking', () => { +// const fishArray = z.array(z.number()); +// const fail = () => fishArray.pick({} as any); +// expect(fail).toThrow(); +// }); + +// test('other array masking', () => { +// const fishArray = z.array(z.array(z.number())); +// const fail = () => fishArray.pick({} as any); +// expect(fail).toThrow(); +// }); + +// test('invalid mask #1', () => { +// const fail = () => fish.pick(1 as any); +// expect(fail).toThrow(); +// }); + +// test('invalid mask #2', () => { +// const fail = () => fish.pick([] as any); +// expect(fail).toThrow(); +// }); + +// test('invalid mask #3', () => { +// const fail = () => fish.pick(false as any); +// expect(fail).toThrow(); +// }); + +// test('invalid mask #4', () => { +// const fail = () => fish.pick('asdf' as any); +// expect(fail).toThrow(); +// }); + +// test('invalid mask #5', () => { +// const fail = () => fish.omit(1 as any); +// expect(fail).toThrow(); +// }); + +// test('invalid mask #6', () => { +// const fail = () => fish.omit([] as any); +// expect(fail).toThrow(); +// }); + +// test('invalid mask #7', () => { +// const fail = () => fish.omit(false as any); +// expect(fail).toThrow(); +// }); + +// test('invalid mask #8', () => { +// const fail = () => fish.omit('asdf' as any); +// expect(fail).toThrow(); +// }); diff --git a/node_modules/zod/src/v3/tests/default.test.ts b/node_modules/zod/src/v3/tests/default.test.ts new file mode 100644 index 0000000..29e007c --- /dev/null +++ b/node_modules/zod/src/v3/tests/default.test.ts @@ -0,0 +1,112 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import { z } from "zod/v3"; +import { util } from "../helpers/util.js"; + +test("basic defaults", () => { + expect(z.string().default("default").parse(undefined)).toBe("default"); +}); + +test("default with transform", () => { + const stringWithDefault = z + .string() + .transform((val) => val.toUpperCase()) + .default("default"); + expect(stringWithDefault.parse(undefined)).toBe("DEFAULT"); + expect(stringWithDefault).toBeInstanceOf(z.ZodDefault); + expect(stringWithDefault._def.innerType).toBeInstanceOf(z.ZodEffects); + expect(stringWithDefault._def.innerType._def.schema).toBeInstanceOf(z.ZodSchema); + + type inp = z.input; + util.assertEqual(true); + type out = z.output; + util.assertEqual(true); +}); + +test("default on existing optional", () => { + const stringWithDefault = z.string().optional().default("asdf"); + expect(stringWithDefault.parse(undefined)).toBe("asdf"); + expect(stringWithDefault).toBeInstanceOf(z.ZodDefault); + expect(stringWithDefault._def.innerType).toBeInstanceOf(z.ZodOptional); + expect(stringWithDefault._def.innerType._def.innerType).toBeInstanceOf(z.ZodString); + + type inp = z.input; + util.assertEqual(true); + type out = z.output; + util.assertEqual(true); +}); + +test("optional on default", () => { + const stringWithDefault = z.string().default("asdf").optional(); + + type inp = z.input; + util.assertEqual(true); + type out = z.output; + util.assertEqual(true); +}); + +test("complex chain example", () => { + const complex = z + .string() + .default("asdf") + .transform((val) => val.toUpperCase()) + .default("qwer") + .removeDefault() + .optional() + .default("asdfasdf"); + + expect(complex.parse(undefined)).toBe("ASDFASDF"); +}); + +test("removeDefault", () => { + const stringWithRemovedDefault = z.string().default("asdf").removeDefault(); + + type out = z.output; + util.assertEqual(true); +}); + +test("nested", () => { + const inner = z.string().default("asdf"); + const outer = z.object({ inner }).default({ + inner: undefined, + }); + type input = z.input; + util.assertEqual(true); + type out = z.output; + util.assertEqual(true); + expect(outer.parse(undefined)).toEqual({ inner: "asdf" }); + expect(outer.parse({})).toEqual({ inner: "asdf" }); + expect(outer.parse({ inner: undefined })).toEqual({ inner: "asdf" }); +}); + +test("chained defaults", () => { + const stringWithDefault = z.string().default("inner").default("outer"); + const result = stringWithDefault.parse(undefined); + expect(result).toEqual("outer"); +}); + +test("factory", () => { + expect(z.ZodDefault.create(z.string(), { default: "asdf" }).parse(undefined)).toEqual("asdf"); +}); + +test("native enum", () => { + enum Fruits { + apple = "apple", + orange = "orange", + } + + const schema = z.object({ + fruit: z.nativeEnum(Fruits).default(Fruits.apple), + }); + + expect(schema.parse({})).toEqual({ fruit: Fruits.apple }); +}); + +test("enum", () => { + const schema = z.object({ + fruit: z.enum(["apple", "orange"]).default("apple"), + }); + + expect(schema.parse({})).toEqual({ fruit: "apple" }); +}); diff --git a/node_modules/zod/src/v3/tests/description.test.ts b/node_modules/zod/src/v3/tests/description.test.ts new file mode 100644 index 0000000..1edaa1c --- /dev/null +++ b/node_modules/zod/src/v3/tests/description.test.ts @@ -0,0 +1,33 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +const description = "a description"; + +test("passing `description` to schema should add a description", () => { + expect(z.string({ description }).description).toEqual(description); + expect(z.number({ description }).description).toEqual(description); + expect(z.boolean({ description }).description).toEqual(description); +}); + +test("`.describe` should add a description", () => { + expect(z.string().describe(description).description).toEqual(description); + expect(z.number().describe(description).description).toEqual(description); + expect(z.boolean().describe(description).description).toEqual(description); +}); + +test("description should carry over to chained schemas", () => { + const schema = z.string({ description }); + expect(schema.description).toEqual(description); + expect(schema.optional().description).toEqual(description); + expect(schema.optional().nullable().default("default").description).toEqual(description); +}); + +test("description should not carry over to chained array schema", () => { + const schema = z.string().describe(description); + + expect(schema.description).toEqual(description); + expect(schema.array().description).toEqual(undefined); + expect(z.array(schema).description).toEqual(undefined); +}); diff --git a/node_modules/zod/src/v3/tests/discriminated-unions.test.ts b/node_modules/zod/src/v3/tests/discriminated-unions.test.ts new file mode 100644 index 0000000..7fb5cfe --- /dev/null +++ b/node_modules/zod/src/v3/tests/discriminated-unions.test.ts @@ -0,0 +1,315 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +test("valid", () => { + expect( + z + .discriminatedUnion("type", [ + z.object({ type: z.literal("a"), a: z.string() }), + z.object({ type: z.literal("b"), b: z.string() }), + ]) + .parse({ type: "a", a: "abc" }) + ).toEqual({ type: "a", a: "abc" }); +}); + +test("valid - discriminator value of various primitive types", () => { + const schema = z.discriminatedUnion("type", [ + z.object({ type: z.literal("1"), val: z.literal(1) }), + z.object({ type: z.literal(1), val: z.literal(2) }), + z.object({ type: z.literal(BigInt(1)), val: z.literal(3) }), + z.object({ type: z.literal("true"), val: z.literal(4) }), + z.object({ type: z.literal(true), val: z.literal(5) }), + z.object({ type: z.literal("null"), val: z.literal(6) }), + z.object({ type: z.literal(null), val: z.literal(7) }), + z.object({ type: z.literal("undefined"), val: z.literal(8) }), + z.object({ type: z.literal(undefined), val: z.literal(9) }), + z.object({ type: z.literal("transform"), val: z.literal(10) }), + z.object({ type: z.literal("refine"), val: z.literal(11) }), + z.object({ type: z.literal("superRefine"), val: z.literal(12) }), + ]); + + expect(schema.parse({ type: "1", val: 1 })).toEqual({ type: "1", val: 1 }); + expect(schema.parse({ type: 1, val: 2 })).toEqual({ type: 1, val: 2 }); + expect(schema.parse({ type: BigInt(1), val: 3 })).toEqual({ + type: BigInt(1), + val: 3, + }); + expect(schema.parse({ type: "true", val: 4 })).toEqual({ + type: "true", + val: 4, + }); + expect(schema.parse({ type: true, val: 5 })).toEqual({ + type: true, + val: 5, + }); + expect(schema.parse({ type: "null", val: 6 })).toEqual({ + type: "null", + val: 6, + }); + expect(schema.parse({ type: null, val: 7 })).toEqual({ + type: null, + val: 7, + }); + expect(schema.parse({ type: "undefined", val: 8 })).toEqual({ + type: "undefined", + val: 8, + }); + expect(schema.parse({ type: undefined, val: 9 })).toEqual({ + type: undefined, + val: 9, + }); +}); + +test("invalid - null", () => { + try { + z.discriminatedUnion("type", [ + z.object({ type: z.literal("a"), a: z.string() }), + z.object({ type: z.literal("b"), b: z.string() }), + ]).parse(null); + throw new Error(); + } catch (e: any) { + expect(JSON.parse(e.message)).toEqual([ + { + code: z.ZodIssueCode.invalid_type, + expected: z.ZodParsedType.object, + message: "Expected object, received null", + received: z.ZodParsedType.null, + path: [], + }, + ]); + } +}); + +test("invalid discriminator value", () => { + try { + z.discriminatedUnion("type", [ + z.object({ type: z.literal("a"), a: z.string() }), + z.object({ type: z.literal("b"), b: z.string() }), + ]).parse({ type: "x", a: "abc" }); + throw new Error(); + } catch (e: any) { + expect(JSON.parse(e.message)).toEqual([ + { + code: z.ZodIssueCode.invalid_union_discriminator, + options: ["a", "b"], + message: "Invalid discriminator value. Expected 'a' | 'b'", + path: ["type"], + }, + ]); + } +}); + +test("valid discriminator value, invalid data", () => { + try { + z.discriminatedUnion("type", [ + z.object({ type: z.literal("a"), a: z.string() }), + z.object({ type: z.literal("b"), b: z.string() }), + ]).parse({ type: "a", b: "abc" }); + throw new Error(); + } catch (e: any) { + expect(JSON.parse(e.message)).toEqual([ + { + code: z.ZodIssueCode.invalid_type, + expected: z.ZodParsedType.string, + message: "Required", + path: ["a"], + received: z.ZodParsedType.undefined, + }, + ]); + } +}); + +test("wrong schema - missing discriminator", () => { + try { + z.discriminatedUnion("type", [ + z.object({ type: z.literal("a"), a: z.string() }), + z.object({ b: z.string() }) as any, + ]); + throw new Error(); + } catch (e: any) { + expect(e.message.includes("could not be extracted")).toBe(true); + } +}); + +test("wrong schema - duplicate discriminator values", () => { + try { + z.discriminatedUnion("type", [ + z.object({ type: z.literal("a"), a: z.string() }), + z.object({ type: z.literal("a"), b: z.string() }), + ]); + throw new Error(); + } catch (e: any) { + expect(e.message.includes("has duplicate value")).toEqual(true); + } +}); + +test("async - valid", async () => { + expect( + await z + .discriminatedUnion("type", [ + z.object({ + type: z.literal("a"), + a: z + .string() + .refine(async () => true) + .transform(async (val) => Number(val)), + }), + z.object({ + type: z.literal("b"), + b: z.string(), + }), + ]) + .parseAsync({ type: "a", a: "1" }) + ).toEqual({ type: "a", a: 1 }); +}); + +test("async - invalid", async () => { + try { + await z + .discriminatedUnion("type", [ + z.object({ + type: z.literal("a"), + a: z + .string() + .refine(async () => true) + .transform(async (val) => val), + }), + z.object({ + type: z.literal("b"), + b: z.string(), + }), + ]) + .parseAsync({ type: "a", a: 1 }); + throw new Error(); + } catch (e: any) { + expect(JSON.parse(e.message)).toEqual([ + { + code: "invalid_type", + expected: "string", + received: "number", + path: ["a"], + message: "Expected string, received number", + }, + ]); + } +}); + +test("valid - literals with .default or .preprocess", () => { + const schema = z.discriminatedUnion("type", [ + z.object({ + type: z.literal("foo").default("foo"), + a: z.string(), + }), + z.object({ + type: z.literal("custom"), + method: z.string(), + }), + z.object({ + type: z.preprocess((val) => String(val), z.literal("bar")), + c: z.string(), + }), + ]); + expect(schema.parse({ type: "foo", a: "foo" })).toEqual({ + type: "foo", + a: "foo", + }); +}); + +test("enum and nativeEnum", () => { + enum MyEnum { + d = 0, + e = "e", + } + + const schema = z.discriminatedUnion("key", [ + z.object({ + key: z.literal("a"), + // Add other properties specific to this option + }), + z.object({ + key: z.enum(["b", "c"]), + // Add other properties specific to this option + }), + z.object({ + key: z.nativeEnum(MyEnum), + // Add other properties specific to this option + }), + ]); + + // type schema = z.infer; + + schema.parse({ key: "a" }); + schema.parse({ key: "b" }); + schema.parse({ key: "c" }); + schema.parse({ key: MyEnum.d }); + schema.parse({ key: MyEnum.e }); + schema.parse({ key: "e" }); +}); + +test("branded", () => { + const schema = z.discriminatedUnion("key", [ + z.object({ + key: z.literal("a"), + // Add other properties specific to this option + }), + z.object({ + key: z.literal("b").brand("asdfaf"), + // Add other properties specific to this option + }), + ]); + + // type schema = z.infer; + + schema.parse({ key: "a" }); + schema.parse({ key: "b" }); + expect(() => { + schema.parse({ key: "c" }); + }).toThrow(); +}); + +test("optional and nullable", () => { + const schema = z.discriminatedUnion("key", [ + z.object({ + key: z.literal("a").optional(), + a: z.literal(true), + }), + z.object({ + key: z.literal("b").nullable(), + b: z.literal(true), + // Add other properties specific to this option + }), + ]); + + type schema = z.infer; + z.util.assertEqual(true); + + schema.parse({ key: "a", a: true }); + schema.parse({ key: undefined, a: true }); + schema.parse({ key: "b", b: true }); + schema.parse({ key: null, b: true }); + expect(() => { + schema.parse({ key: null, a: true }); + }).toThrow(); + expect(() => { + schema.parse({ key: "b", a: true }); + }).toThrow(); + + const value = schema.parse({ key: null, b: true }); + + if (!("key" in value)) value.a; + if (value.key === undefined) value.a; + if (value.key === "a") value.a; + if (value.key === "b") value.b; + if (value.key === null) value.b; +}); + +test("readonly array of options", () => { + const options = [ + z.object({ type: z.literal("x"), val: z.literal(1) }), + z.object({ type: z.literal("y"), val: z.literal(2) }), + ] as const; + + expect(z.discriminatedUnion("type", options).parse({ type: "x", val: 1 })).toEqual({ type: "x", val: 1 }); +}); diff --git a/node_modules/zod/src/v3/tests/enum.test.ts b/node_modules/zod/src/v3/tests/enum.test.ts new file mode 100644 index 0000000..53f4a3e --- /dev/null +++ b/node_modules/zod/src/v3/tests/enum.test.ts @@ -0,0 +1,80 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; + +test("create enum", () => { + const MyEnum = z.enum(["Red", "Green", "Blue"]); + expect(MyEnum.Values.Red).toEqual("Red"); + expect(MyEnum.Enum.Red).toEqual("Red"); + expect(MyEnum.enum.Red).toEqual("Red"); +}); + +test("infer enum", () => { + const MyEnum = z.enum(["Red", "Green", "Blue"]); + type MyEnum = z.infer; + util.assertEqual(true); +}); + +test("get options", () => { + expect(z.enum(["tuna", "trout"]).options).toEqual(["tuna", "trout"]); +}); + +test("readonly enum", () => { + const HTTP_SUCCESS = ["200", "201"] as const; + const arg = z.enum(HTTP_SUCCESS); + type arg = z.infer; + util.assertEqual(true); + + arg.parse("201"); + expect(() => arg.parse("202")).toThrow(); +}); + +test("error params", () => { + const result = z.enum(["test"], { required_error: "REQUIRED" }).safeParse(undefined); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues[0].message).toEqual("REQUIRED"); + } +}); + +test("extract/exclude", () => { + const foods = ["Pasta", "Pizza", "Tacos", "Burgers", "Salad"] as const; + const FoodEnum = z.enum(foods); + const ItalianEnum = FoodEnum.extract(["Pasta", "Pizza"]); + const UnhealthyEnum = FoodEnum.exclude(["Salad"]); + const EmptyFoodEnum = FoodEnum.exclude(foods); + + util.assertEqual, "Pasta" | "Pizza">(true); + util.assertEqual, "Pasta" | "Pizza" | "Tacos" | "Burgers">(true); + // @ts-expect-error TS2344 + util.assertEqual>(true); + util.assertEqual, never>(true); +}); + +test("error map in extract/exclude", () => { + const foods = ["Pasta", "Pizza", "Tacos", "Burgers", "Salad"] as const; + const FoodEnum = z.enum(foods, { + errorMap: () => ({ message: "This is not food!" }), + }); + const ItalianEnum = FoodEnum.extract(["Pasta", "Pizza"]); + const foodsError = FoodEnum.safeParse("Cucumbers"); + const italianError = ItalianEnum.safeParse("Tacos"); + if (!foodsError.success && !italianError.success) { + expect(foodsError.error.issues[0].message).toEqual(italianError.error.issues[0].message); + } + + const UnhealthyEnum = FoodEnum.exclude(["Salad"], { + errorMap: () => ({ message: "This is not healthy food!" }), + }); + const unhealthyError = UnhealthyEnum.safeParse("Salad"); + if (!unhealthyError.success) { + expect(unhealthyError.error.issues[0].message).toEqual("This is not healthy food!"); + } +}); + +test("readonly in ZodEnumDef", () => { + let _t!: z.ZodEnumDef; + _t; +}); diff --git a/node_modules/zod/src/v3/tests/error.test.ts b/node_modules/zod/src/v3/tests/error.test.ts new file mode 100644 index 0000000..5caaa6d --- /dev/null +++ b/node_modules/zod/src/v3/tests/error.test.ts @@ -0,0 +1,551 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { ZodError, ZodIssueCode } from "../ZodError.js"; +import { ZodParsedType } from "../helpers/util.js"; + +test("error creation", () => { + const err1 = ZodError.create([]); + err1.addIssue({ + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ZodParsedType.string, + path: [], + message: "", + fatal: true, + }); + err1.isEmpty; + + const err2 = ZodError.create(err1.issues); + const err3 = new ZodError([]); + err3.addIssues(err1.issues); + err3.addIssue(err1.issues[0]); + err1.message; + err2.message; + err3.message; +}); + +const errorMap: z.ZodErrorMap = (error, ctx) => { + if (error.code === ZodIssueCode.invalid_type) { + if (error.expected === "string") { + return { message: "bad type!" }; + } + } + if (error.code === ZodIssueCode.custom) { + return { message: `less-than-${error.params?.minimum}` }; + } + return { message: ctx.defaultError }; +}; + +test("type error with custom error map", () => { + try { + z.string().parse(234, { errorMap }); + } catch (err) { + const zerr: z.ZodError = err as any; + + expect(zerr.issues[0].code).toEqual(z.ZodIssueCode.invalid_type); + expect(zerr.issues[0].message).toEqual(`bad type!`); + } +}); + +test("refinement fail with params", () => { + try { + z.number() + .refine((val) => val >= 3, { + params: { minimum: 3 }, + }) + .parse(2, { errorMap }); + } catch (err) { + const zerr: z.ZodError = err as any; + expect(zerr.issues[0].code).toEqual(z.ZodIssueCode.custom); + expect(zerr.issues[0].message).toEqual(`less-than-3`); + } +}); + +test("custom error with custom errormap", () => { + try { + z.string() + .refine((val) => val.length > 12, { + params: { minimum: 13 }, + message: "override", + }) + .parse("asdf", { errorMap }); + } catch (err) { + const zerr: z.ZodError = err as any; + expect(zerr.issues[0].message).toEqual("override"); + } +}); + +test("default error message", () => { + try { + z.number() + .refine((x) => x > 3) + .parse(2); + } catch (err) { + const zerr: z.ZodError = err as any; + expect(zerr.issues.length).toEqual(1); + expect(zerr.issues[0].message).toEqual("Invalid input"); + } +}); + +test("override error in refine", () => { + try { + z.number() + .refine((x) => x > 3, "override") + .parse(2); + } catch (err) { + const zerr: z.ZodError = err as any; + expect(zerr.issues.length).toEqual(1); + expect(zerr.issues[0].message).toEqual("override"); + } +}); + +test("override error in refinement", () => { + try { + z.number() + .refine((x) => x > 3, { + message: "override", + }) + .parse(2); + } catch (err) { + const zerr: z.ZodError = err as any; + expect(zerr.issues.length).toEqual(1); + expect(zerr.issues[0].message).toEqual("override"); + } +}); + +test("array minimum", () => { + try { + z.array(z.string()).min(3, "tooshort").parse(["asdf", "qwer"]); + } catch (err) { + const zerr: ZodError = err as any; + expect(zerr.issues[0].code).toEqual(ZodIssueCode.too_small); + expect(zerr.issues[0].message).toEqual("tooshort"); + } + try { + z.array(z.string()).min(3).parse(["asdf", "qwer"]); + } catch (err) { + const zerr: ZodError = err as any; + expect(zerr.issues[0].code).toEqual(ZodIssueCode.too_small); + expect(zerr.issues[0].message).toEqual(`Array must contain at least 3 element(s)`); + } +}); + +// implement test for semi-smart union logic that checks for type error on either left or right +// test("union smart errors", () => { +// // expect.assertions(2); + +// const p1 = z +// .union([z.string(), z.number().refine((x) => x > 0)]) +// .safeParse(-3.2); + +// if (p1.success === true) throw new Error(); +// expect(p1.success).toBe(false); +// expect(p1.error.issues[0].code).toEqual(ZodIssueCode.custom); + +// const p2 = z.union([z.string(), z.number()]).safeParse(false); +// // .catch(err => expect(err.issues[0].code).toEqual(ZodIssueCode.invalid_union)); +// if (p2.success === true) throw new Error(); +// expect(p2.success).toBe(false); +// expect(p2.error.issues[0].code).toEqual(ZodIssueCode.invalid_union); +// }); + +test("custom path in custom error map", () => { + const schema = z.object({ + items: z.array(z.string()).refine((data) => data.length > 3, { + path: ["items-too-few"], + }), + }); + + const errorMap: z.ZodErrorMap = (error) => { + expect(error.path.length).toBe(2); + return { message: "doesnt matter" }; + }; + const result = schema.safeParse({ items: ["first"] }, { errorMap }); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues[0].path).toEqual(["items", "items-too-few"]); + } +}); + +test("error metadata from value", () => { + const dynamicRefine = z.string().refine( + (val) => val === val.toUpperCase(), + (val) => ({ params: { val } }) + ); + + const result = dynamicRefine.safeParse("asdf"); + expect(result.success).toEqual(false); + if (!result.success) { + const sub = result.error.issues[0]; + expect(result.error.issues[0].code).toEqual("custom"); + if (sub.code === "custom") { + expect(sub.params!.val).toEqual("asdf"); + } + } +}); + +// test("don't call refine after validation failed", () => { +// const asdf = z +// .union([ +// z.number(), +// z.string().transform(z.number(), (val) => { +// return parseFloat(val); +// }), +// ]) +// .refine((v) => v >= 1); + +// expect(() => asdf.safeParse("foo")).not.toThrow(); +// }); + +test("root level formatting", () => { + const schema = z.string().email(); + const result = schema.safeParse("asdfsdf"); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.format()._errors).toEqual(["Invalid email"]); + } +}); + +test("custom path", () => { + const schema = z + .object({ + password: z.string(), + confirm: z.string(), + }) + .refine((val) => val.confirm === val.password, { path: ["confirm"] }); + + const result = schema.safeParse({ + password: "peanuts", + confirm: "qeanuts", + }); + + expect(result.success).toEqual(false); + if (!result.success) { + // nested errors + const error = result.error.format(); + expect(error._errors).toEqual([]); + expect(error.password?._errors).toEqual(undefined); + expect(error.confirm?._errors).toEqual(["Invalid input"]); + } +}); + +test("custom path", () => { + const schema = z + .object({ + password: z.string().min(6), + confirm: z.string().min(6), + }) + .refine((val) => val.confirm === val.password); + + const result = schema.safeParse({ + password: "qwer", + confirm: "asdf", + }); + + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues.length).toEqual(3); + } +}); + +const schema = z.object({ + inner: z.object({ + name: z + .string() + .refine((val) => val.length > 5) + .array() + .refine((val) => val.length <= 1), + }), +}); + +test("no abort early on refinements", () => { + const invalidItem = { + inner: { name: ["aasd", "asdfasdfasfd"] }, + }; + + const result1 = schema.safeParse(invalidItem); + expect(result1.success).toEqual(false); + if (!result1.success) { + expect(result1.error.issues.length).toEqual(2); + } +}); +test("formatting", () => { + const invalidItem = { + inner: { name: ["aasd", "asdfasdfasfd"] }, + }; + const invalidArray = { + inner: { name: ["asdfasdf", "asdfasdfasfd"] }, + }; + const result1 = schema.safeParse(invalidItem); + const result2 = schema.safeParse(invalidArray); + + expect(result1.success).toEqual(false); + expect(result2.success).toEqual(false); + if (!result1.success) { + const error = result1.error.format(); + + expect(error._errors).toEqual([]); + expect(error.inner?._errors).toEqual([]); + // expect(error.inner?.name?._errors).toEqual(["Invalid input"]); + // expect(error.inner?.name?.[0]._errors).toEqual(["Invalid input"]); + expect(error.inner?.name?.[1]).toEqual(undefined); + } + if (!result2.success) { + type FormattedError = z.inferFormattedError; + const error: FormattedError = result2.error.format(); + expect(error._errors).toEqual([]); + expect(error.inner?._errors).toEqual([]); + expect(error.inner?.name?._errors).toEqual(["Invalid input"]); + expect(error.inner?.name?.[0]).toEqual(undefined); + expect(error.inner?.name?.[1]).toEqual(undefined); + expect(error.inner?.name?.[2]).toEqual(undefined); + } + + // test custom mapper + if (!result2.success) { + type FormattedError = z.inferFormattedError; + const error: FormattedError = result2.error.format(() => 5); + expect(error._errors).toEqual([]); + expect(error.inner?._errors).toEqual([]); + expect(error.inner?.name?._errors).toEqual([5]); + } +}); + +test("formatting with nullable and optional fields", () => { + const nameSchema = z.string().refine((val) => val.length > 5); + const schema = z.object({ + nullableObject: z.object({ name: nameSchema }).nullable(), + nullableArray: z.array(nameSchema).nullable(), + nullableTuple: z.tuple([nameSchema, nameSchema, z.number()]).nullable(), + optionalObject: z.object({ name: nameSchema }).optional(), + optionalArray: z.array(nameSchema).optional(), + optionalTuple: z.tuple([nameSchema, nameSchema, z.number()]).optional(), + }); + const invalidItem = { + nullableObject: { name: "abcd" }, + nullableArray: ["abcd"], + nullableTuple: ["abcd", "abcd", 1], + optionalObject: { name: "abcd" }, + optionalArray: ["abcd"], + optionalTuple: ["abcd", "abcd", 1], + }; + const result = schema.safeParse(invalidItem); + expect(result.success).toEqual(false); + if (!result.success) { + type FormattedError = z.inferFormattedError; + const error: FormattedError = result.error.format(); + expect(error._errors).toEqual([]); + expect(error.nullableObject?._errors).toEqual([]); + expect(error.nullableObject?.name?._errors).toEqual(["Invalid input"]); + expect(error.nullableArray?._errors).toEqual([]); + expect(error.nullableArray?.[0]?._errors).toEqual(["Invalid input"]); + expect(error.nullableTuple?._errors).toEqual([]); + expect(error.nullableTuple?.[0]?._errors).toEqual(["Invalid input"]); + expect(error.nullableTuple?.[1]?._errors).toEqual(["Invalid input"]); + expect(error.optionalObject?._errors).toEqual([]); + expect(error.optionalObject?.name?._errors).toEqual(["Invalid input"]); + expect(error.optionalArray?._errors).toEqual([]); + expect(error.optionalArray?.[0]?._errors).toEqual(["Invalid input"]); + expect(error.optionalTuple?._errors).toEqual([]); + expect(error.optionalTuple?.[0]?._errors).toEqual(["Invalid input"]); + expect(error.optionalTuple?.[1]?._errors).toEqual(["Invalid input"]); + } +}); + +const stringWithCustomError = z.string({ + errorMap: (issue, ctx) => ({ + message: issue.code === "invalid_type" ? (ctx.data ? "Invalid name" : "Name is required") : ctx.defaultError, + }), +}); + +test("schema-bound error map", () => { + const result = stringWithCustomError.safeParse(1234); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues[0].message).toEqual("Invalid name"); + } + + const result2 = stringWithCustomError.safeParse(undefined); + expect(result2.success).toEqual(false); + if (!result2.success) { + expect(result2.error.issues[0].message).toEqual("Name is required"); + } + + // support contextual override + const result3 = stringWithCustomError.safeParse(undefined, { + errorMap: () => ({ message: "OVERRIDE" }), + }); + expect(result3.success).toEqual(false); + if (!result3.success) { + expect(result3.error.issues[0].message).toEqual("OVERRIDE"); + } +}); + +test("overrideErrorMap", () => { + // support overrideErrorMap + z.setErrorMap(() => ({ message: "OVERRIDE" })); + const result4 = stringWithCustomError.min(10).safeParse("tooshort"); + expect(result4.success).toEqual(false); + if (!result4.success) { + expect(result4.error.issues[0].message).toEqual("OVERRIDE"); + } + z.setErrorMap(z.defaultErrorMap); +}); + +test("invalid and required", () => { + const str = z.string({ + invalid_type_error: "Invalid name", + required_error: "Name is required", + }); + const result1 = str.safeParse(1234); + expect(result1.success).toEqual(false); + if (!result1.success) { + expect(result1.error.issues[0].message).toEqual("Invalid name"); + } + const result2 = str.safeParse(undefined); + expect(result2.success).toEqual(false); + if (!result2.success) { + expect(result2.error.issues[0].message).toEqual("Name is required"); + } +}); + +test("Fallback to default required error", () => { + const str = z.string({ + invalid_type_error: "Invalid name", + // required_error: "Name is required", + }); + + const result2 = str.safeParse(undefined); + expect(result2.success).toEqual(false); + if (!result2.success) { + expect(result2.error.issues[0].message).toEqual("Required"); + } +}); + +test("invalid and required and errorMap", () => { + expect(() => { + return z.string({ + invalid_type_error: "Invalid name", + required_error: "Name is required", + errorMap: () => ({ message: "OVERRIDE" }), + }); + }).toThrow(); +}); + +test("strict error message", () => { + const errorMsg = "Invalid object"; + const obj = z.object({ x: z.string() }).strict(errorMsg); + const result = obj.safeParse({ x: "a", y: "b" }); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues[0].message).toEqual(errorMsg); + } +}); + +test("enum error message, invalid enum elementstring", () => { + try { + z.enum(["Tuna", "Trout"]).parse("Salmon"); + } catch (err) { + const zerr: z.ZodError = err as any; + expect(zerr.issues.length).toEqual(1); + expect(zerr.issues[0].message).toEqual("Invalid enum value. Expected 'Tuna' | 'Trout', received 'Salmon'"); + } +}); + +test("enum error message, invalid type", () => { + try { + z.enum(["Tuna", "Trout"]).parse(12); + } catch (err) { + const zerr: z.ZodError = err as any; + expect(zerr.issues.length).toEqual(1); + expect(zerr.issues[0].message).toEqual("Expected 'Tuna' | 'Trout', received number"); + } +}); + +test("nativeEnum default error message", () => { + enum Fish { + Tuna = "Tuna", + Trout = "Trout", + } + try { + z.nativeEnum(Fish).parse("Salmon"); + } catch (err) { + const zerr: z.ZodError = err as any; + expect(zerr.issues.length).toEqual(1); + expect(zerr.issues[0].message).toEqual("Invalid enum value. Expected 'Tuna' | 'Trout', received 'Salmon'"); + } +}); + +test("literal default error message", () => { + try { + z.literal("Tuna").parse("Trout"); + } catch (err) { + const zerr: z.ZodError = err as any; + expect(zerr.issues.length).toEqual(1); + expect(zerr.issues[0].message).toEqual(`Invalid literal value, expected "Tuna"`); + } +}); + +test("literal bigint default error message", () => { + try { + z.literal(BigInt(12)).parse(BigInt(13)); + } catch (err) { + const zerr: z.ZodError = err as any; + expect(zerr.issues.length).toEqual(1); + expect(zerr.issues[0].message).toEqual(`Invalid literal value, expected "12"`); + } +}); + +test("enum with message returns the custom error message", () => { + const schema = z.enum(["apple", "banana"], { + message: "the value provided is invalid", + }); + + const result1 = schema.safeParse("berries"); + expect(result1.success).toEqual(false); + if (!result1.success) { + expect(result1.error.issues[0].message).toEqual("the value provided is invalid"); + } + + const result2 = schema.safeParse(undefined); + expect(result2.success).toEqual(false); + if (!result2.success) { + expect(result2.error.issues[0].message).toEqual("the value provided is invalid"); + } + + const result3 = schema.safeParse("banana"); + expect(result3.success).toEqual(true); + + const result4 = schema.safeParse(null); + expect(result4.success).toEqual(false); + if (!result4.success) { + expect(result4.error.issues[0].message).toEqual("the value provided is invalid"); + } +}); + +test("when the message is falsy, it is used as is provided", () => { + const schema = z.string().max(1, { message: "" }); + const result = schema.safeParse("asdf"); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues[0].message).toEqual(""); + } +}); + +// test("dont short circuit on continuable errors", () => { +// const user = z +// .object({ +// password: z.string().min(6), +// confirm: z.string(), +// }) +// .refine((data) => data.password === data.confirm, { +// message: "Passwords don't match", +// path: ["confirm"], +// }); +// const result = user.safeParse({ password: "asdf", confirm: "qwer" }); +// if (!result.success) { +// expect(result.error.issues.length).toEqual(2); +// } +// }); diff --git a/node_modules/zod/src/v3/tests/firstparty.test.ts b/node_modules/zod/src/v3/tests/firstparty.test.ts new file mode 100644 index 0000000..017a1c1 --- /dev/null +++ b/node_modules/zod/src/v3/tests/firstparty.test.ts @@ -0,0 +1,87 @@ +// @ts-ignore TS6133 +import { test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; + +test("first party switch", () => { + const myType = z.string() as z.ZodFirstPartySchemaTypes; + const def = myType._def; + + switch (def.typeName) { + case z.ZodFirstPartyTypeKind.ZodString: + break; + case z.ZodFirstPartyTypeKind.ZodNumber: + break; + case z.ZodFirstPartyTypeKind.ZodNaN: + break; + case z.ZodFirstPartyTypeKind.ZodBigInt: + break; + case z.ZodFirstPartyTypeKind.ZodBoolean: + break; + case z.ZodFirstPartyTypeKind.ZodDate: + break; + case z.ZodFirstPartyTypeKind.ZodUndefined: + break; + case z.ZodFirstPartyTypeKind.ZodNull: + break; + case z.ZodFirstPartyTypeKind.ZodAny: + break; + case z.ZodFirstPartyTypeKind.ZodUnknown: + break; + case z.ZodFirstPartyTypeKind.ZodNever: + break; + case z.ZodFirstPartyTypeKind.ZodVoid: + break; + case z.ZodFirstPartyTypeKind.ZodArray: + break; + case z.ZodFirstPartyTypeKind.ZodObject: + break; + case z.ZodFirstPartyTypeKind.ZodUnion: + break; + case z.ZodFirstPartyTypeKind.ZodDiscriminatedUnion: + break; + case z.ZodFirstPartyTypeKind.ZodIntersection: + break; + case z.ZodFirstPartyTypeKind.ZodTuple: + break; + case z.ZodFirstPartyTypeKind.ZodRecord: + break; + case z.ZodFirstPartyTypeKind.ZodMap: + break; + case z.ZodFirstPartyTypeKind.ZodSet: + break; + case z.ZodFirstPartyTypeKind.ZodFunction: + break; + case z.ZodFirstPartyTypeKind.ZodLazy: + break; + case z.ZodFirstPartyTypeKind.ZodLiteral: + break; + case z.ZodFirstPartyTypeKind.ZodEnum: + break; + case z.ZodFirstPartyTypeKind.ZodEffects: + break; + case z.ZodFirstPartyTypeKind.ZodNativeEnum: + break; + case z.ZodFirstPartyTypeKind.ZodOptional: + break; + case z.ZodFirstPartyTypeKind.ZodNullable: + break; + case z.ZodFirstPartyTypeKind.ZodDefault: + break; + case z.ZodFirstPartyTypeKind.ZodCatch: + break; + case z.ZodFirstPartyTypeKind.ZodPromise: + break; + case z.ZodFirstPartyTypeKind.ZodBranded: + break; + case z.ZodFirstPartyTypeKind.ZodPipeline: + break; + case z.ZodFirstPartyTypeKind.ZodSymbol: + break; + case z.ZodFirstPartyTypeKind.ZodReadonly: + break; + default: + util.assertNever(def); + } +}); diff --git a/node_modules/zod/src/v3/tests/firstpartyschematypes.test.ts b/node_modules/zod/src/v3/tests/firstpartyschematypes.test.ts new file mode 100644 index 0000000..ad397d8 --- /dev/null +++ b/node_modules/zod/src/v3/tests/firstpartyschematypes.test.ts @@ -0,0 +1,21 @@ +// @ts-ignore TS6133 +import { test } from "vitest"; + +import type { ZodFirstPartySchemaTypes, ZodFirstPartyTypeKind } from "zod/v3"; +import { util } from "../helpers/util.js"; + +test("Identify missing [ZodFirstPartySchemaTypes]", () => { + type ZodFirstPartySchemaForType = ZodFirstPartySchemaTypes extends infer Schema + ? Schema extends { _def: { typeName: T } } + ? Schema + : never + : never; + type ZodMappedTypes = { + [key in ZodFirstPartyTypeKind]: ZodFirstPartySchemaForType; + }; + type ZodFirstPartySchemaTypesMissingFromUnion = keyof { + [key in keyof ZodMappedTypes as ZodMappedTypes[key] extends { _def: never } ? key : never]: unknown; + }; + + util.assertEqual(true); +}); diff --git a/node_modules/zod/src/v3/tests/function.test.ts b/node_modules/zod/src/v3/tests/function.test.ts new file mode 100644 index 0000000..a0f03bb --- /dev/null +++ b/node_modules/zod/src/v3/tests/function.test.ts @@ -0,0 +1,257 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; + +const args1 = z.tuple([z.string()]); +const returns1 = z.number(); +const func1 = z.function(args1, returns1); + +test("function parsing", () => { + const parsed = func1.parse((arg: any) => arg.length); + parsed("asdf"); +}); + +test("parsed function fail 1", () => { + const parsed = func1.parse((x: string) => x); + expect(() => parsed("asdf")).toThrow(); +}); + +test("parsed function fail 2", () => { + const parsed = func1.parse((x: string) => x); + expect(() => parsed(13 as any)).toThrow(); +}); + +test("function inference 1", () => { + type func1 = z.TypeOf; + util.assertEqual number>(true); +}); + +test("method parsing", () => { + const methodObject = z.object({ + property: z.number(), + method: z.function().args(z.string()).returns(z.number()), + }); + const methodInstance = { + property: 3, + method: function (s: string) { + return s.length + this.property; + }, + }; + const parsed = methodObject.parse(methodInstance); + expect(parsed.method("length=8")).toBe(11); // 8 length + 3 property +}); + +test("async method parsing", async () => { + const methodObject = z.object({ + property: z.number(), + method: z.function().args(z.string()).returns(z.promise(z.number())), + }); + const methodInstance = { + property: 3, + method: async function (s: string) { + return s.length + this.property; + }, + }; + const parsed = methodObject.parse(methodInstance); + expect(await parsed.method("length=8")).toBe(11); // 8 length + 3 property +}); + +test("args method", () => { + const t1 = z.function(); + type t1 = z.infer; + util.assertEqual unknown>(true); + + const t2 = t1.args(z.string()); + type t2 = z.infer; + util.assertEqual unknown>(true); + + const t3 = t2.returns(z.boolean()); + type t3 = z.infer; + util.assertEqual boolean>(true); +}); + +const args2 = z.tuple([ + z.object({ + f1: z.number(), + f2: z.string().nullable(), + f3: z.array(z.boolean().optional()).optional(), + }), +]); +const returns2 = z.union([z.string(), z.number()]); + +const func2 = z.function(args2, returns2); + +test("function inference 2", () => { + type func2 = z.TypeOf; + util.assertEqual< + func2, + (arg: { + f1: number; + f2: string | null; + f3?: (boolean | undefined)[] | undefined; + }) => string | number + >(true); +}); + +test("valid function run", () => { + const validFunc2Instance = func2.validate((_x) => { + return "adf" as any; + }); + + const checker = () => { + validFunc2Instance({ + f1: 21, + f2: "asdf", + f3: [true, false], + }); + }; + + checker(); +}); + +test("input validation error", () => { + const invalidFuncInstance = func2.validate((_x) => { + return "adf" as any; + }); + + const checker = () => { + invalidFuncInstance("Invalid_input" as any); + }; + + expect(checker).toThrow(); +}); + +test("output validation error", () => { + const invalidFuncInstance = func2.validate((_x) => { + return ["this", "is", "not", "valid", "output"] as any; + }); + + const checker = () => { + invalidFuncInstance({ + f1: 21, + f2: "asdf", + f3: [true, false], + }); + }; + + expect(checker).toThrow(); +}); + +z.function(z.tuple([z.string()])).args()._def.args; + +test("special function error codes", () => { + const checker = z.function(z.tuple([z.string()]), z.boolean()).implement((arg) => { + return arg.length as any; + }); + try { + checker("12" as any); + } catch (err) { + const zerr = err as z.ZodError; + const first = zerr.issues[0]; + if (first.code !== z.ZodIssueCode.invalid_return_type) throw new Error(); + + expect(first.returnTypeError).toBeInstanceOf(z.ZodError); + } + + try { + checker(12 as any); + } catch (err) { + const zerr = err as z.ZodError; + const first = zerr.issues[0]; + if (first.code !== z.ZodIssueCode.invalid_arguments) throw new Error(); + expect(first.argumentsError).toBeInstanceOf(z.ZodError); + } +}); + +test("function with async refinements", async () => { + const func = z + .function() + .args(z.string().refine(async (val) => val.length > 10)) + .returns(z.promise(z.number().refine(async (val) => val > 10))) + .implement(async (val) => { + return val.length; + }); + const results = []; + try { + await func("asdfasdf"); + results.push("success"); + } catch (_err) { + results.push("fail"); + } + try { + await func("asdflkjasdflkjsf"); + results.push("success"); + } catch (_err) { + results.push("fail"); + } + + expect(results).toEqual(["fail", "success"]); +}); + +test("non async function with async refinements should fail", async () => { + const func = z + .function() + .args(z.string().refine(async (val) => val.length > 10)) + .returns(z.number().refine(async (val) => val > 10)) + .implement((val) => { + return val.length; + }); + + const results = []; + try { + await func("asdasdfasdffasdf"); + results.push("success"); + } catch (_err) { + results.push("fail"); + } + + expect(results).toEqual(["fail"]); +}); + +test("allow extra parameters", () => { + const maxLength5 = z + .function() + .args(z.string()) + .returns(z.boolean()) + .implement((str, _arg, _qewr) => { + return str.length <= 5; + }); + + const filteredList = ["apple", "orange", "pear", "banana", "strawberry"].filter(maxLength5); + expect(filteredList.length).toEqual(2); +}); + +test("params and returnType getters", () => { + const func = z.function().args(z.string()).returns(z.string()); + + func.parameters().items[0].parse("asdf"); + func.returnType().parse("asdf"); +}); + +test("inference with transforms", () => { + const funcSchema = z + .function() + .args(z.string().transform((val) => val.length)) + .returns(z.object({ val: z.number() })); + const myFunc = funcSchema.implement((val) => { + return { val, extra: "stuff" }; + }); + myFunc("asdf"); + + util.assertEqual { val: number; extra: string }>(true); +}); + +test("fallback to OuterTypeOfFunction", () => { + const funcSchema = z + .function() + .args(z.string().transform((val) => val.length)) + .returns(z.object({ arg: z.number() }).transform((val) => val.arg)); + + const myFunc = funcSchema.implement((val) => { + return { arg: val, arg2: false }; + }); + + util.assertEqual number>(true); +}); diff --git a/node_modules/zod/src/v3/tests/generics.test.ts b/node_modules/zod/src/v3/tests/generics.test.ts new file mode 100644 index 0000000..e0af470 --- /dev/null +++ b/node_modules/zod/src/v3/tests/generics.test.ts @@ -0,0 +1,48 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; + +test("generics", () => { + async function stripOuter(schema: TData, data: unknown) { + return z + .object({ + nested: schema, // as z.ZodTypeAny, + }) + .transform((data) => { + return data.nested!; + }) + .parse({ nested: data }); + } + + const result = stripOuter(z.object({ a: z.string() }), { a: "asdf" }); + util.assertEqual>(true); +}); + +// test("assignability", () => { +// const createSchemaAndParse = ( +// key: K, +// valueSchema: VS, +// data: unknown +// ) => { +// const schema = z.object({ +// [key]: valueSchema, +// } as { [k in K]: VS }); +// return { [key]: valueSchema }; +// const parsed = schema.parse(data); +// return parsed; +// // const inferred: z.infer> = parsed; +// // return inferred; +// }; +// const parsed = createSchemaAndParse("foo", z.string(), { foo: "" }); +// util.assertEqual(true); +// }); + +test("nested no undefined", () => { + const inner = z.string().or(z.array(z.string())); + const outer = z.object({ inner }); + type outerSchema = z.infer; + z.util.assertEqual(true); + expect(outer.safeParse({ inner: undefined }).success).toEqual(false); +}); diff --git a/node_modules/zod/src/v3/tests/instanceof.test.ts b/node_modules/zod/src/v3/tests/instanceof.test.ts new file mode 100644 index 0000000..de66f3f --- /dev/null +++ b/node_modules/zod/src/v3/tests/instanceof.test.ts @@ -0,0 +1,37 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; + +test("instanceof", async () => { + class Test {} + class Subtest extends Test {} + abstract class AbstractBar { + constructor(public val: string) {} + } + class Bar extends AbstractBar {} + + const TestSchema = z.instanceof(Test); + const SubtestSchema = z.instanceof(Subtest); + const AbstractSchema = z.instanceof(AbstractBar); + const BarSchema = z.instanceof(Bar); + + TestSchema.parse(new Test()); + TestSchema.parse(new Subtest()); + SubtestSchema.parse(new Subtest()); + AbstractSchema.parse(new Bar("asdf")); + const bar = BarSchema.parse(new Bar("asdf")); + expect(bar.val).toEqual("asdf"); + + await expect(() => SubtestSchema.parse(new Test())).toThrow(/Input not instance of Subtest/); + await expect(() => TestSchema.parse(12)).toThrow(/Input not instance of Test/); + + util.assertEqual>(true); +}); + +test("instanceof fatal", () => { + const schema = z.instanceof(Date).refine((d) => d.toString()); + const res = schema.safeParse(null); + expect(res.success).toBe(false); +}); diff --git a/node_modules/zod/src/v3/tests/intersection.test.ts b/node_modules/zod/src/v3/tests/intersection.test.ts new file mode 100644 index 0000000..6d7936c --- /dev/null +++ b/node_modules/zod/src/v3/tests/intersection.test.ts @@ -0,0 +1,110 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +test("object intersection", () => { + const BaseTeacher = z.object({ + subjects: z.array(z.string()), + }); + const HasID = z.object({ id: z.string() }); + + const Teacher = z.intersection(BaseTeacher.passthrough(), HasID); // BaseTeacher.merge(HasID); + const data = { + subjects: ["math"], + id: "asdfasdf", + }; + expect(Teacher.parse(data)).toEqual(data); + expect(() => Teacher.parse({ subject: data.subjects })).toThrow(); + expect(Teacher.parse({ ...data, extra: 12 })).toEqual({ ...data, extra: 12 }); + + expect(() => z.intersection(BaseTeacher.strict(), HasID).parse({ ...data, extra: 12 })).toThrow(); +}); + +test("deep intersection", () => { + const Animal = z.object({ + properties: z.object({ + is_animal: z.boolean(), + }), + }); + const Cat = z + .object({ + properties: z.object({ + jumped: z.boolean(), + }), + }) + .and(Animal); + + type _Cat = z.infer; + // const cat:Cat = 'asdf' as any; + const cat = Cat.parse({ properties: { is_animal: true, jumped: true } }); + expect(cat.properties).toEqual({ is_animal: true, jumped: true }); +}); + +test("deep intersection of arrays", async () => { + const Author = z.object({ + posts: z.array( + z.object({ + post_id: z.number(), + }) + ), + }); + const Registry = z + .object({ + posts: z.array( + z.object({ + title: z.string(), + }) + ), + }) + .and(Author); + + const posts = [ + { post_id: 1, title: "Novels" }, + { post_id: 2, title: "Fairy tales" }, + ]; + const cat = Registry.parse({ posts }); + expect(cat.posts).toEqual(posts); + const asyncCat = await Registry.parseAsync({ posts }); + expect(asyncCat.posts).toEqual(posts); +}); + +test("invalid intersection types", async () => { + const numberIntersection = z.intersection( + z.number(), + z.number().transform((x) => x + 1) + ); + + const syncResult = numberIntersection.safeParse(1234); + expect(syncResult.success).toEqual(false); + if (!syncResult.success) { + expect(syncResult.error.issues[0].code).toEqual(z.ZodIssueCode.invalid_intersection_types); + } + + const asyncResult = await numberIntersection.spa(1234); + expect(asyncResult.success).toEqual(false); + if (!asyncResult.success) { + expect(asyncResult.error.issues[0].code).toEqual(z.ZodIssueCode.invalid_intersection_types); + } +}); + +test("invalid array merge", async () => { + const stringArrInt = z.intersection( + z.string().array(), + z + .string() + .array() + .transform((val) => [...val, "asdf"]) + ); + const syncResult = stringArrInt.safeParse(["asdf", "qwer"]); + expect(syncResult.success).toEqual(false); + if (!syncResult.success) { + expect(syncResult.error.issues[0].code).toEqual(z.ZodIssueCode.invalid_intersection_types); + } + + const asyncResult = await stringArrInt.spa(["asdf", "qwer"]); + expect(asyncResult.success).toEqual(false); + if (!asyncResult.success) { + expect(asyncResult.error.issues[0].code).toEqual(z.ZodIssueCode.invalid_intersection_types); + } +}); diff --git a/node_modules/zod/src/v3/tests/language-server.source.ts b/node_modules/zod/src/v3/tests/language-server.source.ts new file mode 100644 index 0000000..cbe818b --- /dev/null +++ b/node_modules/zod/src/v3/tests/language-server.source.ts @@ -0,0 +1,76 @@ +import * as z from "zod/v3"; + +export const filePath = __filename; + +// z.object() + +export const Test = z.object({ + f1: z.number(), +}); + +export type Test = z.infer; + +export const instanceOfTest: Test = { + f1: 1, +}; + +// z.object().merge() + +export const TestMerge = z + .object({ + f2: z.string().optional(), + }) + .merge(Test); + +export type TestMerge = z.infer; + +export const instanceOfTestMerge: TestMerge = { + f1: 1, + f2: "string", +}; + +// z.union() + +export const TestUnion = z.union([ + z.object({ + f2: z.string().optional(), + }), + Test, +]); + +export type TestUnion = z.infer; + +export const instanceOfTestUnion: TestUnion = { + f1: 1, + f2: "string", +}; + +// z.object().partial() + +export const TestPartial = Test.partial(); + +export type TestPartial = z.infer; + +export const instanceOfTestPartial: TestPartial = { + f1: 1, +}; + +// z.object().pick() + +export const TestPick = TestMerge.pick({ f1: true }); + +export type TestPick = z.infer; + +export const instanceOfTestPick: TestPick = { + f1: 1, +}; + +// z.object().omit() + +export const TestOmit = TestMerge.omit({ f2: true }); + +export type TestOmit = z.infer; + +export const instanceOfTestOmit: TestOmit = { + f1: 1, +}; diff --git a/node_modules/zod/src/v3/tests/language-server.test.ts b/node_modules/zod/src/v3/tests/language-server.test.ts new file mode 100644 index 0000000..851fdc4 --- /dev/null +++ b/node_modules/zod/src/v3/tests/language-server.test.ts @@ -0,0 +1,207 @@ +import { test } from "vitest"; +// import path from "path"; +// import { Node, Project, SyntaxKind } from "ts-morph"; + +// import { filePath } from "./language-server.source"; + +// The following tool is helpful for understanding the TypeScript AST associated with these tests: +// https://ts-ast-viewer.com/ (just copy the contents of language-server.source into the viewer) + +test("", () => {}); +// describe("Executing Go To Definition (and therefore Find Usages and Rename Refactoring) using an IDE works on inferred object properties", () => { +// // Compile file developmentEnvironment.source +// const project = new Project({ +// tsConfigFilePath: path.join(__dirname, "..", "..", "tsconfig.json"), +// skipAddingFilesFromTsConfig: true, +// }); +// const sourceFile = project.addSourceFileAtPath(filePath); + +// test("works for object properties inferred from z.object()", () => { +// // Find usage of Test.f1 property +// const instanceVariable = +// sourceFile.getVariableDeclarationOrThrow("instanceOfTest"); +// const propertyBeingAssigned = getPropertyBeingAssigned( +// instanceVariable, +// "f1" +// ); + +// // Find definition of Test.f1 property +// const definitionOfProperty = propertyBeingAssigned?.getDefinitionNodes()[0]; +// const parentOfProperty = definitionOfProperty?.getFirstAncestorByKind( +// SyntaxKind.VariableDeclaration +// ); + +// // Assert that find definition returned the Zod definition of Test +// expect(definitionOfProperty?.getText()).toEqual("f1: z.number()"); +// expect(parentOfProperty?.getName()).toEqual("Test"); +// }); + +// // test("works for first object properties inferred from z.object().merge()", () => { +// // // Find usage of TestMerge.f1 property +// // const instanceVariable = sourceFile.getVariableDeclarationOrThrow( +// // "instanceOfTestMerge" +// // ); +// // const propertyBeingAssigned = getPropertyBeingAssigned( +// // instanceVariable, +// // "f1" +// // ); + +// // // Find definition of TestMerge.f1 property +// // const definitionOfProperty = propertyBeingAssigned?.getDefinitionNodes()[0]; +// // const parentOfProperty = definitionOfProperty?.getFirstAncestorByKind( +// // SyntaxKind.VariableDeclaration +// // ); + +// // // Assert that find definition returned the Zod definition of Test +// // expect(definitionOfProperty?.getText()).toEqual("f1: z.number()"); +// // expect(parentOfProperty?.getName()).toEqual("Test"); +// // }); + +// // test("works for second object properties inferred from z.object().merge()", () => { +// // // Find usage of TestMerge.f2 property +// // const instanceVariable = sourceFile.getVariableDeclarationOrThrow( +// // "instanceOfTestMerge" +// // ); +// // const propertyBeingAssigned = getPropertyBeingAssigned( +// // instanceVariable, +// // "f2" +// // ); + +// // // Find definition of TestMerge.f2 property +// // const definitionOfProperty = propertyBeingAssigned?.getDefinitionNodes()[0]; +// // const parentOfProperty = definitionOfProperty?.getFirstAncestorByKind( +// // SyntaxKind.VariableDeclaration +// // ); + +// // // Assert that find definition returned the Zod definition of TestMerge +// // expect(definitionOfProperty?.getText()).toEqual( +// // "f2: z.string().optional()" +// // ); +// // expect(parentOfProperty?.getName()).toEqual("TestMerge"); +// // }); + +// test("works for first object properties inferred from z.union()", () => { +// // Find usage of TestUnion.f1 property +// const instanceVariable = sourceFile.getVariableDeclarationOrThrow( +// "instanceOfTestUnion" +// ); +// const propertyBeingAssigned = getPropertyBeingAssigned( +// instanceVariable, +// "f1" +// ); + +// // Find definition of TestUnion.f1 property +// const definitionOfProperty = propertyBeingAssigned?.getDefinitionNodes()[0]; +// const parentOfProperty = definitionOfProperty?.getFirstAncestorByKind( +// SyntaxKind.VariableDeclaration +// ); + +// // Assert that find definition returned the Zod definition of Test +// expect(definitionOfProperty?.getText()).toEqual("f1: z.number()"); +// expect(parentOfProperty?.getName()).toEqual("Test"); +// }); + +// test("works for second object properties inferred from z.union()", () => { +// // Find usage of TestUnion.f2 property +// const instanceVariable = sourceFile.getVariableDeclarationOrThrow( +// "instanceOfTestUnion" +// ); +// const propertyBeingAssigned = getPropertyBeingAssigned( +// instanceVariable, +// "f2" +// ); + +// // Find definition of TestUnion.f2 property +// const definitionOfProperty = propertyBeingAssigned?.getDefinitionNodes()[0]; +// const parentOfProperty = definitionOfProperty?.getFirstAncestorByKind( +// SyntaxKind.VariableDeclaration +// ); + +// // Assert that find definition returned the Zod definition of TestUnion +// expect(definitionOfProperty?.getText()).toEqual( +// "f2: z.string().optional()" +// ); +// expect(parentOfProperty?.getName()).toEqual("TestUnion"); +// }); + +// test("works for object properties inferred from z.object().partial()", () => { +// // Find usage of TestPartial.f1 property +// const instanceVariable = sourceFile.getVariableDeclarationOrThrow( +// "instanceOfTestPartial" +// ); +// const propertyBeingAssigned = getPropertyBeingAssigned( +// instanceVariable, +// "f1" +// ); + +// // Find definition of TestPartial.f1 property +// const definitionOfProperty = propertyBeingAssigned?.getDefinitionNodes()[0]; +// const parentOfProperty = definitionOfProperty?.getFirstAncestorByKind( +// SyntaxKind.VariableDeclaration +// ); + +// // Assert that find definition returned the Zod definition of Test +// expect(definitionOfProperty?.getText()).toEqual("f1: z.number()"); +// expect(parentOfProperty?.getName()).toEqual("Test"); +// }); + +// test("works for object properties inferred from z.object().pick()", () => { +// // Find usage of TestPick.f1 property +// const instanceVariable = +// sourceFile.getVariableDeclarationOrThrow("instanceOfTestPick"); +// const propertyBeingAssigned = getPropertyBeingAssigned( +// instanceVariable, +// "f1" +// ); + +// // Find definition of TestPick.f1 property +// const definitionOfProperty = propertyBeingAssigned?.getDefinitionNodes()[0]; +// const parentOfProperty = definitionOfProperty?.getFirstAncestorByKind( +// SyntaxKind.VariableDeclaration +// ); + +// // Assert that find definition returned the Zod definition of Test +// expect(definitionOfProperty?.getText()).toEqual("f1: z.number()"); +// expect(parentOfProperty?.getName()).toEqual("Test"); +// }); + +// test("works for object properties inferred from z.object().omit()", () => { +// // Find usage of TestOmit.f1 property +// const instanceVariable = +// sourceFile.getVariableDeclarationOrThrow("instanceOfTestOmit"); +// const propertyBeingAssigned = getPropertyBeingAssigned( +// instanceVariable, +// "f1" +// ); + +// // Find definition of TestOmit.f1 property +// const definitionOfProperty = propertyBeingAssigned?.getDefinitionNodes()[0]; +// const parentOfProperty = definitionOfProperty?.getFirstAncestorByKind( +// SyntaxKind.VariableDeclaration +// ); + +// // Assert that find definition returned the Zod definition of Test +// expect(definitionOfProperty?.getText()).toEqual("f1: z.number()"); +// expect(parentOfProperty?.getName()).toEqual("Test"); +// }); +// }); + +// const getPropertyBeingAssigned = (node: Node, name: string) => { +// const propertyAssignment = node.forEachDescendant((descendent) => +// Node.isPropertyAssignment(descendent) && descendent.getName() == name +// ? descendent +// : undefined +// ); + +// if (propertyAssignment == null) +// fail(`Could not find property assignment with name ${name}`); + +// const propertyLiteral = propertyAssignment.getFirstDescendantByKind( +// SyntaxKind.Identifier +// ); + +// if (propertyLiteral == null) +// fail(`Could not find property literal with name ${name}`); + +// return propertyLiteral; +// }; diff --git a/node_modules/zod/src/v3/tests/literal.test.ts b/node_modules/zod/src/v3/tests/literal.test.ts new file mode 100644 index 0000000..d166a24 --- /dev/null +++ b/node_modules/zod/src/v3/tests/literal.test.ts @@ -0,0 +1,36 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +const literalTuna = z.literal("tuna"); +const literalFortyTwo = z.literal(42); +const literalTrue = z.literal(true); + +const terrificSymbol = Symbol("terrific"); +const literalTerrificSymbol = z.literal(terrificSymbol); + +test("passing validations", () => { + literalTuna.parse("tuna"); + literalFortyTwo.parse(42); + literalTrue.parse(true); + literalTerrificSymbol.parse(terrificSymbol); +}); + +test("failing validations", () => { + expect(() => literalTuna.parse("shark")).toThrow(); + expect(() => literalFortyTwo.parse(43)).toThrow(); + expect(() => literalTrue.parse(false)).toThrow(); + expect(() => literalTerrificSymbol.parse(Symbol("terrific"))).toThrow(); +}); + +test("invalid_literal should have `received` field with data", () => { + const data = "shark"; + const result = literalTuna.safeParse(data); + if (!result.success) { + const issue = result.error.issues[0]; + if (issue.code === "invalid_literal") { + expect(issue.received).toBe(data); + } + } +}); diff --git a/node_modules/zod/src/v3/tests/map.test.ts b/node_modules/zod/src/v3/tests/map.test.ts new file mode 100644 index 0000000..9471819 --- /dev/null +++ b/node_modules/zod/src/v3/tests/map.test.ts @@ -0,0 +1,110 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { ZodIssueCode } from "zod/v3"; +import { util } from "../helpers/util.js"; + +const stringMap = z.map(z.string(), z.string()); +type stringMap = z.infer; + +test("type inference", () => { + util.assertEqual>(true); +}); + +test("valid parse", () => { + const result = stringMap.safeParse( + new Map([ + ["first", "foo"], + ["second", "bar"], + ]) + ); + expect(result.success).toEqual(true); + if (result.success) { + expect(result.data.has("first")).toEqual(true); + expect(result.data.has("second")).toEqual(true); + expect(result.data.get("first")).toEqual("foo"); + expect(result.data.get("second")).toEqual("bar"); + } +}); + +test("valid parse async", async () => { + const result = await stringMap.spa( + new Map([ + ["first", "foo"], + ["second", "bar"], + ]) + ); + expect(result.success).toEqual(true); + if (result.success) { + expect(result.data.has("first")).toEqual(true); + expect(result.data.has("second")).toEqual(true); + expect(result.data.get("first")).toEqual("foo"); + expect(result.data.get("second")).toEqual("bar"); + } +}); + +test("throws when a Set is given", () => { + const result = stringMap.safeParse(new Set([])); + expect(result.success).toEqual(false); + if (result.success === false) { + expect(result.error.issues.length).toEqual(1); + expect(result.error.issues[0].code).toEqual(ZodIssueCode.invalid_type); + } +}); + +test("throws when the given map has invalid key and invalid input", () => { + const result = stringMap.safeParse(new Map([[42, Symbol()]])); + expect(result.success).toEqual(false); + if (result.success === false) { + expect(result.error.issues.length).toEqual(2); + expect(result.error.issues[0].code).toEqual(ZodIssueCode.invalid_type); + expect(result.error.issues[0].path).toEqual([0, "key"]); + expect(result.error.issues[1].code).toEqual(ZodIssueCode.invalid_type); + expect(result.error.issues[1].path).toEqual([0, "value"]); + } +}); + +test("throws when the given map has multiple invalid entries", () => { + // const result = stringMap.safeParse(new Map([[42, Symbol()]])); + + const result = stringMap.safeParse( + new Map([ + [1, "foo"], + ["bar", 2], + ] as [any, any][]) as Map + ); + + // const result = stringMap.safeParse(new Map([[42, Symbol()]])); + expect(result.success).toEqual(false); + if (result.success === false) { + expect(result.error.issues.length).toEqual(2); + expect(result.error.issues[0].code).toEqual(ZodIssueCode.invalid_type); + expect(result.error.issues[0].path).toEqual([0, "key"]); + expect(result.error.issues[1].code).toEqual(ZodIssueCode.invalid_type); + expect(result.error.issues[1].path).toEqual([1, "value"]); + } +}); + +test("dirty", async () => { + const map = z.map( + z.string().refine((val) => val === val.toUpperCase(), { + message: "Keys must be uppercase", + }), + z.string() + ); + const result = await map.spa( + new Map([ + ["first", "foo"], + ["second", "bar"], + ]) + ); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues.length).toEqual(2); + expect(result.error.issues[0].code).toEqual(z.ZodIssueCode.custom); + expect(result.error.issues[0].message).toEqual("Keys must be uppercase"); + expect(result.error.issues[1].code).toEqual(z.ZodIssueCode.custom); + expect(result.error.issues[1].message).toEqual("Keys must be uppercase"); + } +}); diff --git a/node_modules/zod/src/v3/tests/masking.test.ts b/node_modules/zod/src/v3/tests/masking.test.ts new file mode 100644 index 0000000..63817e2 --- /dev/null +++ b/node_modules/zod/src/v3/tests/masking.test.ts @@ -0,0 +1,4 @@ +// @ts-ignore TS6133 +import { test } from "vitest"; + +test("masking test", () => {}); diff --git a/node_modules/zod/src/v3/tests/mocker.test.ts b/node_modules/zod/src/v3/tests/mocker.test.ts new file mode 100644 index 0000000..3a2506b --- /dev/null +++ b/node_modules/zod/src/v3/tests/mocker.test.ts @@ -0,0 +1,19 @@ +// @ts-ignore TS6133 +import { test } from "vitest"; + +import { Mocker } from "./Mocker.js"; + +test("mocker", () => { + const mocker = new Mocker(); + mocker.string; + mocker.number; + mocker.boolean; + mocker.null; + mocker.undefined; + mocker.stringOptional; + mocker.stringNullable; + mocker.numberOptional; + mocker.numberNullable; + mocker.booleanOptional; + mocker.booleanNullable; +}); diff --git a/node_modules/zod/src/v3/tests/nan.test.ts b/node_modules/zod/src/v3/tests/nan.test.ts new file mode 100644 index 0000000..e24567a --- /dev/null +++ b/node_modules/zod/src/v3/tests/nan.test.ts @@ -0,0 +1,21 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +const schema = z.nan(); + +test("passing validations", () => { + schema.parse(Number.NaN); + schema.parse(Number("Not a number")); +}); + +test("failing validations", () => { + expect(() => schema.parse(5)).toThrow(); + expect(() => schema.parse("John")).toThrow(); + expect(() => schema.parse(true)).toThrow(); + expect(() => schema.parse(null)).toThrow(); + expect(() => schema.parse(undefined)).toThrow(); + expect(() => schema.parse({})).toThrow(); + expect(() => schema.parse([])).toThrow(); +}); diff --git a/node_modules/zod/src/v3/tests/nativeEnum.test.ts b/node_modules/zod/src/v3/tests/nativeEnum.test.ts new file mode 100644 index 0000000..61eb37a --- /dev/null +++ b/node_modules/zod/src/v3/tests/nativeEnum.test.ts @@ -0,0 +1,87 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; + +test("nativeEnum test with consts", () => { + const Fruits: { Apple: "apple"; Banana: "banana" } = { + Apple: "apple", + Banana: "banana", + }; + const fruitEnum = z.nativeEnum(Fruits); + type fruitEnum = z.infer; + fruitEnum.parse("apple"); + fruitEnum.parse("banana"); + fruitEnum.parse(Fruits.Apple); + fruitEnum.parse(Fruits.Banana); + util.assertEqual(true); +}); + +test("nativeEnum test with real enum", () => { + enum Fruits { + Apple = "apple", + Banana = "banana", + } + // @ts-ignore + const fruitEnum = z.nativeEnum(Fruits); + type fruitEnum = z.infer; + fruitEnum.parse("apple"); + fruitEnum.parse("banana"); + fruitEnum.parse(Fruits.Apple); + fruitEnum.parse(Fruits.Banana); + util.assertIs(true); +}); + +test("nativeEnum test with const with numeric keys", () => { + const FruitValues = { + Apple: 10, + Banana: 20, + // @ts-ignore + } as const; + const fruitEnum = z.nativeEnum(FruitValues); + type fruitEnum = z.infer; + fruitEnum.parse(10); + fruitEnum.parse(20); + fruitEnum.parse(FruitValues.Apple); + fruitEnum.parse(FruitValues.Banana); + util.assertEqual(true); +}); + +test("from enum", () => { + enum Fruits { + Cantaloupe = 0, + Apple = "apple", + Banana = "banana", + } + + const FruitEnum = z.nativeEnum(Fruits as any); + type _FruitEnum = z.infer; + FruitEnum.parse(Fruits.Cantaloupe); + FruitEnum.parse(Fruits.Apple); + FruitEnum.parse("apple"); + FruitEnum.parse(0); + expect(() => FruitEnum.parse(1)).toThrow(); + expect(() => FruitEnum.parse("Apple")).toThrow(); + expect(() => FruitEnum.parse("Cantaloupe")).toThrow(); +}); + +test("from const", () => { + const Greek = { + Alpha: "a", + Beta: "b", + Gamma: 3, + // @ts-ignore + } as const; + + const GreekEnum = z.nativeEnum(Greek); + type _GreekEnum = z.infer; + GreekEnum.parse("a"); + GreekEnum.parse("b"); + GreekEnum.parse(3); + expect(() => GreekEnum.parse("v")).toThrow(); + expect(() => GreekEnum.parse("Alpha")).toThrow(); + expect(() => GreekEnum.parse(2)).toThrow(); + + expect(GreekEnum.enum.Alpha).toEqual("a"); +}); diff --git a/node_modules/zod/src/v3/tests/nullable.test.ts b/node_modules/zod/src/v3/tests/nullable.test.ts new file mode 100644 index 0000000..90c1eed --- /dev/null +++ b/node_modules/zod/src/v3/tests/nullable.test.ts @@ -0,0 +1,42 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +function checkErrors(a: z.ZodTypeAny, bad: any) { + let expected: any; + try { + a.parse(bad); + } catch (error) { + expected = (error as z.ZodError).formErrors; + } + try { + a.nullable().parse(bad); + } catch (error) { + expect((error as z.ZodError).formErrors).toEqual(expected); + } +} + +test("Should have error messages appropriate for the underlying type", () => { + checkErrors(z.string().min(2), 1); + z.string().min(2).nullable().parse(null); + checkErrors(z.number().gte(2), 1); + z.number().gte(2).nullable().parse(null); + checkErrors(z.boolean(), ""); + z.boolean().nullable().parse(null); + checkErrors(z.null(), null); + z.null().nullable().parse(null); + checkErrors(z.null(), {}); + z.null().nullable().parse(null); + checkErrors(z.object({}), 1); + z.object({}).nullable().parse(null); + checkErrors(z.tuple([]), 1); + z.tuple([]).nullable().parse(null); + checkErrors(z.unknown(), 1); + z.unknown().nullable().parse(null); +}); + +test("unwrap", () => { + const unwrapped = z.string().nullable().unwrap(); + expect(unwrapped).toBeInstanceOf(z.ZodString); +}); diff --git a/node_modules/zod/src/v3/tests/number.test.ts b/node_modules/zod/src/v3/tests/number.test.ts new file mode 100644 index 0000000..db3f73b --- /dev/null +++ b/node_modules/zod/src/v3/tests/number.test.ts @@ -0,0 +1,176 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +const gtFive = z.number().gt(5); +const gteFive = z.number().gte(-5).gte(5); +const minFive = z.number().min(0).min(5); +const ltFive = z.number().lte(10).lt(5); +const lteFive = z.number().lte(5); +const maxFive = z.number().max(10).max(5); +const intNum = z.number().int(); +const positive = z.number().positive(); +const negative = z.number().negative(); +const nonpositive = z.number().nonpositive(); +const nonnegative = z.number().nonnegative(); +const multipleOfFive = z.number().multipleOf(5); +const multipleOfNegativeFive = z.number().multipleOf(-5); +const finite = z.number().finite(); +const safe = z.number().safe(); +const stepPointOne = z.number().step(0.1); +const stepPointZeroZeroZeroOne = z.number().step(0.0001); +const stepSixPointFour = z.number().step(6.4); + +test("passing validations", () => { + z.number().parse(1); + z.number().parse(1.5); + z.number().parse(0); + z.number().parse(-1.5); + z.number().parse(-1); + z.number().parse(Number.POSITIVE_INFINITY); + z.number().parse(Number.NEGATIVE_INFINITY); + gtFive.parse(6); + gtFive.parse(Number.POSITIVE_INFINITY); + gteFive.parse(5); + gteFive.parse(Number.POSITIVE_INFINITY); + minFive.parse(5); + minFive.parse(Number.POSITIVE_INFINITY); + ltFive.parse(4); + ltFive.parse(Number.NEGATIVE_INFINITY); + lteFive.parse(5); + lteFive.parse(Number.NEGATIVE_INFINITY); + maxFive.parse(5); + maxFive.parse(Number.NEGATIVE_INFINITY); + intNum.parse(4); + positive.parse(1); + positive.parse(Number.POSITIVE_INFINITY); + negative.parse(-1); + negative.parse(Number.NEGATIVE_INFINITY); + nonpositive.parse(0); + nonpositive.parse(-1); + nonpositive.parse(Number.NEGATIVE_INFINITY); + nonnegative.parse(0); + nonnegative.parse(1); + nonnegative.parse(Number.POSITIVE_INFINITY); + multipleOfFive.parse(15); + multipleOfFive.parse(-15); + multipleOfNegativeFive.parse(-15); + multipleOfNegativeFive.parse(15); + finite.parse(123); + safe.parse(Number.MIN_SAFE_INTEGER); + safe.parse(Number.MAX_SAFE_INTEGER); + stepPointOne.parse(6); + stepPointOne.parse(6.1); + stepPointOne.parse(6.1); + stepSixPointFour.parse(12.8); + stepPointZeroZeroZeroOne.parse(3.01); +}); + +test("failing validations", () => { + expect(() => ltFive.parse(5)).toThrow(); + expect(() => lteFive.parse(6)).toThrow(); + expect(() => maxFive.parse(6)).toThrow(); + expect(() => gtFive.parse(5)).toThrow(); + expect(() => gteFive.parse(4)).toThrow(); + expect(() => minFive.parse(4)).toThrow(); + expect(() => intNum.parse(3.14)).toThrow(); + expect(() => positive.parse(0)).toThrow(); + expect(() => positive.parse(-1)).toThrow(); + expect(() => negative.parse(0)).toThrow(); + expect(() => negative.parse(1)).toThrow(); + expect(() => nonpositive.parse(1)).toThrow(); + expect(() => nonnegative.parse(-1)).toThrow(); + expect(() => multipleOfFive.parse(7.5)).toThrow(); + expect(() => multipleOfFive.parse(-7.5)).toThrow(); + expect(() => multipleOfNegativeFive.parse(-7.5)).toThrow(); + expect(() => multipleOfNegativeFive.parse(7.5)).toThrow(); + expect(() => finite.parse(Number.POSITIVE_INFINITY)).toThrow(); + expect(() => finite.parse(Number.NEGATIVE_INFINITY)).toThrow(); + expect(() => safe.parse(Number.MIN_SAFE_INTEGER - 1)).toThrow(); + expect(() => safe.parse(Number.MAX_SAFE_INTEGER + 1)).toThrow(); + + expect(() => stepPointOne.parse(6.11)).toThrow(); + expect(() => stepPointOne.parse(6.1000000001)).toThrow(); + expect(() => stepSixPointFour.parse(6.41)).toThrow(); +}); + +test("parse NaN", () => { + expect(() => z.number().parse(Number.NaN)).toThrow(); +}); + +test("min max getters", () => { + expect(z.number().minValue).toBeNull; + expect(ltFive.minValue).toBeNull; + expect(lteFive.minValue).toBeNull; + expect(maxFive.minValue).toBeNull; + expect(negative.minValue).toBeNull; + expect(nonpositive.minValue).toBeNull; + expect(intNum.minValue).toBeNull; + expect(multipleOfFive.minValue).toBeNull; + expect(finite.minValue).toBeNull; + expect(gtFive.minValue).toEqual(5); + expect(gteFive.minValue).toEqual(5); + expect(minFive.minValue).toEqual(5); + expect(minFive.min(10).minValue).toEqual(10); + expect(positive.minValue).toEqual(0); + expect(nonnegative.minValue).toEqual(0); + expect(safe.minValue).toEqual(Number.MIN_SAFE_INTEGER); + + expect(z.number().maxValue).toBeNull; + expect(gtFive.maxValue).toBeNull; + expect(gteFive.maxValue).toBeNull; + expect(minFive.maxValue).toBeNull; + expect(positive.maxValue).toBeNull; + expect(nonnegative.maxValue).toBeNull; + expect(intNum.minValue).toBeNull; + expect(multipleOfFive.minValue).toBeNull; + expect(finite.minValue).toBeNull; + expect(ltFive.maxValue).toEqual(5); + expect(lteFive.maxValue).toEqual(5); + expect(maxFive.maxValue).toEqual(5); + expect(maxFive.max(1).maxValue).toEqual(1); + expect(negative.maxValue).toEqual(0); + expect(nonpositive.maxValue).toEqual(0); + expect(safe.maxValue).toEqual(Number.MAX_SAFE_INTEGER); +}); + +test("int getter", () => { + expect(z.number().isInt).toEqual(false); + expect(z.number().multipleOf(1.5).isInt).toEqual(false); + expect(gtFive.isInt).toEqual(false); + expect(gteFive.isInt).toEqual(false); + expect(minFive.isInt).toEqual(false); + expect(positive.isInt).toEqual(false); + expect(nonnegative.isInt).toEqual(false); + expect(finite.isInt).toEqual(false); + expect(ltFive.isInt).toEqual(false); + expect(lteFive.isInt).toEqual(false); + expect(maxFive.isInt).toEqual(false); + expect(negative.isInt).toEqual(false); + expect(nonpositive.isInt).toEqual(false); + expect(safe.isInt).toEqual(false); + + expect(intNum.isInt).toEqual(true); + expect(multipleOfFive.isInt).toEqual(true); +}); + +test("finite getter", () => { + expect(z.number().isFinite).toEqual(false); + expect(gtFive.isFinite).toEqual(false); + expect(gteFive.isFinite).toEqual(false); + expect(minFive.isFinite).toEqual(false); + expect(positive.isFinite).toEqual(false); + expect(nonnegative.isFinite).toEqual(false); + expect(ltFive.isFinite).toEqual(false); + expect(lteFive.isFinite).toEqual(false); + expect(maxFive.isFinite).toEqual(false); + expect(negative.isFinite).toEqual(false); + expect(nonpositive.isFinite).toEqual(false); + + expect(finite.isFinite).toEqual(true); + expect(intNum.isFinite).toEqual(true); + expect(multipleOfFive.isFinite).toEqual(true); + expect(z.number().min(5).max(10).isFinite).toEqual(true); + expect(safe.isFinite).toEqual(true); +}); diff --git a/node_modules/zod/src/v3/tests/object-augmentation.test.ts b/node_modules/zod/src/v3/tests/object-augmentation.test.ts new file mode 100644 index 0000000..964ea3d --- /dev/null +++ b/node_modules/zod/src/v3/tests/object-augmentation.test.ts @@ -0,0 +1,29 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +test("object augmentation", () => { + const Animal = z + .object({ + species: z.string(), + }) + .augment({ + population: z.number(), + }); + // overwrites `species` + const ModifiedAnimal = Animal.augment({ + species: z.array(z.string()), + }); + ModifiedAnimal.parse({ + species: ["asd"], + population: 1324, + }); + + const bad = () => + ModifiedAnimal.parse({ + species: "asdf", + population: 1324, + } as any); + expect(bad).toThrow(); +}); diff --git a/node_modules/zod/src/v3/tests/object-in-es5-env.test.ts b/node_modules/zod/src/v3/tests/object-in-es5-env.test.ts new file mode 100644 index 0000000..293ebf0 --- /dev/null +++ b/node_modules/zod/src/v3/tests/object-in-es5-env.test.ts @@ -0,0 +1,29 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +const RealSet = Set; +const RealMap = Map; +const RealDate = Date; + +test("doesn’t throw when Date is undefined", () => { + delete (globalThis as any).Date; + const result = z.object({}).safeParse({}); + expect(result.success).toEqual(true); + globalThis.Date = RealDate; +}); + +test("doesn’t throw when Set is undefined", () => { + delete (globalThis as any).Set; + const result = z.object({}).safeParse({}); + expect(result.success).toEqual(true); + globalThis.Set = RealSet; +}); + +test("doesn’t throw when Map is undefined", () => { + delete (globalThis as any).Map; + const result = z.object({}).safeParse({}); + expect(result.success).toEqual(true); + globalThis.Map = RealMap; +}); diff --git a/node_modules/zod/src/v3/tests/object.test.ts b/node_modules/zod/src/v3/tests/object.test.ts new file mode 100644 index 0000000..d8772d4 --- /dev/null +++ b/node_modules/zod/src/v3/tests/object.test.ts @@ -0,0 +1,434 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; + +const Test = z.object({ + f1: z.number(), + f2: z.string().optional(), + f3: z.string().nullable(), + f4: z.array(z.object({ t: z.union([z.string(), z.boolean()]) })), +}); + +test("object type inference", () => { + type TestType = { + f1: number; + f2?: string | undefined; + f3: string | null; + f4: { t: string | boolean }[]; + }; + + util.assertEqual, TestType>(true); +}); + +test("unknown throw", () => { + const asdf: unknown = 35; + expect(() => Test.parse(asdf)).toThrow(); +}); + +test("shape() should return schema of particular key", () => { + const f1Schema = Test.shape.f1; + const f2Schema = Test.shape.f2; + const f3Schema = Test.shape.f3; + const f4Schema = Test.shape.f4; + + expect(f1Schema).toBeInstanceOf(z.ZodNumber); + expect(f2Schema).toBeInstanceOf(z.ZodOptional); + expect(f3Schema).toBeInstanceOf(z.ZodNullable); + expect(f4Schema).toBeInstanceOf(z.ZodArray); +}); + +test("correct parsing", () => { + Test.parse({ + f1: 12, + f2: "string", + f3: "string", + f4: [ + { + t: "string", + }, + ], + }); + + Test.parse({ + f1: 12, + f3: null, + f4: [ + { + t: false, + }, + ], + }); +}); + +test("incorrect #1", () => { + expect(() => Test.parse({} as any)).toThrow(); +}); + +test("nonstrict by default", () => { + z.object({ points: z.number() }).parse({ + points: 2314, + unknown: "asdf", + }); +}); + +const data = { + points: 2314, + unknown: "asdf", +}; + +test("strip by default", () => { + const val = z.object({ points: z.number() }).parse(data); + expect(val).toEqual({ points: 2314 }); +}); + +test("unknownkeys override", () => { + const val = z.object({ points: z.number() }).strict().passthrough().strip().nonstrict().parse(data); + + expect(val).toEqual(data); +}); + +test("passthrough unknown", () => { + const val = z.object({ points: z.number() }).passthrough().parse(data); + + expect(val).toEqual(data); +}); + +test("strip unknown", () => { + const val = z.object({ points: z.number() }).strip().parse(data); + + expect(val).toEqual({ points: 2314 }); +}); + +test("strict", () => { + const val = z.object({ points: z.number() }).strict().safeParse(data); + + expect(val.success).toEqual(false); +}); + +test("catchall inference", () => { + const o1 = z + .object({ + first: z.string(), + }) + .catchall(z.number()); + + const d1 = o1.parse({ first: "asdf", num: 1243 }); + util.assertEqual(true); + util.assertEqual(true); +}); + +test("catchall overrides strict", () => { + const o1 = z.object({ first: z.string().optional() }).strict().catchall(z.number()); + + // should run fine + // setting a catchall overrides the unknownKeys behavior + o1.parse({ + asdf: 1234, + }); + + // should only run catchall validation + // against unknown keys + o1.parse({ + first: "asdf", + asdf: 1234, + }); +}); + +test("catchall overrides strict", () => { + const o1 = z + .object({ + first: z.string(), + }) + .strict() + .catchall(z.number()); + + // should run fine + // setting a catchall overrides the unknownKeys behavior + o1.parse({ + first: "asdf", + asdf: 1234, + }); +}); + +test("test that optional keys are unset", async () => { + const SNamedEntity = z.object({ + id: z.string(), + set: z.string().optional(), + unset: z.string().optional(), + }); + const result = await SNamedEntity.parse({ + id: "asdf", + set: undefined, + }); + // eslint-disable-next-line ban/ban + expect(Object.keys(result)).toEqual(["id", "set"]); +}); + +test("test catchall parsing", async () => { + const result = z.object({ name: z.string() }).catchall(z.number()).parse({ name: "Foo", validExtraKey: 61 }); + + expect(result).toEqual({ name: "Foo", validExtraKey: 61 }); + + const result2 = z + .object({ name: z.string() }) + .catchall(z.number()) + .safeParse({ name: "Foo", validExtraKey: 61, invalid: "asdf" }); + + expect(result2.success).toEqual(false); +}); + +test("test nonexistent keys", async () => { + const Schema = z.union([z.object({ a: z.string() }), z.object({ b: z.number() })]); + const obj = { a: "A" }; + const result = await Schema.spa(obj); // Works with 1.11.10, breaks with 2.0.0-beta.21 + expect(result.success).toBe(true); +}); + +test("test async union", async () => { + const Schema2 = z.union([ + z.object({ + ty: z.string(), + }), + z.object({ + ty: z.number(), + }), + ]); + + const obj = { ty: "A" }; + const result = await Schema2.spa(obj); // Works with 1.11.10, breaks with 2.0.0-beta.21 + expect(result.success).toEqual(true); +}); + +test("test inferred merged type", async () => { + const asdf = z.object({ a: z.string() }).merge(z.object({ a: z.number() })); + type asdf = z.infer; + util.assertEqual(true); +}); + +test("inferred merged object type with optional properties", async () => { + const Merged = z + .object({ a: z.string(), b: z.string().optional() }) + .merge(z.object({ a: z.string().optional(), b: z.string() })); + type Merged = z.infer; + util.assertEqual(true); + // todo + // util.assertEqual(true); +}); + +test("inferred unioned object type with optional properties", async () => { + const Unioned = z.union([ + z.object({ a: z.string(), b: z.string().optional() }), + z.object({ a: z.string().optional(), b: z.string() }), + ]); + type Unioned = z.infer; + util.assertEqual(true); +}); + +test("inferred enum type", async () => { + const Enum = z.object({ a: z.string(), b: z.string().optional() }).keyof(); + + expect(Enum.Values).toEqual({ + a: "a", + b: "b", + }); + expect(Enum.enum).toEqual({ + a: "a", + b: "b", + }); + expect(Enum._def.values).toEqual(["a", "b"]); + type Enum = z.infer; + util.assertEqual(true); +}); + +test("inferred partial object type with optional properties", async () => { + const Partial = z.object({ a: z.string(), b: z.string().optional() }).partial(); + type Partial = z.infer; + util.assertEqual(true); +}); + +test("inferred picked object type with optional properties", async () => { + const Picked = z.object({ a: z.string(), b: z.string().optional() }).pick({ b: true }); + type Picked = z.infer; + util.assertEqual(true); +}); + +test("inferred type for unknown/any keys", () => { + const myType = z.object({ + anyOptional: z.any().optional(), + anyRequired: z.any(), + unknownOptional: z.unknown().optional(), + unknownRequired: z.unknown(), + }); + type myType = z.infer; + util.assertEqual< + myType, + { + anyOptional?: any; + anyRequired?: any; + unknownOptional?: unknown; + unknownRequired?: unknown; + } + >(true); +}); + +test("setKey", () => { + const base = z.object({ name: z.string() }); + const withNewKey = base.setKey("age", z.number()); + + type withNewKey = z.infer; + util.assertEqual(true); + withNewKey.parse({ name: "asdf", age: 1234 }); +}); + +test("strictcreate", async () => { + const strictObj = z.strictObject({ + name: z.string(), + }); + + const syncResult = strictObj.safeParse({ name: "asdf", unexpected: 13 }); + expect(syncResult.success).toEqual(false); + + const asyncResult = await strictObj.spa({ name: "asdf", unexpected: 13 }); + expect(asyncResult.success).toEqual(false); +}); + +test("object with refine", async () => { + const schema = z + .object({ + a: z.string().default("foo"), + b: z.number(), + }) + .refine(() => true); + expect(schema.parse({ b: 5 })).toEqual({ b: 5, a: "foo" }); + const result = await schema.parseAsync({ b: 5 }); + expect(result).toEqual({ b: 5, a: "foo" }); +}); + +test("intersection of object with date", async () => { + const schema = z.object({ + a: z.date(), + }); + expect(schema.and(schema).parse({ a: new Date(1637353595983) })).toEqual({ + a: new Date(1637353595983), + }); + const result = await schema.parseAsync({ a: new Date(1637353595983) }); + expect(result).toEqual({ a: new Date(1637353595983) }); +}); + +test("intersection of object with refine with date", async () => { + const schema = z + .object({ + a: z.date(), + }) + .refine(() => true); + expect(schema.and(schema).parse({ a: new Date(1637353595983) })).toEqual({ + a: new Date(1637353595983), + }); + const result = await schema.parseAsync({ a: new Date(1637353595983) }); + expect(result).toEqual({ a: new Date(1637353595983) }); +}); + +test("constructor key", () => { + const person = z + .object({ + name: z.string(), + }) + .strict(); + + expect(() => + person.parse({ + name: "bob dylan", + constructor: 61, + }) + ).toThrow(); +}); + +test("constructor key", () => { + const Example = z.object({ + prop: z.string(), + opt: z.number().optional(), + arr: z.string().array(), + }); + + type Example = z.infer; + util.assertEqual(true); +}); + +test("unknownkeys merging", () => { + // This one is "strict" + const schemaA = z + .object({ + a: z.string(), + }) + .strict(); + + // This one is "strip" + const schemaB = z + .object({ + b: z.string(), + }) + .catchall(z.string()); + + const mergedSchema = schemaA.merge(schemaB); + type mergedSchema = typeof mergedSchema; + util.assertEqual(true); + expect(mergedSchema._def.unknownKeys).toEqual("strip"); + + util.assertEqual(true); + expect(mergedSchema._def.catchall instanceof z.ZodString).toEqual(true); +}); + +const personToExtend = z.object({ + firstName: z.string(), + lastName: z.string(), +}); + +test("extend() should return schema with new key", () => { + const PersonWithNickname = personToExtend.extend({ nickName: z.string() }); + type PersonWithNickname = z.infer; + + const expected = { firstName: "f", nickName: "n", lastName: "l" }; + const actual = PersonWithNickname.parse(expected); + + expect(actual).toEqual(expected); + util.assertEqual(true); + util.assertEqual(true); +}); + +test("extend() should have power to override existing key", () => { + const PersonWithNumberAsLastName = personToExtend.extend({ + lastName: z.number(), + }); + type PersonWithNumberAsLastName = z.infer; + + const expected = { firstName: "f", lastName: 42 }; + const actual = PersonWithNumberAsLastName.parse(expected); + + expect(actual).toEqual(expected); + util.assertEqual(true); +}); + +test("passthrough index signature", () => { + const a = z.object({ a: z.string() }); + type a = z.infer; + util.assertEqual<{ a: string }, a>(true); + const b = a.passthrough(); + type b = z.infer; + util.assertEqual<{ a: string } & { [k: string]: unknown }, b>(true); +}); + +test("xor", () => { + type Without = { [P in Exclude]?: never }; + type XOR = T extends object ? (U extends object ? (Without & U) | (Without & T) : U) : T; + + type A = { name: string; a: number }; + type B = { name: string; b: number }; + type C = XOR; + type Outer = { data: C }; + + const _Outer: z.ZodType = z.object({ + data: z.union([z.object({ name: z.string(), a: z.number() }), z.object({ name: z.string(), b: z.number() })]), + }); +}); diff --git a/node_modules/zod/src/v3/tests/optional.test.ts b/node_modules/zod/src/v3/tests/optional.test.ts new file mode 100644 index 0000000..016c954 --- /dev/null +++ b/node_modules/zod/src/v3/tests/optional.test.ts @@ -0,0 +1,42 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +function checkErrors(a: z.ZodTypeAny, bad: any) { + let expected: any; + try { + a.parse(bad); + } catch (error) { + expected = (error as z.ZodError).formErrors; + } + try { + a.optional().parse(bad); + } catch (error) { + expect((error as z.ZodError).formErrors).toEqual(expected); + } +} + +test("Should have error messages appropriate for the underlying type", () => { + checkErrors(z.string().min(2), 1); + z.string().min(2).optional().parse(undefined); + checkErrors(z.number().gte(2), 1); + z.number().gte(2).optional().parse(undefined); + checkErrors(z.boolean(), ""); + z.boolean().optional().parse(undefined); + checkErrors(z.undefined(), null); + z.undefined().optional().parse(undefined); + checkErrors(z.null(), {}); + z.null().optional().parse(undefined); + checkErrors(z.object({}), 1); + z.object({}).optional().parse(undefined); + checkErrors(z.tuple([]), 1); + z.tuple([]).optional().parse(undefined); + checkErrors(z.unknown(), 1); + z.unknown().optional().parse(undefined); +}); + +test("unwrap", () => { + const unwrapped = z.string().optional().unwrap(); + expect(unwrapped).toBeInstanceOf(z.ZodString); +}); diff --git a/node_modules/zod/src/v3/tests/parseUtil.test.ts b/node_modules/zod/src/v3/tests/parseUtil.test.ts new file mode 100644 index 0000000..8882d4c --- /dev/null +++ b/node_modules/zod/src/v3/tests/parseUtil.test.ts @@ -0,0 +1,23 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import { type SyncParseReturnType, isAborted, isDirty, isValid } from "../helpers/parseUtil.js"; + +test("parseUtil isInvalid should use structural typing", () => { + // Test for issue #556: https://github.com/colinhacks/zod/issues/556 + const aborted: SyncParseReturnType = { status: "aborted" }; + const dirty: SyncParseReturnType = { status: "dirty", value: "whatever" }; + const valid: SyncParseReturnType = { status: "valid", value: "whatever" }; + + expect(isAborted(aborted)).toBe(true); + expect(isAborted(dirty)).toBe(false); + expect(isAborted(valid)).toBe(false); + + expect(isDirty(aborted)).toBe(false); + expect(isDirty(dirty)).toBe(true); + expect(isDirty(valid)).toBe(false); + + expect(isValid(aborted)).toBe(false); + expect(isValid(dirty)).toBe(false); + expect(isValid(valid)).toBe(true); +}); diff --git a/node_modules/zod/src/v3/tests/parser.test.ts b/node_modules/zod/src/v3/tests/parser.test.ts new file mode 100644 index 0000000..6e685f9 --- /dev/null +++ b/node_modules/zod/src/v3/tests/parser.test.ts @@ -0,0 +1,41 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +test("parse strict object with unknown keys", () => { + expect(() => + z + .object({ name: z.string() }) + .strict() + .parse({ name: "bill", unknownKey: 12 } as any) + ).toThrow(); +}); + +test("parse nonstrict object with unknown keys", () => { + z.object({ name: z.string() }).nonstrict().parse({ name: "bill", unknownKey: 12 }); +}); + +test("invalid left side of intersection", () => { + expect(() => z.intersection(z.string(), z.number()).parse(12 as any)).toThrow(); +}); + +test("invalid right side of intersection", () => { + expect(() => z.intersection(z.string(), z.number()).parse("12" as any)).toThrow(); +}); + +test("parsing non-array in tuple schema", () => { + expect(() => z.tuple([]).parse("12" as any)).toThrow(); +}); + +test("incorrect num elements in tuple", () => { + expect(() => z.tuple([]).parse(["asdf"] as any)).toThrow(); +}); + +test("invalid enum value", () => { + expect(() => z.enum(["Blue"]).parse("Red" as any)).toThrow(); +}); + +test("parsing unknown", () => { + z.string().parse("Red" as unknown); +}); diff --git a/node_modules/zod/src/v3/tests/partials.test.ts b/node_modules/zod/src/v3/tests/partials.test.ts new file mode 100644 index 0000000..a2fb6ed --- /dev/null +++ b/node_modules/zod/src/v3/tests/partials.test.ts @@ -0,0 +1,243 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { ZodNullable, ZodOptional } from "zod/v3"; +import { util } from "../helpers/util.js"; + +const nested = z.object({ + name: z.string(), + age: z.number(), + outer: z.object({ + inner: z.string(), + }), + array: z.array(z.object({ asdf: z.string() })), +}); + +test("shallow inference", () => { + const shallow = nested.partial(); + type shallow = z.infer; + type correct = { + name?: string | undefined; + age?: number | undefined; + outer?: { inner: string } | undefined; + array?: { asdf: string }[]; + }; + util.assertEqual(true); +}); + +test("shallow partial parse", () => { + const shallow = nested.partial(); + shallow.parse({}); + shallow.parse({ + name: "asdf", + age: 23143, + }); +}); + +test("deep partial inference", () => { + const deep = nested.deepPartial(); + const asdf = deep.shape.array.unwrap().element.shape.asdf.unwrap(); + asdf.parse("asdf"); + type deep = z.infer; + type correct = { + array?: { asdf?: string }[]; + name?: string | undefined; + age?: number | undefined; + outer?: { inner?: string | undefined } | undefined; + }; + + util.assertEqual(true); +}); + +test("deep partial parse", () => { + const deep = nested.deepPartial(); + + expect(deep.shape.name instanceof z.ZodOptional).toBe(true); + expect(deep.shape.outer instanceof z.ZodOptional).toBe(true); + expect(deep.shape.outer._def.innerType instanceof z.ZodObject).toBe(true); + expect(deep.shape.outer._def.innerType.shape.inner instanceof z.ZodOptional).toBe(true); + expect(deep.shape.outer._def.innerType.shape.inner._def.innerType instanceof z.ZodString).toBe(true); +}); + +test("deep partial runtime tests", () => { + const deep = nested.deepPartial(); + deep.parse({}); + deep.parse({ + outer: {}, + }); + deep.parse({ + name: "asdf", + age: 23143, + outer: { + inner: "adsf", + }, + }); +}); + +test("deep partial optional/nullable", () => { + const schema = z + .object({ + name: z.string().optional(), + age: z.number().nullable(), + }) + .deepPartial(); + + expect(schema.shape.name.unwrap()).toBeInstanceOf(ZodOptional); + expect(schema.shape.age.unwrap()).toBeInstanceOf(ZodNullable); +}); + +test("deep partial tuple", () => { + const schema = z + .object({ + tuple: z.tuple([ + z.object({ + name: z.string().optional(), + age: z.number().nullable(), + }), + ]), + }) + .deepPartial(); + + expect(schema.shape.tuple.unwrap().items[0].shape.name).toBeInstanceOf(ZodOptional); +}); + +test("deep partial inference", () => { + const mySchema = z.object({ + name: z.string(), + array: z.array(z.object({ asdf: z.string() })), + tuple: z.tuple([z.object({ value: z.string() })]), + }); + + const partialed = mySchema.deepPartial(); + type partialed = z.infer; + type expected = { + name?: string | undefined; + array?: + | { + asdf?: string | undefined; + }[] + | undefined; + tuple?: [{ value?: string }] | undefined; + }; + util.assertEqual(true); +}); + +test("required", () => { + const object = z.object({ + name: z.string(), + age: z.number().optional(), + field: z.string().optional().default("asdf"), + nullableField: z.number().nullable(), + nullishField: z.string().nullish(), + }); + + const requiredObject = object.required(); + expect(requiredObject.shape.name).toBeInstanceOf(z.ZodString); + expect(requiredObject.shape.age).toBeInstanceOf(z.ZodNumber); + expect(requiredObject.shape.field).toBeInstanceOf(z.ZodDefault); + expect(requiredObject.shape.nullableField).toBeInstanceOf(z.ZodNullable); + expect(requiredObject.shape.nullishField).toBeInstanceOf(z.ZodNullable); +}); + +test("required inference", () => { + const object = z.object({ + name: z.string(), + age: z.number().optional(), + field: z.string().optional().default("asdf"), + nullableField: z.number().nullable(), + nullishField: z.string().nullish(), + }); + + const requiredObject = object.required(); + + type required = z.infer; + type expected = { + name: string; + age: number; + field: string; + nullableField: number | null; + nullishField: string | null; + }; + util.assertEqual(true); +}); + +test("required with mask", () => { + const object = z.object({ + name: z.string(), + age: z.number().optional(), + field: z.string().optional().default("asdf"), + country: z.string().optional(), + }); + + const requiredObject = object.required({ age: true }); + expect(requiredObject.shape.name).toBeInstanceOf(z.ZodString); + expect(requiredObject.shape.age).toBeInstanceOf(z.ZodNumber); + expect(requiredObject.shape.field).toBeInstanceOf(z.ZodDefault); + expect(requiredObject.shape.country).toBeInstanceOf(z.ZodOptional); +}); + +test("required with mask -- ignore falsy values", () => { + const object = z.object({ + name: z.string(), + age: z.number().optional(), + field: z.string().optional().default("asdf"), + country: z.string().optional(), + }); + + // @ts-expect-error + const requiredObject = object.required({ age: true, country: false }); + expect(requiredObject.shape.name).toBeInstanceOf(z.ZodString); + expect(requiredObject.shape.age).toBeInstanceOf(z.ZodNumber); + expect(requiredObject.shape.field).toBeInstanceOf(z.ZodDefault); + expect(requiredObject.shape.country).toBeInstanceOf(z.ZodOptional); +}); + +test("partial with mask", async () => { + const object = z.object({ + name: z.string(), + age: z.number().optional(), + field: z.string().optional().default("asdf"), + country: z.string(), + }); + + const masked = object.partial({ age: true, field: true, name: true }).strict(); + + expect(masked.shape.name).toBeInstanceOf(z.ZodOptional); + expect(masked.shape.age).toBeInstanceOf(z.ZodOptional); + expect(masked.shape.field).toBeInstanceOf(z.ZodOptional); + expect(masked.shape.country).toBeInstanceOf(z.ZodString); + + masked.parse({ country: "US" }); + await masked.parseAsync({ country: "US" }); +}); + +test("partial with mask -- ignore falsy values", async () => { + const object = z.object({ + name: z.string(), + age: z.number().optional(), + field: z.string().optional().default("asdf"), + country: z.string(), + }); + + // @ts-expect-error + const masked = object.partial({ name: true, country: false }).strict(); + + expect(masked.shape.name).toBeInstanceOf(z.ZodOptional); + expect(masked.shape.age).toBeInstanceOf(z.ZodOptional); + expect(masked.shape.field).toBeInstanceOf(z.ZodDefault); + expect(masked.shape.country).toBeInstanceOf(z.ZodString); + + masked.parse({ country: "US" }); + await masked.parseAsync({ country: "US" }); +}); + +test("deeppartial array", () => { + const schema = z.object({ array: z.string().array().min(42) }).deepPartial(); + + // works as expected + schema.parse({}); + + // should be false, but is true + expect(schema.safeParse({ array: [] }).success).toBe(false); +}); diff --git a/node_modules/zod/src/v3/tests/pickomit.test.ts b/node_modules/zod/src/v3/tests/pickomit.test.ts new file mode 100644 index 0000000..b1056e5 --- /dev/null +++ b/node_modules/zod/src/v3/tests/pickomit.test.ts @@ -0,0 +1,111 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; + +const fish = z.object({ + name: z.string(), + age: z.number(), + nested: z.object({}), +}); + +test("pick type inference", () => { + const nameonlyFish = fish.pick({ name: true }); + type nameonlyFish = z.infer; + util.assertEqual(true); +}); + +test("pick parse - success", () => { + const nameonlyFish = fish.pick({ name: true }); + nameonlyFish.parse({ name: "bob" }); + + // @ts-expect-error checking runtime picks `name` only. + const anotherNameonlyFish = fish.pick({ name: true, age: false }); + anotherNameonlyFish.parse({ name: "bob" }); +}); + +test("pick parse - fail", () => { + fish.pick({ name: true }).parse({ name: "12" } as any); + fish.pick({ name: true }).parse({ name: "bob", age: 12 } as any); + fish.pick({ age: true }).parse({ age: 12 } as any); + + const nameonlyFish = fish.pick({ name: true }).strict(); + const bad1 = () => nameonlyFish.parse({ name: 12 } as any); + const bad2 = () => nameonlyFish.parse({ name: "bob", age: 12 } as any); + const bad3 = () => nameonlyFish.parse({ age: 12 } as any); + + // @ts-expect-error checking runtime picks `name` only. + const anotherNameonlyFish = fish.pick({ name: true, age: false }).strict(); + const bad4 = () => anotherNameonlyFish.parse({ name: "bob", age: 12 } as any); + + expect(bad1).toThrow(); + expect(bad2).toThrow(); + expect(bad3).toThrow(); + expect(bad4).toThrow(); +}); + +test("omit type inference", () => { + const nonameFish = fish.omit({ name: true }); + type nonameFish = z.infer; + util.assertEqual(true); +}); + +test("omit parse - success", () => { + const nonameFish = fish.omit({ name: true }); + nonameFish.parse({ age: 12, nested: {} }); + + // @ts-expect-error checking runtime omits `name` only. + const anotherNonameFish = fish.omit({ name: true, age: false }); + anotherNonameFish.parse({ age: 12, nested: {} }); +}); + +test("omit parse - fail", () => { + const nonameFish = fish.omit({ name: true }); + const bad1 = () => nonameFish.parse({ name: 12 } as any); + const bad2 = () => nonameFish.parse({ age: 12 } as any); + const bad3 = () => nonameFish.parse({} as any); + + // @ts-expect-error checking runtime omits `name` only. + const anotherNonameFish = fish.omit({ name: true, age: false }); + const bad4 = () => anotherNonameFish.parse({ nested: {} } as any); + + expect(bad1).toThrow(); + expect(bad2).toThrow(); + expect(bad3).toThrow(); + expect(bad4).toThrow(); +}); + +test("nonstrict inference", () => { + const laxfish = fish.pick({ name: true }).catchall(z.any()); + type laxfish = z.infer; + util.assertEqual(true); +}); + +test("nonstrict parsing - pass", () => { + const laxfish = fish.passthrough().pick({ name: true }); + laxfish.parse({ name: "asdf", whatever: "asdf" }); + laxfish.parse({ name: "asdf", age: 12, nested: {} }); +}); + +test("nonstrict parsing - fail", () => { + const laxfish = fish.passthrough().pick({ name: true }); + const bad = () => laxfish.parse({ whatever: "asdf" } as any); + expect(bad).toThrow(); +}); + +test("pick/omit/required/partial - do not allow unknown keys", () => { + const schema = z.object({ + name: z.string(), + age: z.number(), + }); + + // @ts-expect-error + schema.pick({ $unknown: true }); + // @ts-expect-error + schema.omit({ $unknown: true }); + // @ts-expect-error + schema.required({ $unknown: true }); + // @ts-expect-error + schema.partial({ $unknown: true }); +}); diff --git a/node_modules/zod/src/v3/tests/pipeline.test.ts b/node_modules/zod/src/v3/tests/pipeline.test.ts new file mode 100644 index 0000000..cc94fc5 --- /dev/null +++ b/node_modules/zod/src/v3/tests/pipeline.test.ts @@ -0,0 +1,29 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +test("string to number pipeline", () => { + const schema = z.string().transform(Number).pipe(z.number()); + expect(schema.parse("1234")).toEqual(1234); +}); + +test("string to number pipeline async", async () => { + const schema = z + .string() + .transform(async (val) => Number(val)) + .pipe(z.number()); + expect(await schema.parseAsync("1234")).toEqual(1234); +}); + +test("break if dirty", () => { + const schema = z + .string() + .refine((c) => c === "1234") + .transform(async (val) => Number(val)) + .pipe(z.number().refine((v) => v < 100)); + const r1: any = schema.safeParse("12345"); + expect(r1.error.issues.length).toBe(1); + const r2: any = schema.safeParse("3"); + expect(r2.error.issues.length).toBe(1); +}); diff --git a/node_modules/zod/src/v3/tests/preprocess.test.ts b/node_modules/zod/src/v3/tests/preprocess.test.ts new file mode 100644 index 0000000..7e1b5a1 --- /dev/null +++ b/node_modules/zod/src/v3/tests/preprocess.test.ts @@ -0,0 +1,186 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; + +test("preprocess", () => { + const schema = z.preprocess((data) => [data], z.string().array()); + + const value = schema.parse("asdf"); + expect(value).toEqual(["asdf"]); + util.assertEqual<(typeof schema)["_input"], unknown>(true); +}); + +test("async preprocess", async () => { + const schema = z.preprocess(async (data) => [data], z.string().array()); + + const value = await schema.parseAsync("asdf"); + expect(value).toEqual(["asdf"]); +}); + +test("preprocess ctx.addIssue with parse", () => { + expect(() => { + z.preprocess((data, ctx) => { + ctx.addIssue({ + code: "custom", + message: `${data} is not one of our allowed strings`, + }); + return data; + }, z.string()).parse("asdf"); + }).toThrow( + JSON.stringify( + [ + { + code: "custom", + message: "asdf is not one of our allowed strings", + path: [], + }, + ], + null, + 2 + ) + ); +}); + +test("preprocess ctx.addIssue non-fatal by default", () => { + try { + z.preprocess((data, ctx) => { + ctx.addIssue({ + code: "custom", + message: `custom error`, + }); + return data; + }, z.string()).parse(1234); + } catch (err) { + z.ZodError.assert(err); + expect(err.issues.length).toEqual(2); + } +}); + +test("preprocess ctx.addIssue fatal true", () => { + try { + z.preprocess((data, ctx) => { + ctx.addIssue({ + code: "custom", + message: `custom error`, + fatal: true, + }); + return data; + }, z.string()).parse(1234); + } catch (err) { + z.ZodError.assert(err); + expect(err.issues.length).toEqual(1); + } +}); + +test("async preprocess ctx.addIssue with parse", async () => { + const schema = z.preprocess(async (data, ctx) => { + ctx.addIssue({ + code: "custom", + message: `custom error`, + }); + return data; + }, z.string()); + + expect(await schema.safeParseAsync("asdf")).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "code": "custom", + "message": "custom error", + "path": [] + } + ]], + "success": false, + } + `); +}); + +test("preprocess ctx.addIssue with parseAsync", async () => { + const result = await z + .preprocess(async (data, ctx) => { + ctx.addIssue({ + code: "custom", + message: `${data} is not one of our allowed strings`, + }); + return data; + }, z.string()) + .safeParseAsync("asdf"); + + expect(JSON.parse(JSON.stringify(result))).toEqual({ + success: false, + error: { + issues: [ + { + code: "custom", + message: "asdf is not one of our allowed strings", + path: [], + }, + ], + name: "ZodError", + }, + }); +}); + +test("z.NEVER in preprocess", () => { + const foo = z.preprocess((val, ctx) => { + if (!val) { + ctx.addIssue({ code: z.ZodIssueCode.custom, message: "bad" }); + return z.NEVER; + } + return val; + }, z.number()); + + type foo = z.infer; + util.assertEqual(true); + const arg = foo.safeParse(undefined); + expect(arg.error!.issues).toHaveLength(2); + expect(arg.error!.issues[0].message).toEqual("bad"); +}); +test("preprocess as the second property of object", () => { + const schema = z.object({ + nonEmptyStr: z.string().min(1), + positiveNum: z.preprocess((v) => Number(v), z.number().positive()), + }); + const result = schema.safeParse({ + nonEmptyStr: "", + positiveNum: "", + }); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues.length).toEqual(2); + expect(result.error.issues[0].code).toEqual(z.ZodIssueCode.too_small); + expect(result.error.issues[1].code).toEqual(z.ZodIssueCode.too_small); + } +}); + +test("preprocess validates with sibling errors", () => { + expect(() => { + z.object({ + // Must be first + missing: z.string().refine(() => false), + preprocess: z.preprocess((data: any) => data?.trim(), z.string().regex(/ asdf/)), + }).parse({ preprocess: " asdf" }); + }).toThrow( + JSON.stringify( + [ + { + code: "invalid_type", + expected: "string", + received: "undefined", + path: ["missing"], + message: "Required", + }, + { + validation: "regex", + code: "invalid_string", + message: "Invalid", + path: ["preprocess"], + }, + ], + null, + 2 + ) + ); +}); diff --git a/node_modules/zod/src/v3/tests/primitive.test.ts b/node_modules/zod/src/v3/tests/primitive.test.ts new file mode 100644 index 0000000..48e36a2 --- /dev/null +++ b/node_modules/zod/src/v3/tests/primitive.test.ts @@ -0,0 +1,440 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; +import { Mocker } from "./Mocker.js"; + +const literalStringSchema = z.literal("asdf"); +const literalNumberSchema = z.literal(12); +const literalBooleanSchema = z.literal(true); +const literalBigIntSchema = z.literal(BigInt(42)); +const MySymbol = Symbol("stuff"); +const literalSymbolSchema = z.literal(MySymbol); +const stringSchema = z.string(); +const numberSchema = z.number(); +const bigintSchema = z.bigint(); +const booleanSchema = z.boolean(); +const dateSchema = z.date(); +const symbolSchema = z.symbol(); + +const nullSchema = z.null(); +const undefinedSchema = z.undefined(); +const stringSchemaOptional = z.string().optional(); +const stringSchemaNullable = z.string().nullable(); +const numberSchemaOptional = z.number().optional(); +const numberSchemaNullable = z.number().nullable(); +const bigintSchemaOptional = z.bigint().optional(); +const bigintSchemaNullable = z.bigint().nullable(); +const booleanSchemaOptional = z.boolean().optional(); +const booleanSchemaNullable = z.boolean().nullable(); +const dateSchemaOptional = z.date().optional(); +const dateSchemaNullable = z.date().nullable(); +const symbolSchemaOptional = z.symbol().optional(); +const symbolSchemaNullable = z.symbol().nullable(); + +const val = new Mocker(); + +test("literal string correct", () => { + expect(literalStringSchema.parse("asdf")).toBe("asdf"); +}); + +test("literal string incorrect", () => { + const f = () => literalStringSchema.parse("not_asdf"); + expect(f).toThrow(); +}); + +test("literal string number", () => { + const f = () => literalStringSchema.parse(123); + expect(f).toThrow(); +}); + +test("literal string boolean", () => { + const f = () => literalStringSchema.parse(true); + expect(f).toThrow(); +}); + +test("literal string boolean", () => { + const f = () => literalStringSchema.parse(true); + expect(f).toThrow(); +}); + +test("literal string object", () => { + const f = () => literalStringSchema.parse({}); + expect(f).toThrow(); +}); + +test("literal number correct", () => { + expect(literalNumberSchema.parse(12)).toBe(12); +}); + +test("literal number incorrect", () => { + const f = () => literalNumberSchema.parse(13); + expect(f).toThrow(); +}); + +test("literal number number", () => { + const f = () => literalNumberSchema.parse(val.string); + expect(f).toThrow(); +}); + +test("literal number boolean", () => { + const f = () => literalNumberSchema.parse(val.boolean); + expect(f).toThrow(); +}); + +test("literal number object", () => { + const f = () => literalStringSchema.parse({}); + expect(f).toThrow(); +}); + +test("literal boolean correct", () => { + expect(literalBooleanSchema.parse(true)).toBe(true); +}); + +test("literal boolean incorrect", () => { + const f = () => literalBooleanSchema.parse(false); + expect(f).toThrow(); +}); + +test("literal boolean number", () => { + const f = () => literalBooleanSchema.parse("asdf"); + expect(f).toThrow(); +}); + +test("literal boolean boolean", () => { + const f = () => literalBooleanSchema.parse(123); + expect(f).toThrow(); +}); + +test("literal boolean object", () => { + const f = () => literalBooleanSchema.parse({}); + expect(f).toThrow(); +}); + +test("literal bigint correct", () => { + expect(literalBigIntSchema.parse(BigInt(42))).toBe(BigInt(42)); +}); + +test("literal bigint incorrect", () => { + const f = () => literalBigIntSchema.parse(BigInt(43)); + expect(f).toThrow(); +}); + +test("literal bigint number", () => { + const f = () => literalBigIntSchema.parse("asdf"); + expect(f).toThrow(); +}); + +test("literal bigint boolean", () => { + const f = () => literalBigIntSchema.parse(123); + expect(f).toThrow(); +}); + +test("literal bigint object", () => { + const f = () => literalBigIntSchema.parse({}); + expect(f).toThrow(); +}); + +test("literal symbol", () => { + util.assertEqual, typeof MySymbol>(true); + literalSymbolSchema.parse(MySymbol); + expect(() => literalSymbolSchema.parse(Symbol("asdf"))).toThrow(); +}); + +test("parse stringSchema string", () => { + stringSchema.parse(val.string); +}); + +test("parse stringSchema number", () => { + const f = () => stringSchema.parse(val.number); + expect(f).toThrow(); +}); + +test("parse stringSchema boolean", () => { + const f = () => stringSchema.parse(val.boolean); + expect(f).toThrow(); +}); + +test("parse stringSchema undefined", () => { + const f = () => stringSchema.parse(val.undefined); + expect(f).toThrow(); +}); + +test("parse stringSchema null", () => { + const f = () => stringSchema.parse(val.null); + expect(f).toThrow(); +}); + +test("parse numberSchema string", () => { + const f = () => numberSchema.parse(val.string); + expect(f).toThrow(); +}); + +test("parse numberSchema number", () => { + numberSchema.parse(val.number); +}); + +test("parse numberSchema bigint", () => { + const f = () => numberSchema.parse(val.bigint); + expect(f).toThrow(); +}); + +test("parse numberSchema boolean", () => { + const f = () => numberSchema.parse(val.boolean); + expect(f).toThrow(); +}); + +test("parse numberSchema undefined", () => { + const f = () => numberSchema.parse(val.undefined); + expect(f).toThrow(); +}); + +test("parse numberSchema null", () => { + const f = () => numberSchema.parse(val.null); + expect(f).toThrow(); +}); + +test("parse bigintSchema string", () => { + const f = () => bigintSchema.parse(val.string); + expect(f).toThrow(); +}); + +test("parse bigintSchema number", () => { + const f = () => bigintSchema.parse(val.number); + expect(f).toThrow(); +}); + +test("parse bigintSchema bigint", () => { + bigintSchema.parse(val.bigint); +}); + +test("parse bigintSchema boolean", () => { + const f = () => bigintSchema.parse(val.boolean); + expect(f).toThrow(); +}); + +test("parse bigintSchema undefined", () => { + const f = () => bigintSchema.parse(val.undefined); + expect(f).toThrow(); +}); + +test("parse bigintSchema null", () => { + const f = () => bigintSchema.parse(val.null); + expect(f).toThrow(); +}); + +test("parse booleanSchema string", () => { + const f = () => booleanSchema.parse(val.string); + expect(f).toThrow(); +}); + +test("parse booleanSchema number", () => { + const f = () => booleanSchema.parse(val.number); + expect(f).toThrow(); +}); + +test("parse booleanSchema boolean", () => { + booleanSchema.parse(val.boolean); +}); + +test("parse booleanSchema undefined", () => { + const f = () => booleanSchema.parse(val.undefined); + expect(f).toThrow(); +}); + +test("parse booleanSchema null", () => { + const f = () => booleanSchema.parse(val.null); + expect(f).toThrow(); +}); + +// ============== + +test("parse dateSchema string", () => { + const f = () => dateSchema.parse(val.string); + expect(f).toThrow(); +}); + +test("parse dateSchema number", () => { + const f = () => dateSchema.parse(val.number); + expect(f).toThrow(); +}); + +test("parse dateSchema boolean", () => { + const f = () => dateSchema.parse(val.boolean); + expect(f).toThrow(); +}); + +test("parse dateSchema date", () => { + dateSchema.parse(val.date); +}); + +test("parse dateSchema undefined", () => { + const f = () => dateSchema.parse(val.undefined); + expect(f).toThrow(); +}); + +test("parse dateSchema null", () => { + const f = () => dateSchema.parse(val.null); + expect(f).toThrow(); +}); + +test("parse dateSchema invalid date", async () => { + try { + await dateSchema.parseAsync(new Date("invalid")); + } catch (err) { + expect((err as z.ZodError).issues[0].code).toEqual(z.ZodIssueCode.invalid_date); + } +}); +// ============== + +test("parse symbolSchema string", () => { + const f = () => symbolSchema.parse(val.string); + expect(f).toThrow(); +}); + +test("parse symbolSchema number", () => { + const f = () => symbolSchema.parse(val.number); + expect(f).toThrow(); +}); + +test("parse symbolSchema boolean", () => { + const f = () => symbolSchema.parse(val.boolean); + expect(f).toThrow(); +}); + +test("parse symbolSchema date", () => { + const f = () => symbolSchema.parse(val.date); + expect(f).toThrow(); +}); + +test("parse symbolSchema symbol", () => { + symbolSchema.parse(val.symbol); +}); + +test("parse symbolSchema undefined", () => { + const f = () => symbolSchema.parse(val.undefined); + expect(f).toThrow(); +}); + +test("parse symbolSchema null", () => { + const f = () => symbolSchema.parse(val.null); + expect(f).toThrow(); +}); + +// ============== + +test("parse undefinedSchema string", () => { + const f = () => undefinedSchema.parse(val.string); + expect(f).toThrow(); +}); + +test("parse undefinedSchema number", () => { + const f = () => undefinedSchema.parse(val.number); + expect(f).toThrow(); +}); + +test("parse undefinedSchema boolean", () => { + const f = () => undefinedSchema.parse(val.boolean); + expect(f).toThrow(); +}); + +test("parse undefinedSchema undefined", () => { + undefinedSchema.parse(val.undefined); +}); + +test("parse undefinedSchema null", () => { + const f = () => undefinedSchema.parse(val.null); + expect(f).toThrow(); +}); + +test("parse nullSchema string", () => { + const f = () => nullSchema.parse(val.string); + expect(f).toThrow(); +}); + +test("parse nullSchema number", () => { + const f = () => nullSchema.parse(val.number); + expect(f).toThrow(); +}); + +test("parse nullSchema boolean", () => { + const f = () => nullSchema.parse(val.boolean); + expect(f).toThrow(); +}); + +test("parse nullSchema undefined", () => { + const f = () => nullSchema.parse(val.undefined); + expect(f).toThrow(); +}); + +test("parse nullSchema null", () => { + nullSchema.parse(val.null); +}); + +test("primitive inference", () => { + util.assertEqual, "asdf">(true); + util.assertEqual, 12>(true); + util.assertEqual, true>(true); + util.assertEqual, bigint>(true); + util.assertEqual, string>(true); + util.assertEqual, number>(true); + util.assertEqual, bigint>(true); + util.assertEqual, boolean>(true); + util.assertEqual, Date>(true); + util.assertEqual, symbol>(true); + + util.assertEqual, null>(true); + util.assertEqual, undefined>(true); + util.assertEqual, string | undefined>(true); + util.assertEqual, string | null>(true); + util.assertEqual, number | undefined>(true); + util.assertEqual, number | null>(true); + util.assertEqual, bigint | undefined>(true); + util.assertEqual, bigint | null>(true); + util.assertEqual, boolean | undefined>(true); + util.assertEqual, boolean | null>(true); + util.assertEqual, Date | undefined>(true); + util.assertEqual, Date | null>(true); + util.assertEqual, symbol | undefined>(true); + util.assertEqual, symbol | null>(true); + + // [ + // literalStringSchemaTest, + // literalNumberSchemaTest, + // literalBooleanSchemaTest, + // literalBigIntSchemaTest, + // stringSchemaTest, + // numberSchemaTest, + // bigintSchemaTest, + // booleanSchemaTest, + // dateSchemaTest, + // symbolSchemaTest, + + // nullSchemaTest, + // undefinedSchemaTest, + // stringSchemaOptionalTest, + // stringSchemaNullableTest, + // numberSchemaOptionalTest, + // numberSchemaNullableTest, + // bigintSchemaOptionalTest, + // bigintSchemaNullableTest, + // booleanSchemaOptionalTest, + // booleanSchemaNullableTest, + // dateSchemaOptionalTest, + // dateSchemaNullableTest, + // symbolSchemaOptionalTest, + // symbolSchemaNullableTest, + + // ]; +}); + +test("get literal value", () => { + expect(literalStringSchema.value).toEqual("asdf"); +}); + +test("optional convenience method", () => { + z.ostring().parse(undefined); + z.onumber().parse(undefined); + z.oboolean().parse(undefined); +}); diff --git a/node_modules/zod/src/v3/tests/promise.test.ts b/node_modules/zod/src/v3/tests/promise.test.ts new file mode 100644 index 0000000..23b6de1 --- /dev/null +++ b/node_modules/zod/src/v3/tests/promise.test.ts @@ -0,0 +1,90 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; + +const promSchema = z.promise( + z.object({ + name: z.string(), + age: z.number(), + }) +); + +test("promise inference", () => { + type promSchemaType = z.infer; + util.assertEqual>(true); +}); + +test("promise parsing success", async () => { + const pr = promSchema.parse(Promise.resolve({ name: "Bobby", age: 10 })); + expect(pr).toBeInstanceOf(Promise); + const result = await pr; + expect(typeof result).toBe("object"); + expect(typeof result.age).toBe("number"); + expect(typeof result.name).toBe("string"); +}); + +test("promise parsing success 2", () => { + const fakePromise = { + then() { + return this; + }, + catch() { + return this; + }, + }; + promSchema.parse(fakePromise); +}); + +test("promise parsing fail", async () => { + const bad = promSchema.parse(Promise.resolve({ name: "Bobby", age: "10" })); + // return await expect(bad).resolves.toBe({ name: 'Bobby', age: '10' }); + return await expect(bad).rejects.toBeInstanceOf(z.ZodError); + // done(); +}); + +test("promise parsing fail 2", async () => { + const failPromise = promSchema.parse(Promise.resolve({ name: "Bobby", age: "10" })); + await expect(failPromise).rejects.toBeInstanceOf(z.ZodError); + // done();/z +}); + +test("promise parsing fail", () => { + const bad = () => promSchema.parse({ then: () => {}, catch: {} }); + expect(bad).toThrow(); +}); + +// test('sync promise parsing', () => { +// expect(() => z.promise(z.string()).parse(Promise.resolve('asfd'))).toThrow(); +// }); + +const asyncFunction = z.function(z.tuple([]), promSchema); + +test("async function pass", async () => { + const validatedFunction = asyncFunction.implement(async () => { + return { name: "jimmy", age: 14 }; + }); + await expect(validatedFunction()).resolves.toEqual({ + name: "jimmy", + age: 14, + }); +}); + +test("async function fail", async () => { + const validatedFunction = asyncFunction.implement(() => { + return Promise.resolve("asdf" as any); + }); + await expect(validatedFunction()).rejects.toBeInstanceOf(z.ZodError); +}); + +test("async promise parsing", () => { + const res = z.promise(z.number()).parseAsync(Promise.resolve(12)); + expect(res).toBeInstanceOf(Promise); +}); + +test("resolves", () => { + const foo = z.literal("foo"); + const res = z.promise(foo); + expect(res.unwrap()).toEqual(foo); +}); diff --git a/node_modules/zod/src/v3/tests/readonly.test.ts b/node_modules/zod/src/v3/tests/readonly.test.ts new file mode 100644 index 0000000..5078955 --- /dev/null +++ b/node_modules/zod/src/v3/tests/readonly.test.ts @@ -0,0 +1,194 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; + +enum testEnum { + A = 0, + B = 1, +} + +const schemas = [ + z.string().readonly(), + z.number().readonly(), + z.nan().readonly(), + z.bigint().readonly(), + z.boolean().readonly(), + z.date().readonly(), + z.undefined().readonly(), + z.null().readonly(), + z.any().readonly(), + z.unknown().readonly(), + z.void().readonly(), + z.function().args(z.string(), z.number()).readonly(), + + z.array(z.string()).readonly(), + z.tuple([z.string(), z.number()]).readonly(), + z.map(z.string(), z.date()).readonly(), + z.set(z.promise(z.string())).readonly(), + z.record(z.string()).readonly(), + z.record(z.string(), z.number()).readonly(), + z.object({ a: z.string(), 1: z.number() }).readonly(), + z.nativeEnum(testEnum).readonly(), + z.promise(z.string()).readonly(), +] as const; + +test("flat inference", () => { + util.assertEqual, string>(true); + util.assertEqual, number>(true); + util.assertEqual, number>(true); + util.assertEqual, bigint>(true); + util.assertEqual, boolean>(true); + util.assertEqual, Date>(true); + util.assertEqual, undefined>(true); + util.assertEqual, null>(true); + util.assertEqual, any>(true); + util.assertEqual, Readonly>(true); + util.assertEqual, void>(true); + util.assertEqual, (args_0: string, args_1: number, ...args_2: unknown[]) => unknown>( + true + ); + util.assertEqual, readonly string[]>(true); + + util.assertEqual, readonly [string, number]>(true); + util.assertEqual, ReadonlyMap>(true); + util.assertEqual, ReadonlySet>>(true); + util.assertEqual, Readonly>>(true); + util.assertEqual, Readonly>>(true); + util.assertEqual, { readonly a: string; readonly 1: number }>(true); + util.assertEqual, Readonly>(true); + util.assertEqual, Promise>(true); +}); + +// test("deep inference", () => { +// util.assertEqual, string>(true); +// util.assertEqual, number>(true); +// util.assertEqual, number>(true); +// util.assertEqual, bigint>(true); +// util.assertEqual, boolean>(true); +// util.assertEqual, Date>(true); +// util.assertEqual, undefined>(true); +// util.assertEqual, null>(true); +// util.assertEqual, any>(true); +// util.assertEqual< +// z.infer<(typeof deepReadonlySchemas_0)[9]>, +// Readonly +// >(true); +// util.assertEqual, void>(true); +// util.assertEqual< +// z.infer<(typeof deepReadonlySchemas_0)[11]>, +// (args_0: string, args_1: number, ...args_2: unknown[]) => unknown +// >(true); +// util.assertEqual< +// z.infer<(typeof deepReadonlySchemas_0)[12]>, +// readonly string[] +// >(true); +// util.assertEqual< +// z.infer<(typeof deepReadonlySchemas_0)[13]>, +// readonly [string, number] +// >(true); +// util.assertEqual< +// z.infer<(typeof deepReadonlySchemas_0)[14]>, +// ReadonlyMap +// >(true); +// util.assertEqual< +// z.infer<(typeof deepReadonlySchemas_0)[15]>, +// ReadonlySet> +// >(true); +// util.assertEqual< +// z.infer<(typeof deepReadonlySchemas_0)[16]>, +// Readonly> +// >(true); +// util.assertEqual< +// z.infer<(typeof deepReadonlySchemas_0)[17]>, +// Readonly> +// >(true); +// util.assertEqual< +// z.infer<(typeof deepReadonlySchemas_0)[18]>, +// { readonly a: string; readonly 1: number } +// >(true); +// util.assertEqual< +// z.infer<(typeof deepReadonlySchemas_0)[19]>, +// Readonly +// >(true); +// util.assertEqual< +// z.infer<(typeof deepReadonlySchemas_0)[20]>, +// Promise +// >(true); + +// util.assertEqual< +// z.infer, +// ReadonlyMap< +// ReadonlySet, +// { +// readonly a: { +// readonly [x: string]: readonly any[]; +// }; +// readonly b: { +// readonly c: { +// readonly d: { +// readonly e: { +// readonly f: { +// readonly g?: {}; +// }; +// }; +// }; +// }; +// }; +// } +// > +// >(true); +// }); + +test("object freezing", () => { + expect(Object.isFrozen(z.array(z.string()).readonly().parse(["a"]))).toBe(true); + expect(Object.isFrozen(z.tuple([z.string(), z.number()]).readonly().parse(["a", 1]))).toBe(true); + expect( + Object.isFrozen( + z + .map(z.string(), z.date()) + .readonly() + .parse(new Map([["a", new Date()]])) + ) + ).toBe(true); + expect( + Object.isFrozen( + z + .set(z.promise(z.string())) + .readonly() + .parse(new Set([Promise.resolve("a")])) + ) + ).toBe(true); + expect(Object.isFrozen(z.record(z.string()).readonly().parse({ a: "b" }))).toBe(true); + expect(Object.isFrozen(z.record(z.string(), z.number()).readonly().parse({ a: 1 }))).toBe(true); + expect(Object.isFrozen(z.object({ a: z.string(), 1: z.number() }).readonly().parse({ a: "b", 1: 2 }))).toBe(true); + expect(Object.isFrozen(z.promise(z.string()).readonly().parse(Promise.resolve("a")))).toBe(true); +}); + +test("async object freezing", async () => { + expect(Object.isFrozen(await z.array(z.string()).readonly().parseAsync(["a"]))).toBe(true); + expect(Object.isFrozen(await z.tuple([z.string(), z.number()]).readonly().parseAsync(["a", 1]))).toBe(true); + expect( + Object.isFrozen( + await z + .map(z.string(), z.date()) + .readonly() + .parseAsync(new Map([["a", new Date()]])) + ) + ).toBe(true); + expect( + Object.isFrozen( + await z + .set(z.promise(z.string())) + .readonly() + .parseAsync(new Set([Promise.resolve("a")])) + ) + ).toBe(true); + expect(Object.isFrozen(await z.record(z.string()).readonly().parseAsync({ a: "b" }))).toBe(true); + expect(Object.isFrozen(await z.record(z.string(), z.number()).readonly().parseAsync({ a: 1 }))).toBe(true); + expect( + Object.isFrozen(await z.object({ a: z.string(), 1: z.number() }).readonly().parseAsync({ a: "b", 1: 2 })) + ).toBe(true); + expect(Object.isFrozen(await z.promise(z.string()).readonly().parseAsync(Promise.resolve("a")))).toBe(true); +}); diff --git a/node_modules/zod/src/v3/tests/record.test.ts b/node_modules/zod/src/v3/tests/record.test.ts new file mode 100644 index 0000000..83c363f --- /dev/null +++ b/node_modules/zod/src/v3/tests/record.test.ts @@ -0,0 +1,171 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; + +const booleanRecord = z.record(z.boolean()); +type booleanRecord = z.infer; + +const recordWithEnumKeys = z.record(z.enum(["Tuna", "Salmon"]), z.string()); +type recordWithEnumKeys = z.infer; + +const recordWithLiteralKeys = z.record(z.union([z.literal("Tuna"), z.literal("Salmon")]), z.string()); +type recordWithLiteralKeys = z.infer; + +test("type inference", () => { + util.assertEqual>(true); + + util.assertEqual>>(true); + + util.assertEqual>>(true); +}); + +test("methods", () => { + booleanRecord.optional(); + booleanRecord.nullable(); +}); + +test("string record parse - pass", () => { + booleanRecord.parse({ + k1: true, + k2: false, + 1234: false, + }); +}); + +test("string record parse - fail", () => { + const badCheck = () => + booleanRecord.parse({ + asdf: 1234, + } as any); + expect(badCheck).toThrow(); + + expect(() => booleanRecord.parse("asdf")).toThrow(); +}); + +test("string record parse - fail", () => { + const badCheck = () => + booleanRecord.parse({ + asdf: {}, + } as any); + expect(badCheck).toThrow(); +}); + +test("string record parse - fail", () => { + const badCheck = () => + booleanRecord.parse({ + asdf: [], + } as any); + expect(badCheck).toThrow(); +}); + +test("key schema", () => { + const result1 = recordWithEnumKeys.parse({ + Tuna: "asdf", + Salmon: "asdf", + }); + expect(result1).toEqual({ + Tuna: "asdf", + Salmon: "asdf", + }); + + const result2 = recordWithLiteralKeys.parse({ + Tuna: "asdf", + Salmon: "asdf", + }); + expect(result2).toEqual({ + Tuna: "asdf", + Salmon: "asdf", + }); + + // shouldn't require us to specify all props in record + const result3 = recordWithEnumKeys.parse({ + Tuna: "abcd", + }); + expect(result3).toEqual({ + Tuna: "abcd", + }); + + // shouldn't require us to specify all props in record + const result4 = recordWithLiteralKeys.parse({ + Salmon: "abcd", + }); + expect(result4).toEqual({ + Salmon: "abcd", + }); + + expect(() => + recordWithEnumKeys.parse({ + Tuna: "asdf", + Salmon: "asdf", + Trout: "asdf", + }) + ).toThrow(); + + expect(() => + recordWithLiteralKeys.parse({ + Tuna: "asdf", + Salmon: "asdf", + + Trout: "asdf", + }) + ).toThrow(); +}); + +// test("record element", () => { +// expect(booleanRecord.element).toBeInstanceOf(z.ZodBoolean); +// }); + +test("key and value getters", () => { + const rec = z.record(z.string(), z.number()); + + rec.keySchema.parse("asdf"); + rec.valueSchema.parse(1234); + rec.element.parse(1234); +}); + +test("is not vulnerable to prototype pollution", async () => { + const rec = z.record( + z.object({ + a: z.string(), + }) + ); + + const data = JSON.parse(` + { + "__proto__": { + "a": "evil" + }, + "b": { + "a": "good" + } + } + `); + + const obj1 = rec.parse(data); + expect(obj1.a).toBeUndefined(); + + const obj2 = rec.safeParse(data); + expect(obj2.success).toBe(true); + if (obj2.success) { + expect(obj2.data.a).toBeUndefined(); + } + + const obj3 = await rec.parseAsync(data); + expect(obj3.a).toBeUndefined(); + + const obj4 = await rec.safeParseAsync(data); + expect(obj4.success).toBe(true); + if (obj4.success) { + expect(obj4.data.a).toBeUndefined(); + } +}); + +test("dont parse undefined values", () => { + const result1 = z.record(z.any()).parse({ foo: undefined }); + + expect(result1).toEqual({ + foo: undefined, + }); +}); diff --git a/node_modules/zod/src/v3/tests/recursive.test.ts b/node_modules/zod/src/v3/tests/recursive.test.ts new file mode 100644 index 0000000..f5bb108 --- /dev/null +++ b/node_modules/zod/src/v3/tests/recursive.test.ts @@ -0,0 +1,197 @@ +// @ts-ignore TS6133 +import { test } from "vitest"; + +import { z } from "zod/v3"; + +interface Category { + name: string; + subcategories: Category[]; +} + +const testCategory: Category = { + name: "I", + subcategories: [ + { + name: "A", + subcategories: [ + { + name: "1", + subcategories: [ + { + name: "a", + subcategories: [], + }, + ], + }, + ], + }, + ], +}; + +test("recursion with z.late.object", () => { + const Category: z.ZodType = z.late.object(() => ({ + name: z.string(), + subcategories: z.array(Category), + })); + Category.parse(testCategory); +}); + +test("recursion with z.lazy", () => { + const Category: z.ZodType = z.lazy(() => + z.object({ + name: z.string(), + subcategories: z.array(Category), + }) + ); + Category.parse(testCategory); +}); + +test("schema getter", () => { + z.lazy(() => z.string()).schema.parse("asdf"); +}); + +type LinkedList = null | { value: number; next: LinkedList }; + +const linkedListExample = { + value: 1, + next: { + value: 2, + next: { + value: 3, + next: { + value: 4, + next: null, + }, + }, + }, +}; + +test("recursion involving union type", () => { + const LinkedListSchema: z.ZodType = z.lazy(() => + z.union([ + z.null(), + z.object({ + value: z.number(), + next: LinkedListSchema, + }), + ]) + ); + LinkedListSchema.parse(linkedListExample); +}); + +// interface A { +// val: number; +// b: B; +// } + +// interface B { +// val: number; +// a: A; +// } + +// const A: z.ZodType = z.late.object(() => ({ +// val: z.number(), +// b: B, +// })); + +// const B: z.ZodType = z.late.object(() => ({ +// val: z.number(), +// a: A, +// })); + +// const Alazy: z.ZodType = z.lazy(() => z.object({ +// val: z.number(), +// b: B, +// })); + +// const Blazy: z.ZodType = z.lazy(() => z.object({ +// val: z.number(), +// a: A, +// })); + +// const a: any = { val: 1 }; +// const b: any = { val: 2 }; +// a.b = b; +// b.a = a; + +// test('valid check', () => { +// A.parse(a); +// B.parse(b); +// }); + +// test("valid check lazy", () => { +// A.parse({val:1, b:}); +// B.parse(b); +// }); + +// test('masking check', () => { +// const FragmentOnA = z +// .object({ +// val: z.number(), +// b: z +// .object({ +// val: z.number(), +// a: z +// .object({ +// val: z.number(), +// }) +// .nonstrict(), +// }) +// .nonstrict(), +// }) +// .nonstrict(); + +// const fragment = FragmentOnA.parse(a); +// fragment; +// }); + +// test('invalid check', () => { +// expect(() => A.parse({} as any)).toThrow(); +// }); + +// test('schema getter', () => { +// (A as z.ZodLazy).schema; +// }); + +// test("self recursion with cyclical data", () => { +// interface Category { +// name: string; +// subcategories: Category[]; +// } + +// const Category: z.ZodType = z.late.object(() => ({ +// name: z.string(), +// subcategories: z.array(Category), +// })); + +// const untypedCategory: any = { +// name: "Category A", +// }; +// // creating a cycle +// untypedCategory.subcategories = [untypedCategory]; +// Category.parse(untypedCategory); +// }); + +// test("self recursion with base type", () => { +// const BaseCategory = z.object({ +// name: z.string(), +// }); +// type BaseCategory = z.infer; + +// type Category = BaseCategory & { subcategories: Category[] }; + +// const Category: z.ZodType = z.late +// .object(() => ({ +// subcategories: z.array(Category), +// })) +// .extend({ +// name: z.string(), +// }); + +// const untypedCategory: any = { +// name: "Category A", +// }; +// // creating a cycle +// untypedCategory.subcategories = [untypedCategory]; +// Category.parse(untypedCategory); // parses successfully +// }); diff --git a/node_modules/zod/src/v3/tests/refine.test.ts b/node_modules/zod/src/v3/tests/refine.test.ts new file mode 100644 index 0000000..55c27fe --- /dev/null +++ b/node_modules/zod/src/v3/tests/refine.test.ts @@ -0,0 +1,313 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { ZodIssueCode } from "../ZodError.js"; +import { util } from "../helpers/util.js"; + +test("refinement", () => { + const obj1 = z.object({ + first: z.string(), + second: z.string(), + }); + const obj2 = obj1.partial().strict(); + + const obj3 = obj2.refine((data) => data.first || data.second, "Either first or second should be filled in."); + + expect(obj1 === (obj2 as any)).toEqual(false); + expect(obj2 === (obj3 as any)).toEqual(false); + + expect(() => obj1.parse({})).toThrow(); + expect(() => obj2.parse({ third: "adsf" })).toThrow(); + expect(() => obj3.parse({})).toThrow(); + obj3.parse({ first: "a" }); + obj3.parse({ second: "a" }); + obj3.parse({ first: "a", second: "a" }); +}); + +test("refinement 2", () => { + const validationSchema = z + .object({ + email: z.string().email(), + password: z.string(), + confirmPassword: z.string(), + }) + .refine((data) => data.password === data.confirmPassword, "Both password and confirmation must match"); + + expect(() => + validationSchema.parse({ + email: "aaaa@gmail.com", + password: "aaaaaaaa", + confirmPassword: "bbbbbbbb", + }) + ).toThrow(); +}); + +test("refinement type guard", () => { + const validationSchema = z.object({ + a: z.string().refine((s): s is "a" => s === "a"), + }); + type Input = z.input; + type Schema = z.infer; + + util.assertEqual<"a", Input["a"]>(false); + util.assertEqual(true); + + util.assertEqual<"a", Schema["a"]>(true); + util.assertEqual(false); +}); + +test("refinement Promise", async () => { + const validationSchema = z + .object({ + email: z.string().email(), + password: z.string(), + confirmPassword: z.string(), + }) + .refine( + (data) => Promise.resolve().then(() => data.password === data.confirmPassword), + "Both password and confirmation must match" + ); + + await validationSchema.parseAsync({ + email: "aaaa@gmail.com", + password: "password", + confirmPassword: "password", + }); +}); + +test("custom path", async () => { + const result = await z + .object({ + password: z.string(), + confirm: z.string(), + }) + .refine((data) => data.confirm === data.password, { path: ["confirm"] }) + .spa({ password: "asdf", confirm: "qewr" }); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues[0].path).toEqual(["confirm"]); + } +}); + +test("use path in refinement context", async () => { + const noNested = z.string()._refinement((_val, ctx) => { + if (ctx.path.length > 0) { + ctx.addIssue({ + code: ZodIssueCode.custom, + message: `schema cannot be nested. path: ${ctx.path.join(".")}`, + }); + return false; + } else { + return true; + } + }); + + const data = z.object({ + foo: noNested, + }); + + const t1 = await noNested.spa("asdf"); + const t2 = await data.spa({ foo: "asdf" }); + + expect(t1.success).toBe(true); + expect(t2.success).toBe(false); + if (t2.success === false) { + expect(t2.error.issues[0].message).toEqual("schema cannot be nested. path: foo"); + } +}); + +test("superRefine", () => { + const Strings = z.array(z.string()).superRefine((val, ctx) => { + if (val.length > 3) { + ctx.addIssue({ + code: z.ZodIssueCode.too_big, + maximum: 3, + type: "array", + inclusive: true, + exact: true, + message: "Too many items 😡", + }); + } + + if (val.length !== new Set(val).size) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: `No duplicates allowed.`, + }); + } + }); + + const result = Strings.safeParse(["asfd", "asfd", "asfd", "asfd"]); + + expect(result.success).toEqual(false); + if (!result.success) expect(result.error.issues.length).toEqual(2); + + Strings.parse(["asfd", "qwer"]); +}); + +test("superRefine async", async () => { + const Strings = z.array(z.string()).superRefine(async (val, ctx) => { + if (val.length > 3) { + ctx.addIssue({ + code: z.ZodIssueCode.too_big, + maximum: 3, + type: "array", + inclusive: true, + exact: true, + message: "Too many items 😡", + }); + } + + if (val.length !== new Set(val).size) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: `No duplicates allowed.`, + }); + } + }); + + const result = await Strings.safeParseAsync(["asfd", "asfd", "asfd", "asfd"]); + + expect(result.success).toEqual(false); + if (!result.success) expect(result.error.issues.length).toEqual(2); + + Strings.parseAsync(["asfd", "qwer"]); +}); + +test("superRefine - type narrowing", () => { + type NarrowType = { type: string; age: number }; + const schema = z + .object({ + type: z.string(), + age: z.number(), + }) + .nullable() + .superRefine((arg, ctx): arg is NarrowType => { + if (!arg) { + // still need to make a call to ctx.addIssue + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: "cannot be null", + fatal: true, + }); + return false; + } + return true; + }); + + util.assertEqual, NarrowType>(true); + + expect(schema.safeParse({ type: "test", age: 0 }).success).toEqual(true); + expect(schema.safeParse(null).success).toEqual(false); +}); + +test("chained mixed refining types", () => { + type firstRefinement = { first: string; second: number; third: true }; + type secondRefinement = { first: "bob"; second: number; third: true }; + type thirdRefinement = { first: "bob"; second: 33; third: true }; + const schema = z + .object({ + first: z.string(), + second: z.number(), + third: z.boolean(), + }) + .nullable() + .refine((arg): arg is firstRefinement => !!arg?.third) + .superRefine((arg, ctx): arg is secondRefinement => { + util.assertEqual(true); + if (arg.first !== "bob") { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: "`first` property must be `bob`", + }); + return false; + } + return true; + }) + .refine((arg): arg is thirdRefinement => { + util.assertEqual(true); + return arg.second === 33; + }); + + util.assertEqual, thirdRefinement>(true); +}); + +test("get inner type", () => { + z.string() + .refine(() => true) + .innerType() + .parse("asdf"); +}); + +test("chained refinements", () => { + const objectSchema = z + .object({ + length: z.number(), + size: z.number(), + }) + .refine(({ length }) => length > 5, { + path: ["length"], + message: "length greater than 5", + }) + .refine(({ size }) => size > 7, { + path: ["size"], + message: "size greater than 7", + }); + const r1 = objectSchema.safeParse({ + length: 4, + size: 9, + }); + expect(r1.success).toEqual(false); + if (!r1.success) expect(r1.error.issues.length).toEqual(1); + + const r2 = objectSchema.safeParse({ + length: 4, + size: 3, + }); + expect(r2.success).toEqual(false); + if (!r2.success) expect(r2.error.issues.length).toEqual(2); +}); + +test("fatal superRefine", () => { + const Strings = z + .string() + .superRefine((val, ctx) => { + if (val === "") { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: "foo", + fatal: true, + }); + } + }) + .superRefine((val, ctx) => { + if (val !== " ") { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: "bar", + }); + } + }); + + const result = Strings.safeParse(""); + + expect(result.success).toEqual(false); + if (!result.success) expect(result.error.issues.length).toEqual(1); +}); + +test("superRefine after skipped transform", () => { + const schema = z + .string() + .regex(/^\d+$/) + .transform((val) => Number(val)) + .superRefine((val) => { + if (typeof val !== "number") { + throw new Error("Called without transform"); + } + }); + + const result = schema.safeParse(""); + + expect(result.success).toEqual(false); +}); diff --git a/node_modules/zod/src/v3/tests/safeparse.test.ts b/node_modules/zod/src/v3/tests/safeparse.test.ts new file mode 100644 index 0000000..950a2df --- /dev/null +++ b/node_modules/zod/src/v3/tests/safeparse.test.ts @@ -0,0 +1,27 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +const stringSchema = z.string(); + +test("safeparse fail", () => { + const safe = stringSchema.safeParse(12); + expect(safe.success).toEqual(false); + expect(safe.error).toBeInstanceOf(z.ZodError); +}); + +test("safeparse pass", () => { + const safe = stringSchema.safeParse("12"); + expect(safe.success).toEqual(true); + expect(safe.data).toEqual("12"); +}); + +test("safeparse unexpected error", () => { + expect(() => + stringSchema + .refine((data) => { + throw new Error(data); + }) + .safeParse("12") + ).toThrow(); +}); diff --git a/node_modules/zod/src/v3/tests/set.test.ts b/node_modules/zod/src/v3/tests/set.test.ts new file mode 100644 index 0000000..890cdd2 --- /dev/null +++ b/node_modules/zod/src/v3/tests/set.test.ts @@ -0,0 +1,142 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { ZodIssueCode } from "zod/v3"; +import { util } from "../helpers/util.js"; + +const stringSet = z.set(z.string()); +type stringSet = z.infer; + +const minTwo = z.set(z.string()).min(2); +const maxTwo = z.set(z.string()).max(2); +const justTwo = z.set(z.string()).size(2); +const nonEmpty = z.set(z.string()).nonempty(); +const nonEmptyMax = z.set(z.string()).nonempty().max(2); + +test("type inference", () => { + util.assertEqual>(true); +}); + +test("valid parse", () => { + const result = stringSet.safeParse(new Set(["first", "second"])); + expect(result.success).toEqual(true); + if (result.success) { + expect(result.data.has("first")).toEqual(true); + expect(result.data.has("second")).toEqual(true); + expect(result.data.has("third")).toEqual(false); + } + + expect(() => { + minTwo.parse(new Set(["a", "b"])); + minTwo.parse(new Set(["a", "b", "c"])); + maxTwo.parse(new Set(["a", "b"])); + maxTwo.parse(new Set(["a"])); + justTwo.parse(new Set(["a", "b"])); + nonEmpty.parse(new Set(["a"])); + nonEmptyMax.parse(new Set(["a"])); + }).not.toThrow(); +}); + +test("valid parse async", async () => { + const result = await stringSet.spa(new Set(["first", "second"])); + expect(result.success).toEqual(true); + if (result.success) { + expect(result.data.has("first")).toEqual(true); + expect(result.data.has("second")).toEqual(true); + expect(result.data.has("third")).toEqual(false); + } + + const asyncResult = await stringSet.safeParse(new Set(["first", "second"])); + expect(asyncResult.success).toEqual(true); + if (asyncResult.success) { + expect(asyncResult.data.has("first")).toEqual(true); + expect(asyncResult.data.has("second")).toEqual(true); + expect(asyncResult.data.has("third")).toEqual(false); + } +}); + +test("valid parse: size-related methods", () => { + expect(() => { + minTwo.parse(new Set(["a", "b"])); + minTwo.parse(new Set(["a", "b", "c"])); + maxTwo.parse(new Set(["a", "b"])); + maxTwo.parse(new Set(["a"])); + justTwo.parse(new Set(["a", "b"])); + nonEmpty.parse(new Set(["a"])); + nonEmptyMax.parse(new Set(["a"])); + }).not.toThrow(); + + const sizeZeroResult = stringSet.parse(new Set()); + expect(sizeZeroResult.size).toBe(0); + + const sizeTwoResult = minTwo.parse(new Set(["a", "b"])); + expect(sizeTwoResult.size).toBe(2); +}); + +test("failing when parsing empty set in nonempty ", () => { + const result = nonEmpty.safeParse(new Set()); + expect(result.success).toEqual(false); + + if (result.success === false) { + expect(result.error.issues.length).toEqual(1); + expect(result.error.issues[0].code).toEqual(ZodIssueCode.too_small); + } +}); + +test("failing when set is smaller than min() ", () => { + const result = minTwo.safeParse(new Set(["just_one"])); + expect(result.success).toEqual(false); + + if (result.success === false) { + expect(result.error.issues.length).toEqual(1); + expect(result.error.issues[0].code).toEqual(ZodIssueCode.too_small); + } +}); + +test("failing when set is bigger than max() ", () => { + const result = maxTwo.safeParse(new Set(["one", "two", "three"])); + expect(result.success).toEqual(false); + + if (result.success === false) { + expect(result.error.issues.length).toEqual(1); + expect(result.error.issues[0].code).toEqual(ZodIssueCode.too_big); + } +}); + +test("doesn’t throw when an empty set is given", () => { + const result = stringSet.safeParse(new Set([])); + expect(result.success).toEqual(true); +}); + +test("throws when a Map is given", () => { + const result = stringSet.safeParse(new Map([])); + expect(result.success).toEqual(false); + if (result.success === false) { + expect(result.error.issues.length).toEqual(1); + expect(result.error.issues[0].code).toEqual(ZodIssueCode.invalid_type); + } +}); + +test("throws when the given set has invalid input", () => { + const result = stringSet.safeParse(new Set([Symbol()])); + expect(result.success).toEqual(false); + if (result.success === false) { + expect(result.error.issues.length).toEqual(1); + expect(result.error.issues[0].code).toEqual(ZodIssueCode.invalid_type); + expect(result.error.issues[0].path).toEqual([0]); + } +}); + +test("throws when the given set has multiple invalid entries", () => { + const result = stringSet.safeParse(new Set([1, 2] as any[]) as Set); + + expect(result.success).toEqual(false); + if (result.success === false) { + expect(result.error.issues.length).toEqual(2); + expect(result.error.issues[0].code).toEqual(ZodIssueCode.invalid_type); + expect(result.error.issues[0].path).toEqual([0]); + expect(result.error.issues[1].code).toEqual(ZodIssueCode.invalid_type); + expect(result.error.issues[1].path).toEqual([1]); + } +}); diff --git a/node_modules/zod/src/v3/tests/standard-schema.test.ts b/node_modules/zod/src/v3/tests/standard-schema.test.ts new file mode 100644 index 0000000..74b3d2b --- /dev/null +++ b/node_modules/zod/src/v3/tests/standard-schema.test.ts @@ -0,0 +1,83 @@ +// import type { StandardSchemaV1 } from "@standard-schema/spec"; +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; +import type { StandardSchemaV1 } from "../standard-schema.js"; + +test("assignability", () => { + const _s1: StandardSchemaV1 = z.string(); + const _s2: StandardSchemaV1 = z.string(); + const _s3: StandardSchemaV1 = z.string(); + const _s4: StandardSchemaV1 = z.string(); + [_s1, _s2, _s3, _s4]; +}); + +test("type inference", () => { + const stringToNumber = z.string().transform((x) => x.length); + type input = StandardSchemaV1.InferInput; + util.assertEqual(true); + type output = StandardSchemaV1.InferOutput; + util.assertEqual(true); +}); + +test("valid parse", () => { + const schema = z.string(); + const result = schema["~standard"].validate("hello"); + if (result instanceof Promise) { + throw new Error("Expected sync result"); + } + expect(result.issues).toEqual(undefined); + if (result.issues) { + throw new Error("Expected no issues"); + } else { + expect(result.value).toEqual("hello"); + } +}); + +test("invalid parse", () => { + const schema = z.string(); + const result = schema["~standard"].validate(1234); + if (result instanceof Promise) { + throw new Error("Expected sync result"); + } + expect(result.issues).toBeDefined(); + if (!result.issues) { + throw new Error("Expected issues"); + } + expect(result.issues.length).toEqual(1); + expect(result.issues[0].path).toEqual([]); +}); + +test("valid parse async", async () => { + const schema = z.string().refine(async () => true); + const _result = schema["~standard"].validate("hello"); + if (_result instanceof Promise) { + const result = await _result; + expect(result.issues).toEqual(undefined); + if (result.issues) { + throw new Error("Expected no issues"); + } else { + expect(result.value).toEqual("hello"); + } + } else { + throw new Error("Expected async result"); + } +}); + +test("invalid parse async", async () => { + const schema = z.string().refine(async () => false); + const _result = schema["~standard"].validate("hello"); + if (_result instanceof Promise) { + const result = await _result; + expect(result.issues).toBeDefined(); + if (!result.issues) { + throw new Error("Expected issues"); + } + expect(result.issues.length).toEqual(1); + expect(result.issues[0].path).toEqual([]); + } else { + throw new Error("Expected async result"); + } +}); diff --git a/node_modules/zod/src/v3/tests/string.test.ts b/node_modules/zod/src/v3/tests/string.test.ts new file mode 100644 index 0000000..c91ac53 --- /dev/null +++ b/node_modules/zod/src/v3/tests/string.test.ts @@ -0,0 +1,916 @@ +import { Buffer } from "node:buffer"; +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +const minFive = z.string().min(5, "min5"); +const maxFive = z.string().max(5, "max5"); +const justFive = z.string().length(5); +const nonempty = z.string().nonempty("nonempty"); +const includes = z.string().includes("includes"); +const includesFromIndex2 = z.string().includes("includes", { position: 2 }); +const startsWith = z.string().startsWith("startsWith"); +const endsWith = z.string().endsWith("endsWith"); + +test("passing validations", () => { + minFive.parse("12345"); + minFive.parse("123456"); + maxFive.parse("12345"); + maxFive.parse("1234"); + nonempty.parse("1"); + justFive.parse("12345"); + includes.parse("XincludesXX"); + includesFromIndex2.parse("XXXincludesXX"); + startsWith.parse("startsWithX"); + endsWith.parse("XendsWith"); +}); + +test("failing validations", () => { + expect(() => minFive.parse("1234")).toThrow(); + expect(() => maxFive.parse("123456")).toThrow(); + expect(() => nonempty.parse("")).toThrow(); + expect(() => justFive.parse("1234")).toThrow(); + expect(() => justFive.parse("123456")).toThrow(); + expect(() => includes.parse("XincludeXX")).toThrow(); + expect(() => includesFromIndex2.parse("XincludesXX")).toThrow(); + expect(() => startsWith.parse("x")).toThrow(); + expect(() => endsWith.parse("x")).toThrow(); +}); + +test("email validations", () => { + const validEmails = [ + `email@domain.com`, + `firstname.lastname@domain.com`, + `email@subdomain.domain.com`, + `firstname+lastname@domain.com`, + `1234567890@domain.com`, + `email@domain-one.com`, + `_______@domain.com`, + `email@domain.name`, + `email@domain.co.jp`, + `firstname-lastname@domain.com`, + `very.common@example.com`, + `disposable.style.email.with+symbol@example.com`, + `other.email-with-hyphen@example.com`, + `fully-qualified-domain@example.com`, + `user.name+tag+sorting@example.com`, + `x@example.com`, + `mojojojo@asdf.example.com`, + `example-indeed@strange-example.com`, + `example@s.example`, + `user-@example.org`, + `user@my-example.com`, + `a@b.cd`, + `work+user@mail.com`, + `tom@test.te-st.com`, + `something@subdomain.domain-with-hyphens.tld`, + `common'name@domain.com`, + `francois@etu.inp-n7.fr`, + ]; + const invalidEmails = [ + // no "printable characters" + // `user%example.com@example.org`, + // `mailhost!username@example.org`, + // `test/test@test.com`, + + // double @ + `francois@@etu.inp-n7.fr`, + // do not support quotes + `"email"@domain.com`, + `"e asdf sadf ?<>ail"@domain.com`, + `" "@example.org`, + `"john..doe"@example.org`, + `"very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com`, + // do not support comma + `a,b@domain.com`, + + // do not support IPv4 + `email@123.123.123.123`, + `email@[123.123.123.123]`, + `postmaster@123.123.123.123`, + `user@[68.185.127.196]`, + `ipv4@[85.129.96.247]`, + `valid@[79.208.229.53]`, + `valid@[255.255.255.255]`, + `valid@[255.0.55.2]`, + `valid@[255.0.55.2]`, + + // do not support ipv6 + `hgrebert0@[IPv6:4dc8:ac7:ce79:8878:1290:6098:5c50:1f25]`, + `bshapiro4@[IPv6:3669:c709:e981:4884:59a3:75d1:166b:9ae]`, + `jsmith@[IPv6:2001:db8::1]`, + `postmaster@[IPv6:2001:0db8:85a3:0000:0000:8a2e:0370:7334]`, + `postmaster@[IPv6:2001:0db8:85a3:0000:0000:8a2e:0370:192.168.1.1]`, + + // microsoft test cases + `plainaddress`, + `#@%^%#$@#$@#.com`, + `@domain.com`, + `Joe Smith <email@domain.com>`, + `email.domain.com`, + `email@domain@domain.com`, + `.email@domain.com`, + `email.@domain.com`, + `email..email@domain.com`, + `あいうえお@domain.com`, + `email@domain.com (Joe Smith)`, + `email@domain`, + `email@-domain.com`, + `email@111.222.333.44444`, + `email@domain..com`, + `Abc.example.com`, + `A@b@c@example.com`, + `colin..hacks@domain.com`, + `a"b(c)d,e:f;gi[j\k]l@example.com`, + `just"not"right@example.com`, + `this is"not\allowed@example.com`, + `this\ still\"not\\allowed@example.com`, + + // random + `i_like_underscore@but_its_not_allowed_in_this_part.example.com`, + `QA[icon]CHOCOLATE[icon]@test.com`, + `invalid@-start.com`, + `invalid@end.com-`, + `a.b@c.d`, + `invalid@[1.1.1.-1]`, + `invalid@[68.185.127.196.55]`, + `temp@[192.168.1]`, + `temp@[9.18.122.]`, + `double..point@test.com`, + `asdad@test..com`, + `asdad@hghg...sd...au`, + `asdad@hghg........au`, + `invalid@[256.2.2.48]`, + `invalid@[256.2.2.48]`, + `invalid@[999.465.265.1]`, + `jkibbey4@[IPv6:82c4:19a8::70a9:2aac:557::ea69:d985:28d]`, + `mlivesay3@[9952:143f:b4df:2179:49a1:5e82:b92e:6b6]`, + `gbacher0@[IPv6:bc37:4d3f:5048:2e26:37cc:248e:df8e:2f7f:af]`, + `invalid@[IPv6:5348:4ed3:5d38:67fb:e9b:acd2:c13:192.168.256.1]`, + `test@.com`, + `aaaaaaaaaaaaaaalongemailthatcausesregexDoSvulnerability@test.c`, + ]; + const emailSchema = z.string().email(); + + expect( + validEmails.every((email) => { + return emailSchema.safeParse(email).success; + }) + ).toBe(true); + expect( + invalidEmails.every((email) => { + return emailSchema.safeParse(email).success === false; + }) + ).toBe(true); +}); + +const validBase64Strings = [ + "SGVsbG8gV29ybGQ=", // "Hello World" + "VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==", // "This is an encoded string" + "TWFueSBoYW5kcyBtYWtlIGxpZ2h0IHdvcms=", // "Many hands make light work" + "UGF0aWVuY2UgaXMgdGhlIGtleSB0byBzdWNjZXNz", // "Patience is the key to success" + "QmFzZTY0IGVuY29kaW5nIGlzIGZ1bg==", // "Base64 encoding is fun" + "MTIzNDU2Nzg5MA==", // "1234567890" + "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo=", // "abcdefghijklmnopqrstuvwxyz" + "QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo=", // "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "ISIkJSMmJyonKCk=", // "!\"#$%&'()*" + "", // Empty string is technically valid base64 + "w7/Dv8O+w74K", // ÿÿþþ +]; + +for (const str of validBase64Strings) { + test(`base64 should accept ${str}`, () => { + expect(z.string().base64().safeParse(str).success).toBe(true); + }); +} + +const invalidBase64Strings = [ + "12345", // Not padded correctly, not a multiple of 4 characters + "12345===", // Not padded correctly + "SGVsbG8gV29ybGQ", // Missing padding + "VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw", // Missing padding + "!UGF0aWVuY2UgaXMgdGhlIGtleSB0byBzdWNjZXNz", // Invalid character '!' + "?QmFzZTY0IGVuY29kaW5nIGlzIGZ1bg==", // Invalid character '?' + ".MTIzND2Nzg5MC4=", // Invalid character '.' + "QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo", // Missing padding + "w7_Dv8O-w74K", // Has - and _ characters (is base64url) +]; + +for (const str of invalidBase64Strings) { + test(`base64 should reject ${str}`, () => { + expect(z.string().base64().safeParse(str).success).toBe(false); + }); +} + +const validBase64URLStrings = [ + "SGVsbG8gV29ybGQ", // "Hello World" + "SGVsbG8gV29ybGQ=", // "Hello World" with padding + "VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw", // "This is an encoded string" + "VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==", // "This is an encoded string" with padding + "TWFueSBoYW5kcyBtYWtlIGxpZ2h0IHdvcms", // "Many hands make light work" + "TWFueSBoYW5kcyBtYWtlIGxpZ2h0IHdvcms=", // "Many hands make light work" with padding + "UGF0aWVuY2UgaXMgdGhlIGtleSB0byBzdWNjZXNz", // "Patience is the key to success" + "QmFzZTY0IGVuY29kaW5nIGlzIGZ1bg", // "Base64 encoding is fun" + "QmFzZTY0IGVuY29kaW5nIGlzIGZ1bg==", // "Base64 encoding is fun" with padding + "MTIzNDU2Nzg5MA", // "1234567890" + "MTIzNDU2Nzg5MA==", // "1234567890" with padding + "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo", // "abcdefghijklmnopqrstuvwxyz" + "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo=", // "abcdefghijklmnopqrstuvwxyz with padding" + "QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo", // "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo=", // "ABCDEFGHIJKLMNOPQRSTUVWXYZ" with padding + "ISIkJSMmJyonKCk", // "!\"#$%&'()*" + "ISIkJSMmJyonKCk=", // "!\"#$%&'()*" with padding + "", // Empty string is technically valid base64url + "w7_Dv8O-w74K", // ÿÿþþ + "123456", +]; + +for (const str of validBase64URLStrings) { + test(`base64url should accept ${str}`, () => { + expect(z.string().base64url().safeParse(str).success).toBe(true); + }); +} + +const invalidBase64URLStrings = [ + "w7/Dv8O+w74K", // Has + and / characters (is base64) + "12345", // Invalid length (not a multiple of 4 characters when adding allowed number of padding characters) + "12345===", // Not padded correctly + "!UGF0aWVuY2UgaXMgdGhlIGtleSB0byBzdWNjZXNz", // Invalid character '!' + "?QmFzZTY0IGVuY29kaW5nIGlzIGZ1bg==", // Invalid character '?' + ".MTIzND2Nzg5MC4=", // Invalid character '.' +]; + +for (const str of invalidBase64URLStrings) { + test(`base64url should reject ${str}`, () => { + expect(z.string().base64url().safeParse(str).success).toBe(false); + }); +} + +function makeJwt(header: object, payload: object) { + const headerBase64 = Buffer.from(JSON.stringify(header)).toString("base64url"); + const payloadBase64 = Buffer.from(JSON.stringify(payload)).toString("base64url"); + const signature = "signature"; // Placeholder for the signature + return `${headerBase64}.${payloadBase64}.${signature}`; +} + +test("jwt validations", () => { + const jwt = z.string().jwt(); + const jwtWithAlg = z.string().jwt({ alg: "HS256" }); + + expect(() => jwt.parse("invalid")).toThrow(); + expect(() => jwt.parse("invalid.invalid")).toThrow(); + expect(() => jwt.parse("invalid.invalid.invalid")).toThrow(); + + // Valid JWTs + const d1 = makeJwt({ typ: "JWT", alg: "HS256" }, {}); + expect(() => jwt.parse(d1)).not.toThrow(); + expect(() => jwtWithAlg.parse(d1)).not.toThrow(); + + // Invalid header + const d2 = makeJwt({}, {}); + expect(() => jwt.parse(d2)).toThrow(); + + // Wrong algorithm + const d3 = makeJwt({ typ: "JWT", alg: "RS256" }, {}); + expect(() => jwtWithAlg.parse(d3)).toThrow(); + + // missing typ is fine + const d4 = makeJwt({ alg: "HS256" }, {}); + jwt.parse(d4); + + // type isn't JWT + const d5 = makeJwt({ typ: "SUP", alg: "HS256" }, { foo: "bar" }); + expect(() => jwt.parse(d5)).toThrow(); + + // Custom error message + const customMsg = "Invalid JWT token"; + const jwtWithMsg = z.string().jwt({ message: customMsg }); + try { + jwtWithMsg.parse("invalid"); + } catch (error) { + expect((error as z.ZodError).issues[0].message).toBe(customMsg); + } +}); + +test("url validations", () => { + const url = z.string().url(); + url.parse("http://google.com"); + url.parse("https://google.com/asdf?asdf=ljk3lk4&asdf=234#asdf"); + expect(() => url.parse("asdf")).toThrow(); + expect(() => url.parse("https:/")).toThrow(); + expect(() => url.parse("asdfj@lkjsdf.com")).toThrow(); +}); + +test("url error overrides", () => { + try { + z.string().url().parse("https"); + } catch (err) { + expect((err as z.ZodError).issues[0].message).toEqual("Invalid url"); + } + try { + z.string().url("badurl").parse("https"); + } catch (err) { + expect((err as z.ZodError).issues[0].message).toEqual("badurl"); + } + try { + z.string().url({ message: "badurl" }).parse("https"); + } catch (err) { + expect((err as z.ZodError).issues[0].message).toEqual("badurl"); + } +}); + +test("emoji validations", () => { + const emoji = z.string().emoji(); + + emoji.parse("👋👋👋👋"); + emoji.parse("🍺👩‍🚀🫡"); + emoji.parse("💚💙💜💛❤️"); + emoji.parse("🐛🗝🐏🍡🎦🚢🏨💫🎌☘🗡😹🔒🎬➡️🍹🗂🚨⚜🕑〽️🚦🌊🍴💍🍌💰😳🌺🍃"); + emoji.parse("🇹🇷🤽🏿‍♂️"); + emoji.parse( + "😀😁😂🤣😃😄😅😆😉😊😋😎😍😘🥰😗😙😚☺️☺🙂🤗🤩🤔🤨😐😑😶🙄😏😣😥😮🤐😯😪😫😴😌😛😜😝🤤😒😓😔😕🙃🤑😲☹️☹🙁😖😞😟😤😢😭😦😧😨😩🤯😬😰😱🥵🥶😳🤪😵😡😠🤬😷🤒🤕🤢🤮🤧😇🤠🥳🥴🥺🤥🤫🤭🧐🤓😈👿🤡👹👺💀☠️☠👻👽👾🤖💩😺😸😹😻😼😽🙀😿😾🙈🙉🙊🏻🏼🏽🏾🏿👶👶🏻👶🏼👶🏽👶🏾👶🏿🧒🧒🏻🧒🏼🧒🏽🧒🏾🧒🏿👦👦🏻👦🏼👦🏽👦🏾👦🏿👧👧🏻👧🏼👧🏽👧🏾👧🏿🧑🧑🏻🧑🏼🧑🏽🧑🏾🧑🏿👨👨🏻👨🏼👨🏽👨🏾👨🏿👩👩🏻👩🏼👩🏽👩🏾👩🏿🧓🧓🏻🧓🏼🧓🏽🧓🏾🧓🏿👴👴🏻👴🏼👴🏽👴🏾👴🏿👵👵🏻👵🏼👵🏽👵🏾👵🏿👨‍⚕️👨‍⚕👨🏻‍⚕️👨🏻‍⚕👨🏼‍⚕️👨🏼‍⚕👨🏽‍⚕️👨🏽‍⚕👨🏾‍⚕️👨🏾‍⚕👨🏿‍⚕️👨🏿‍⚕👩‍⚕️👩‍⚕👩🏻‍⚕️👩🏻‍⚕👩🏼‍⚕️👩🏼‍⚕👩🏽‍⚕️👩🏽‍⚕👩🏾‍⚕️👩🏾‍⚕👩🏿‍⚕️👩🏿‍⚕👨‍🎓👨🏻‍🎓👨🏼‍🎓👨🏽‍🎓👨🏾‍🎓👨🏿‍🎓👩‍🎓👩🏻‍🎓👩🏼‍🎓👩🏽‍🎓👩🏾‍🎓👩🏿‍🎓👨‍🏫👨🏻‍🏫👨🏼‍🏫👨🏽‍🏫👨🏾‍🏫👨🏿‍🏫👩‍🏫👩🏻‍🏫👩🏼‍🏫👩🏽‍🏫👩🏾‍🏫👩🏿‍🏫👨‍⚖️👨‍⚖👨🏻‍⚖️👨🏻‍⚖👨🏼‍⚖️👨🏼‍⚖👨🏽‍⚖️👨🏽‍⚖👨🏾‍⚖️👨🏾‍⚖👨🏿‍⚖️👨🏿‍⚖👩‍⚖️👩‍⚖👩🏻‍⚖️👩🏻‍⚖👩🏼‍⚖️👩🏼‍⚖👩🏽‍⚖️👩🏽‍⚖👩🏾‍⚖️👩🏾‍⚖👩🏿‍⚖️👩🏿‍⚖👨‍🌾👨🏻‍🌾👨🏼‍🌾👨🏽‍🌾👨🏾‍🌾👨🏿‍🌾👩‍🌾👩🏻‍🌾👩🏼‍🌾👩🏽‍🌾👩🏾‍🌾👩🏿‍🌾👨‍🍳👨🏻‍🍳👨🏼‍🍳👨🏽‍🍳👨🏾‍🍳👨🏿‍🍳👩‍🍳👩🏻‍🍳👩🏼‍🍳👩🏽‍🍳👩🏾‍🍳👩🏿‍🍳👨‍🔧👨🏻‍🔧👨🏼‍🔧👨🏽‍🔧👨🏾‍🔧👨🏿‍🔧👩‍🔧👩🏻‍🔧👩🏼‍🔧👩🏽‍🔧👩🏾‍🔧👩🏿‍🔧👨‍🏭👨🏻‍🏭👨🏼‍🏭👨🏽‍🏭👨🏾‍🏭👨🏿‍🏭👩‍🏭👩🏻‍🏭👩🏼‍🏭👩🏽‍🏭👩🏾‍🏭👩🏿‍🏭👨‍💼👨🏻‍💼👨🏼‍💼👨🏽‍💼👨🏾‍💼👨🏿‍💼👩‍💼👩🏻‍💼👩🏼‍💼👩🏽‍💼👩🏾‍💼👩🏿‍💼👨‍🔬👨🏻‍🔬👨🏼‍🔬👨🏽‍🔬👨🏾‍🔬👨🏿‍🔬👩‍🔬👩🏻‍🔬👩🏼‍🔬👩🏽‍🔬👩🏾‍🔬👩🏿‍🔬👨‍💻👨🏻‍💻👨🏼‍💻👨🏽‍💻👨🏾‍💻👨🏿‍💻👩‍💻👩🏻‍💻👩🏼‍💻👩🏽‍💻👩🏾‍💻👩🏿‍💻👨‍🎤👨🏻‍🎤👨🏼‍🎤👨🏽‍🎤👨🏾‍🎤👨🏿‍🎤👩‍🎤👩🏻‍🎤👩🏼‍🎤👩🏽‍🎤👩🏾‍🎤👩🏿‍🎤👨‍🎨👨🏻‍🎨👨🏼‍🎨👨🏽‍🎨👨🏾‍🎨👨🏿‍🎨👩‍🎨👩🏻‍🎨👩🏼‍🎨👩🏽‍🎨👩🏾‍🎨👩🏿‍🎨👨‍✈️👨‍✈👨🏻‍✈️👨🏻‍✈👨🏼‍✈️👨🏼‍✈👨🏽‍✈️👨🏽‍✈👨🏾‍✈️👨🏾‍✈👨🏿‍✈️👨🏿‍✈👩‍✈️👩‍✈👩🏻‍✈️👩🏻‍✈👩🏼‍✈️👩🏼‍✈👩🏽‍✈️👩🏽‍✈👩🏾‍✈️👩🏾‍✈👩🏿‍✈️👩🏿‍✈👨‍🚀👨🏻‍🚀👨🏼‍🚀👨🏽‍🚀👨🏾‍🚀👨🏿‍🚀👩‍🚀👩🏻‍🚀👩🏼‍🚀👩🏽‍🚀👩🏾‍🚀👩🏿‍🚀👨‍🚒👨🏻‍🚒👨🏼‍🚒👨🏽‍🚒👨🏾‍🚒👨🏿‍🚒👩‍🚒👩🏻‍🚒👩🏼‍🚒👩🏽‍🚒👩🏾‍🚒👩🏿‍🚒👮👮🏻👮🏼👮🏽👮🏾👮🏿👮‍♂️👮‍♂👮🏻‍♂️👮🏻‍♂👮🏼‍♂️👮🏼‍♂👮🏽‍♂️👮🏽‍♂👮🏾‍♂️👮🏾‍♂👮🏿‍♂️👮🏿‍♂👮‍♀️👮‍♀👮🏻‍♀️👮🏻‍♀👮🏼‍♀️👮🏼‍♀👮🏽‍♀️👮🏽‍♀👮🏾‍♀️👮🏾‍♀👮🏿‍♀️👮🏿‍♀🕵️🕵🕵🏻🕵🏼🕵🏽🕵🏾🕵🏿🕵️‍♂️🕵‍♂️🕵️‍♂🕵‍♂🕵🏻‍♂️🕵🏻‍♂🕵🏼‍♂️🕵🏼‍♂🕵🏽‍♂️🕵🏽‍♂🕵🏾‍♂️🕵🏾‍♂🕵🏿‍♂️🕵🏿‍♂🕵️‍♀️🕵‍♀️🕵️‍♀🕵‍♀🕵🏻‍♀️🕵🏻‍♀🕵🏼‍♀️🕵🏼‍♀🕵🏽‍♀️🕵🏽‍♀🕵🏾‍♀️🕵🏾‍♀🕵🏿‍♀️🕵🏿‍♀💂💂🏻💂🏼💂🏽💂🏾💂🏿💂‍♂️💂‍♂💂🏻‍♂️💂🏻‍♂💂🏼‍♂️💂🏼‍♂💂🏽‍♂️💂🏽‍♂💂🏾‍♂️💂🏾‍♂💂🏿‍♂️💂🏿‍♂💂‍♀️💂‍♀💂🏻‍♀️💂🏻‍♀💂🏼‍♀️💂🏼‍♀💂🏽‍♀️💂🏽‍♀💂🏾‍♀️💂🏾‍♀💂🏿‍♀️💂🏿‍♀👷👷🏻👷🏼👷🏽👷🏾👷🏿👷‍♂️👷‍♂👷🏻‍♂️👷🏻‍♂👷🏼‍♂️👷🏼‍♂👷🏽‍♂️👷🏽‍♂👷🏾‍♂️👷🏾‍♂👷🏿‍♂️👷🏿‍♂👷‍♀️👷‍♀👷🏻‍♀️👷🏻‍♀👷🏼‍♀️👷🏼‍♀👷🏽‍♀️👷🏽‍♀👷🏾‍♀️👷🏾‍♀👷🏿‍♀️👷🏿‍♀🤴🤴🏻🤴🏼🤴🏽🤴🏾🤴🏿👸👸🏻👸🏼👸🏽👸🏾👸🏿👳👳🏻👳🏼👳🏽👳🏾👳🏿👳‍♂️👳‍♂👳🏻‍♂️👳🏻‍♂👳🏼‍♂️👳🏼‍♂👳🏽‍♂️👳🏽‍♂👳🏾‍♂️👳🏾‍♂👳🏿‍♂️👳🏿‍♂👳‍♀️👳‍♀👳🏻‍♀️👳🏻‍♀👳🏼‍♀️👳🏼‍♀👳🏽‍♀️👳🏽‍♀👳🏾‍♀️👳🏾‍♀👳🏿‍♀️👳🏿‍♀👲👲🏻👲🏼👲🏽👲🏾👲🏿🧕🧕🏻🧕🏼🧕🏽🧕🏾🧕🏿🧔🧔🏻🧔🏼🧔🏽🧔🏾🧔🏿👱👱🏻👱🏼👱🏽👱🏾👱🏿👱‍♂️👱‍♂👱🏻‍♂️👱🏻‍♂👱🏼‍♂️👱🏼‍♂👱🏽‍♂️👱🏽‍♂👱🏾‍♂️👱🏾‍♂👱🏿‍♂️👱🏿‍♂👱‍♀️👱‍♀👱🏻‍♀️👱🏻‍♀👱🏼‍♀️👱🏼‍♀👱🏽‍♀️👱🏽‍♀👱🏾‍♀️👱🏾‍♀👱🏿‍♀️👱🏿‍♀👨‍🦰👨🏻‍🦰👨🏼‍🦰👨🏽‍🦰👨🏾‍🦰👨🏿‍🦰👩‍🦰👩🏻‍🦰👩🏼‍🦰👩🏽‍🦰👩🏾‍🦰👩🏿‍🦰👨‍🦱👨🏻‍🦱👨🏼‍🦱👨🏽‍🦱👨🏾‍🦱👨🏿‍🦱👩‍🦱👩🏻‍🦱👩🏼‍🦱👩🏽‍🦱👩🏾‍🦱👩🏿‍🦱👨‍🦲👨🏻‍🦲👨🏼‍🦲👨🏽‍🦲👨🏾‍🦲👨🏿‍🦲👩‍🦲👩🏻‍🦲👩🏼‍🦲👩🏽‍🦲👩🏾‍🦲👩🏿‍🦲👨‍🦳👨🏻‍🦳👨🏼‍🦳👨🏽‍🦳👨🏾‍🦳👨🏿‍🦳👩‍🦳👩🏻‍🦳👩🏼‍🦳👩🏽‍🦳👩🏾‍🦳👩🏿‍🦳🤵🤵🏻🤵🏼🤵🏽🤵🏾🤵🏿👰👰🏻👰🏼👰🏽👰🏾👰🏿🤰🤰🏻🤰🏼🤰🏽🤰🏾🤰🏿🤱🤱🏻🤱🏼🤱🏽🤱🏾🤱🏿👼👼🏻👼🏼👼🏽👼🏾👼🏿🎅🎅🏻🎅🏼🎅🏽🎅🏾🎅🏿🤶🤶🏻🤶🏼🤶🏽🤶🏾🤶🏿🦸🦸🏻🦸🏼🦸🏽🦸🏾🦸🏿🦸‍♀️🦸‍♀🦸🏻‍♀️🦸🏻‍♀🦸🏼‍♀️🦸🏼‍♀🦸🏽‍♀️🦸🏽‍♀🦸🏾‍♀️🦸🏾‍♀🦸🏿‍♀️🦸🏿‍♀🦸‍♂️🦸‍♂🦸🏻‍♂️🦸🏻‍♂🦸🏼‍♂️🦸🏼‍♂🦸🏽‍♂️🦸🏽‍♂🦸🏾‍♂️🦸🏾‍♂🦸🏿‍♂️🦸🏿‍♂🦹🦹🏻🦹🏼🦹🏽🦹🏾🦹🏿🦹‍♀️🦹‍♀🦹🏻‍♀️🦹🏻‍♀🦹🏼‍♀️🦹🏼‍♀🦹🏽‍♀️🦹🏽‍♀🦹🏾‍♀️🦹🏾‍♀🦹🏿‍♀️🦹🏿‍♀🦹‍♂️🦹‍♂🦹🏻‍♂️🦹🏻‍♂🦹🏼‍♂️🦹🏼‍♂🦹🏽‍♂️🦹🏽‍♂🦹🏾‍♂️🦹🏾‍♂🦹🏿‍♂️🦹🏿‍♂🧙🧙🏻🧙🏼🧙🏽🧙🏾🧙🏿🧙‍♀️🧙‍♀🧙🏻‍♀️🧙🏻‍♀🧙🏼‍♀️🧙🏼‍♀🧙🏽‍♀️🧙🏽‍♀🧙🏾‍♀️🧙🏾‍♀🧙🏿‍♀️🧙🏿‍♀🧙‍♂️🧙‍♂🧙🏻‍♂️🧙🏻‍♂🧙🏼‍♂️🧙🏼‍♂🧙🏽‍♂️🧙🏽‍♂🧙🏾‍♂️🧙🏾‍♂🧙🏿‍♂️🧙🏿‍♂🧚🧚🏻🧚🏼🧚🏽🧚🏾🧚🏿🧚‍♀️🧚‍♀🧚🏻‍♀️🧚🏻‍♀🧚🏼‍♀️🧚🏼‍♀🧚🏽‍♀️🧚🏽‍♀🧚🏾‍♀️🧚🏾‍♀🧚🏿‍♀️🧚🏿‍♀🧚‍♂️🧚‍♂🧚🏻‍♂️🧚🏻‍♂🧚🏼‍♂️🧚🏼‍♂🧚🏽‍♂️🧚🏽‍♂🧚🏾‍♂️🧚🏾‍♂🧚🏿‍♂️🧚🏿‍♂🧛🧛🏻🧛🏼🧛🏽🧛🏾🧛🏿🧛‍♀️🧛‍♀🧛🏻‍♀️🧛🏻‍♀🧛🏼‍♀️🧛🏼‍♀🧛🏽‍♀️🧛🏽‍♀🧛🏾‍♀️🧛🏾‍♀🧛🏿‍♀️🧛🏿‍♀🧛‍♂️🧛‍♂🧛🏻‍♂️🧛🏻‍♂🧛🏼‍♂️🧛🏼‍♂🧛🏽‍♂️🧛🏽‍♂🧛🏾‍♂️🧛🏾‍♂🧛🏿‍♂️🧛🏿‍♂🧜🧜🏻🧜🏼🧜🏽🧜🏾🧜🏿🧜‍♀️🧜‍♀🧜🏻‍♀️🧜🏻‍♀🧜🏼‍♀️🧜🏼‍♀🧜🏽‍♀️🧜🏽‍♀🧜🏾‍♀️🧜🏾‍♀🧜🏿‍♀️🧜🏿‍♀🧜‍♂️🧜‍♂🧜🏻‍♂️🧜🏻‍♂🧜🏼‍♂️🧜🏼‍♂🧜🏽‍♂️🧜🏽‍♂🧜🏾‍♂️🧜🏾‍♂🧜🏿‍♂️🧜🏿‍♂🧝🧝🏻🧝🏼🧝🏽🧝🏾🧝🏿🧝‍♀️🧝‍♀🧝🏻‍♀️🧝🏻‍♀🧝🏼‍♀️🧝🏼‍♀🧝🏽‍♀️🧝🏽‍♀🧝🏾‍♀️🧝🏾‍♀🧝🏿‍♀️🧝🏿‍♀🧝‍♂️🧝‍♂🧝🏻‍♂️🧝🏻‍♂🧝🏼‍♂️🧝🏼‍♂🧝🏽‍♂️🧝🏽‍♂🧝🏾‍♂️🧝🏾‍♂🧝🏿‍♂️🧝🏿‍♂🧞🧞‍♀️🧞‍♀🧞‍♂️🧞‍♂🧟🧟‍♀️🧟‍♀🧟‍♂️🧟‍♂🙍🙍🏻🙍🏼🙍🏽🙍🏾🙍🏿🙍‍♂️🙍‍♂🙍🏻‍♂️🙍🏻‍♂🙍🏼‍♂️🙍🏼‍♂🙍🏽‍♂️🙍🏽‍♂🙍🏾‍♂️🙍🏾‍♂🙍🏿‍♂️🙍🏿‍♂🙍‍♀️🙍‍♀🙍🏻‍♀️🙍🏻‍♀🙍🏼‍♀️🙍🏼‍♀🙍🏽‍♀️🙍🏽‍♀🙍🏾‍♀️🙍🏾‍♀🙍🏿‍♀️🙍🏿‍♀🙎🙎🏻🙎🏼🙎🏽🙎🏾🙎🏿🙎‍♂️🙎‍♂🙎🏻‍♂️🙎🏻‍♂🙎🏼‍♂️🙎🏼‍♂🙎🏽‍♂️🙎🏽‍♂🙎🏾‍♂️🙎🏾‍♂🙎🏿‍♂️🙎🏿‍♂🙎‍♀️🙎‍♀🙎🏻‍♀️🙎🏻‍♀🙎🏼‍♀️🙎🏼‍♀🙎🏽‍♀️🙎🏽‍♀🙎🏾‍♀️🙎🏾‍♀🙎🏿‍♀️🙎🏿‍♀🙅🙅🏻🙅🏼🙅🏽🙅🏾🙅🏿🙅‍♂️🙅‍♂🙅🏻‍♂️🙅🏻‍♂🙅🏼‍♂️🙅🏼‍♂🙅🏽‍♂️🙅🏽‍♂🙅🏾‍♂️🙅🏾‍♂🙅🏿‍♂️🙅🏿‍♂🙅‍♀️🙅‍♀🙅🏻‍♀️🙅🏻‍♀🙅🏼‍♀️🙅🏼‍♀🙅🏽‍♀️🙅🏽‍♀🙅🏾‍♀️🙅🏾‍♀🙅🏿‍♀️🙅🏿‍♀🙆🙆🏻🙆🏼🙆🏽🙆🏾🙆🏿🙆‍♂️🙆‍♂🙆🏻‍♂️🙆🏻‍♂🙆🏼‍♂️🙆🏼‍♂🙆🏽‍♂️🙆🏽‍♂🙆🏾‍♂️🙆🏾‍♂🙆🏿‍♂️🙆🏿‍♂🙆‍♀️🙆‍♀🙆🏻‍♀️🙆🏻‍♀🙆🏼‍♀️🙆🏼‍♀🙆🏽‍♀️🙆🏽‍♀🙆🏾‍♀️🙆🏾‍♀🙆🏿‍♀️🙆🏿‍♀💁💁🏻💁🏼💁🏽💁🏾💁🏿💁‍♂️💁‍♂💁🏻‍♂️💁🏻‍♂💁🏼‍♂️💁🏼‍♂💁🏽‍♂️💁🏽‍♂💁🏾‍♂️💁🏾‍♂💁🏿‍♂️💁🏿‍♂💁‍♀️💁‍♀💁🏻‍♀️💁🏻‍♀💁🏼‍♀️💁🏼‍♀💁🏽‍♀️💁🏽‍♀💁🏾‍♀️💁🏾‍♀💁🏿‍♀️💁🏿‍♀🙋🙋🏻🙋🏼🙋🏽🙋🏾🙋🏿🙋‍♂️🙋‍♂🙋🏻‍♂️🙋🏻‍♂🙋🏼‍♂️🙋🏼‍♂🙋🏽‍♂️🙋🏽‍♂🙋🏾‍♂️🙋🏾‍♂🙋🏿‍♂️🙋🏿‍♂🙋‍♀️🙋‍♀🙋🏻‍♀️🙋🏻‍♀🙋🏼‍♀️🙋🏼‍♀🙋🏽‍♀️🙋🏽‍♀🙋🏾‍♀️🙋🏾‍♀🙋🏿‍♀️🙋🏿‍♀🙇🙇🏻🙇🏼🙇🏽🙇🏾🙇🏿🙇‍♂️🙇‍♂🙇🏻‍♂️🙇🏻‍♂🙇🏼‍♂️🙇🏼‍♂🙇🏽‍♂️🙇🏽‍♂🙇🏾‍♂️🙇🏾‍♂🙇🏿‍♂️🙇🏿‍♂🙇‍♀️🙇‍♀🙇🏻‍♀️🙇🏻‍♀🙇🏼‍♀️🙇🏼‍♀🙇🏽‍♀️🙇🏽‍♀🙇🏾‍♀️🙇🏾‍♀🙇🏿‍♀️🙇🏿‍♀🤦🤦🏻🤦🏼🤦🏽🤦🏾🤦🏿🤦‍♂️🤦‍♂🤦🏻‍♂️🤦🏻‍♂🤦🏼‍♂️🤦🏼‍♂🤦🏽‍♂️🤦🏽‍♂🤦🏾‍♂️🤦🏾‍♂🤦🏿‍♂️🤦🏿‍♂🤦‍♀️🤦‍♀🤦🏻‍♀️🤦🏻‍♀🤦🏼‍♀️🤦🏼‍♀🤦🏽‍♀️🤦🏽‍♀🤦🏾‍♀️🤦🏾‍♀🤦🏿‍♀️🤦🏿‍♀🤷🤷🏻🤷🏼🤷🏽🤷🏾🤷🏿🤷‍♂️🤷‍♂🤷🏻‍♂️🤷🏻‍♂🤷🏼‍♂️🤷🏼‍♂🤷🏽‍♂️🤷🏽‍♂🤷🏾‍♂️🤷🏾‍♂🤷🏿‍♂️🤷🏿‍♂🤷‍♀️🤷‍♀🤷🏻‍♀️🤷🏻‍♀🤷🏼‍♀️🤷🏼‍♀🤷🏽‍♀️🤷🏽‍♀🤷🏾‍♀️🤷🏾‍♀🤷🏿‍♀️🤷🏿‍♀💆💆🏻💆🏼💆🏽💆🏾💆🏿💆‍♂️💆‍♂💆🏻‍♂️💆🏻‍♂💆🏼‍♂️💆🏼‍♂💆🏽‍♂️💆🏽‍♂💆🏾‍♂️💆🏾‍♂💆🏿‍♂️💆🏿‍♂💆‍♀️💆‍♀💆🏻‍♀️💆🏻‍♀💆🏼‍♀️💆🏼‍♀💆🏽‍♀️💆🏽‍♀💆🏾‍♀️💆🏾‍♀💆🏿‍♀️💆🏿‍♀💇💇🏻💇🏼💇🏽💇🏾💇🏿💇‍♂️💇‍♂💇🏻‍♂️💇🏻‍♂💇🏼‍♂️💇🏼‍♂💇🏽‍♂️💇🏽‍♂💇🏾‍♂️💇🏾‍♂💇🏿‍♂️💇🏿‍♂💇‍♀️💇‍♀💇🏻‍♀️💇🏻‍♀💇🏼‍♀️💇🏼‍♀💇🏽‍♀️💇🏽‍♀💇🏾‍♀️💇🏾‍♀💇🏿‍♀️💇🏿‍♀🚶🚶🏻🚶🏼🚶🏽🚶🏾🚶🏿🚶‍♂️🚶‍♂🚶🏻‍♂️🚶🏻‍♂🚶🏼‍♂️🚶🏼‍♂🚶🏽‍♂️🚶🏽‍♂🚶🏾‍♂️🚶🏾‍♂🚶🏿‍♂️🚶🏿‍♂🚶‍♀️🚶‍♀🚶🏻‍♀️🚶🏻‍♀🚶🏼‍♀️🚶🏼‍♀🚶🏽‍♀️🚶🏽‍♀🚶🏾‍♀️🚶🏾‍♀🚶🏿‍♀️🚶🏿‍♀🏃🏃🏻🏃🏼🏃🏽🏃🏾🏃🏿🏃‍♂️🏃‍♂🏃🏻‍♂️🏃🏻‍♂🏃🏼‍♂️🏃🏼‍♂🏃🏽‍♂️🏃🏽‍♂🏃🏾‍♂️🏃🏾‍♂🏃🏿‍♂️🏃🏿‍♂🏃‍♀️🏃‍♀🏃🏻‍♀️🏃🏻‍♀🏃🏼‍♀️🏃🏼‍♀🏃🏽‍♀️🏃🏽‍♀🏃🏾‍♀️🏃🏾‍♀🏃🏿‍♀️🏃🏿‍♀💃💃🏻💃🏼💃🏽💃🏾💃🏿🕺🕺🏻🕺🏼🕺🏽🕺🏾🕺🏿👯👯‍♂️👯‍♂👯‍♀️👯‍♀🧖🧖🏻🧖🏼🧖🏽🧖🏾🧖🏿🧖‍♀️🧖‍♀🧖🏻‍♀️🧖🏻‍♀🧖🏼‍♀️🧖🏼‍♀🧖🏽‍♀️🧖🏽‍♀🧖🏾‍♀️🧖🏾‍♀🧖🏿‍♀️🧖🏿‍♀🧖‍♂️🧖‍♂🧖🏻‍♂️🧖🏻‍♂🧖🏼‍♂️🧖🏼‍♂🧖🏽‍♂️🧖🏽‍♂🧖🏾‍♂️🧖🏾‍♂🧖🏿‍♂️🧖🏿‍♂🧗🧗🏻🧗🏼🧗🏽🧗🏾🧗🏿🧗‍♀️🧗‍♀🧗🏻‍♀️🧗🏻‍♀🧗🏼‍♀️🧗🏼‍♀🧗🏽‍♀️🧗🏽‍♀🧗🏾‍♀️🧗🏾‍♀🧗🏿‍♀️🧗🏿‍♀🧗‍♂️🧗‍♂🧗🏻‍♂️🧗🏻‍♂🧗🏼‍♂️🧗🏼‍♂🧗🏽‍♂️🧗🏽‍♂🧗🏾‍♂️🧗🏾‍♂🧗🏿‍♂️🧗🏿‍♂🧘🧘🏻🧘🏼🧘🏽🧘🏾🧘🏿🧘‍♀️🧘‍♀🧘🏻‍♀️🧘🏻‍♀🧘🏼‍♀️🧘🏼‍♀🧘🏽‍♀️🧘🏽‍♀🧘🏾‍♀️🧘🏾‍♀🧘🏿‍♀️🧘🏿‍♀🧘‍♂️🧘‍♂🧘🏻‍♂️🧘🏻‍♂🧘🏼‍♂️🧘🏼‍♂🧘🏽‍♂️🧘🏽‍♂🧘🏾‍♂️🧘🏾‍♂🧘🏿‍♂️🧘🏿‍♂🛀🛀🏻🛀🏼🛀🏽🛀🏾🛀🏿🛌🛌🏻🛌🏼🛌🏽🛌🏾🛌🏿🕴️🕴🕴🏻🕴🏼🕴🏽🕴🏾🕴🏿🗣️🗣👤👥🤺🏇🏇🏻🏇🏼🏇🏽🏇🏾🏇🏿⛷️⛷🏂🏂🏻🏂🏼🏂🏽🏂🏾🏂🏿🏌️🏌🏌🏻🏌🏼🏌🏽🏌🏾🏌🏿🏌️‍♂️🏌‍♂️🏌️‍♂🏌‍♂🏌🏻‍♂️🏌🏻‍♂🏌🏼‍♂️🏌🏼‍♂🏌🏽‍♂️🏌🏽‍♂🏌🏾‍♂️🏌🏾‍♂🏌🏿‍♂️🏌🏿‍♂🏌️‍♀️🏌‍♀️🏌️‍♀🏌‍♀🏌🏻‍♀️🏌🏻‍♀🏌🏼‍♀️🏌🏼‍♀🏌🏽‍♀️🏌🏽‍♀🏌🏾‍♀️🏌🏾‍♀🏌🏿‍♀️🏌🏿‍♀🏄🏄🏻🏄🏼🏄🏽🏄🏾🏄🏿🏄‍♂️🏄‍♂🏄🏻‍♂️🏄🏻‍♂🏄🏼‍♂️🏄🏼‍♂🏄🏽‍♂️🏄🏽‍♂🏄🏾‍♂️🏄🏾‍♂🏄🏿‍♂️🏄🏿‍♂🏄‍♀️🏄‍♀🏄🏻‍♀️🏄🏻‍♀🏄🏼‍♀️🏄🏼‍♀🏄🏽‍♀️🏄🏽‍♀🏄🏾‍♀️🏄🏾‍♀🏄🏿‍♀️🏄🏿‍♀🚣🚣🏻🚣🏼🚣🏽🚣🏾🚣🏿🚣‍♂️🚣‍♂🚣🏻‍♂️🚣🏻‍♂🚣🏼‍♂️🚣🏼‍♂🚣🏽‍♂️🚣🏽‍♂🚣🏾‍♂️🚣🏾‍♂🚣🏿‍♂️🚣🏿‍♂🚣‍♀️🚣‍♀🚣🏻‍♀️🚣🏻‍♀🚣🏼‍♀️🚣🏼‍♀🚣🏽‍♀️🚣🏽‍♀🚣🏾‍♀️🚣🏾‍♀🚣🏿‍♀️🚣🏿‍♀🏊🏊🏻🏊🏼🏊🏽🏊🏾🏊🏿🏊‍♂️🏊‍♂🏊🏻‍♂️🏊🏻‍♂🏊🏼‍♂️🏊🏼‍♂🏊🏽‍♂️🏊🏽‍♂🏊🏾‍♂️🏊🏾‍♂🏊🏿‍♂️🏊🏿‍♂🏊‍♀️🏊‍♀🏊🏻‍♀️🏊🏻‍♀🏊🏼‍♀️🏊🏼‍♀🏊🏽‍♀️🏊🏽‍♀🏊🏾‍♀️🏊🏾‍♀🏊🏿‍♀️🏊🏿‍♀⛹️⛹⛹🏻⛹🏼⛹🏽⛹🏾⛹🏿⛹️‍♂️⛹‍♂️⛹️‍♂⛹‍♂⛹🏻‍♂️⛹🏻‍♂⛹🏼‍♂️⛹🏼‍♂⛹🏽‍♂️⛹🏽‍♂⛹🏾‍♂️⛹🏾‍♂⛹🏿‍♂️⛹🏿‍♂⛹️‍♀️⛹‍♀️⛹️‍♀⛹‍♀⛹🏻‍♀️⛹🏻‍♀⛹🏼‍♀️⛹🏼‍♀⛹🏽‍♀️⛹🏽‍♀⛹🏾‍♀️⛹🏾‍♀⛹🏿‍♀️⛹🏿‍♀🏋️🏋🏋🏻🏋🏼🏋🏽🏋🏾🏋🏿🏋️‍♂️🏋‍♂️🏋️‍♂🏋‍♂🏋🏻‍♂️🏋🏻‍♂🏋🏼‍♂️🏋🏼‍♂🏋🏽‍♂️🏋🏽‍♂🏋🏾‍♂️🏋🏾‍♂🏋🏿‍♂️🏋🏿‍♂🏋️‍♀️🏋‍♀️🏋️‍♀🏋‍♀🏋🏻‍♀️🏋🏻‍♀🏋🏼‍♀️🏋🏼‍♀🏋🏽‍♀️🏋🏽‍♀🏋🏾‍♀️🏋🏾‍♀🏋🏿‍♀️🏋🏿‍♀🚴🚴🏻🚴🏼🚴🏽🚴🏾🚴🏿🚴‍♂️🚴‍♂🚴🏻‍♂️🚴🏻‍♂🚴🏼‍♂️🚴🏼‍♂🚴🏽‍♂️🚴🏽‍♂🚴🏾‍♂️🚴🏾‍♂🚴🏿‍♂️🚴🏿‍♂🚴‍♀️🚴‍♀🚴🏻‍♀️🚴🏻‍♀🚴🏼‍♀️🚴🏼‍♀🚴🏽‍♀️🚴🏽‍♀🚴🏾‍♀️🚴🏾‍♀🚴🏿‍♀️🚴🏿‍♀🚵🚵🏻🚵🏼🚵🏽🚵🏾🚵🏿🚵‍♂️🚵‍♂🚵🏻‍♂️🚵🏻‍♂🚵🏼‍♂️🚵🏼‍♂🚵🏽‍♂️🚵🏽‍♂🚵🏾‍♂️🚵🏾‍♂🚵🏿‍♂️🚵🏿‍♂🚵‍♀️🚵‍♀🚵🏻‍♀️🚵🏻‍♀🚵🏼‍♀️🚵🏼‍♀🚵🏽‍♀️🚵🏽‍♀🚵🏾‍♀️🚵🏾‍♀🚵🏿‍♀️🚵🏿‍♀🏎️🏎🏍️🏍🤸🤸🏻🤸🏼🤸🏽🤸🏾🤸🏿🤸‍♂️🤸‍♂🤸🏻‍♂️🤸🏻‍♂🤸🏼‍♂️🤸🏼‍♂🤸🏽‍♂️🤸🏽‍♂🤸🏾‍♂️🤸🏾‍♂🤸🏿‍♂️🤸🏿‍♂🤸‍♀️🤸‍♀🤸🏻‍♀️🤸🏻‍♀🤸🏼‍♀️🤸🏼‍♀🤸🏽‍♀️🤸🏽‍♀🤸🏾‍♀️🤸🏾‍♀🤸🏿‍♀️🤸🏿‍♀🤼🤼‍♂️🤼‍♂🤼‍♀️🤼‍♀🤽🤽🏻🤽🏼🤽🏽🤽🏾🤽🏿🤽‍♂️🤽‍♂🤽🏻‍♂️🤽🏻‍♂🤽🏼‍♂️🤽🏼‍♂🤽🏽‍♂️🤽🏽‍♂🤽🏾‍♂️🤽🏾‍♂🤽🏿‍♂️🤽🏿‍♂🤽‍♀️🤽‍♀🤽🏻‍♀️🤽🏻‍♀🤽🏼‍♀️🤽🏼‍♀🤽🏽‍♀️🤽🏽‍♀🤽🏾‍♀️🤽🏾‍♀🤽🏿‍♀️🤽🏿‍♀🤾🤾🏻🤾🏼🤾🏽🤾🏾🤾🏿🤾‍♂️🤾‍♂🤾🏻‍♂️🤾🏻‍♂🤾🏼‍♂️🤾🏼‍♂🤾🏽‍♂️🤾🏽‍♂🤾🏾‍♂️🤾🏾‍♂🤾🏿‍♂️🤾🏿‍♂🤾‍♀️🤾‍♀🤾🏻‍♀️🤾🏻‍♀🤾🏼‍♀️🤾🏼‍♀🤾🏽‍♀️🤾🏽‍♀🤾🏾‍♀️🤾🏾‍♀🤾🏿‍♀️🤾🏿‍♀🤹🤹🏻🤹🏼🤹🏽🤹🏾🤹🏿🤹‍♂️🤹‍♂🤹🏻‍♂️🤹🏻‍♂🤹🏼‍♂️🤹🏼‍♂🤹🏽‍♂️🤹🏽‍♂🤹🏾‍♂️🤹🏾‍♂🤹🏿‍♂️🤹🏿‍♂🤹‍♀️🤹‍♀🤹🏻‍♀️🤹🏻‍♀🤹🏼‍♀️🤹🏼‍♀🤹🏽‍♀️🤹🏽‍♀🤹🏾‍♀️🤹🏾‍♀🤹🏿‍♀️🤹🏿‍♀👫👬👭💏👩‍❤️‍💋‍👨👩‍❤‍💋‍👨👨‍❤️‍💋‍👨👨‍❤‍💋‍👨👩‍❤️‍💋‍👩👩‍❤‍💋‍👩💑👩‍❤️‍👨👩‍❤‍👨👨‍❤️‍👨👨‍❤‍👨👩‍❤️‍👩👩‍❤‍👩👪👨‍👩‍👦👨‍👩‍👧👨‍👩‍👧‍👦👨‍👩‍👦‍👦👨‍👩‍👧‍👧👨‍👨‍👦👨‍👨‍👧👨‍👨‍👧‍👦👨‍👨‍👦‍👦👨‍👨‍👧‍👧👩‍👩‍👦👩‍👩‍👧👩‍👩‍👧‍👦👩‍👩‍👦‍👦👩‍👩‍👧‍👧👨‍👦👨‍👦‍👦👨‍👧👨‍👧‍👦👨‍👧‍👧👩‍👦👩‍👦‍👦👩‍👧👩‍👧‍👦👩‍👧‍👧🤳🤳🏻🤳🏼🤳🏽🤳🏾🤳🏿💪💪🏻💪🏼💪🏽💪🏾💪🏿🦵🦵🏻🦵🏼🦵🏽🦵🏾🦵🏿🦶🦶🏻🦶🏼🦶🏽🦶🏾🦶🏿👈👈🏻👈🏼👈🏽👈🏾👈🏿👉👉🏻👉🏼👉🏽👉🏾👉🏿☝️☝☝🏻☝🏼☝🏽☝🏾☝🏿👆👆🏻👆🏼👆🏽👆🏾👆🏿🖕🖕🏻🖕🏼🖕🏽🖕🏾🖕🏿👇👇🏻👇🏼👇🏽👇🏾👇🏿✌️✌✌🏻✌🏼✌🏽✌🏾✌🏿🤞🤞🏻🤞🏼🤞🏽🤞🏾🤞🏿🖖🖖🏻🖖🏼🖖🏽🖖🏾🖖🏿🤘🤘🏻🤘🏼🤘🏽🤘🏾🤘🏿🤙🤙🏻🤙🏼🤙🏽🤙🏾🤙🏿🖐️🖐🖐🏻🖐🏼🖐🏽🖐🏾🖐🏿✋✋🏻✋🏼✋🏽✋🏾✋🏿👌👌🏻👌🏼👌🏽👌🏾👌🏿👍👍🏻👍🏼👍🏽👍🏾👍🏿👎👎🏻👎🏼👎🏽👎🏾👎🏿✊✊🏻✊🏼✊🏽✊🏾✊🏿👊👊🏻👊🏼👊🏽👊🏾👊🏿🤛🤛🏻🤛🏼🤛🏽🤛🏾🤛🏿🤜🤜🏻🤜🏼🤜🏽🤜🏾🤜🏿🤚🤚🏻🤚🏼🤚🏽🤚🏾🤚🏿👋👋🏻👋🏼👋🏽👋🏾👋🏿🤟🤟🏻🤟🏼🤟🏽🤟🏾🤟🏿✍️✍✍🏻✍🏼✍🏽✍🏾✍🏿👏👏🏻👏🏼👏🏽👏🏾👏🏿👐👐🏻👐🏼👐🏽👐🏾👐🏿🙌🙌🏻🙌🏼🙌🏽🙌🏾🙌🏿🤲🤲🏻🤲🏼🤲🏽🤲🏾🤲🏿🙏🙏🏻🙏🏼🙏🏽🙏🏾🙏🏿🤝💅💅🏻💅🏼💅🏽💅🏾💅🏿👂👂🏻👂🏼👂🏽👂🏾👂🏿👃👃🏻👃🏼👃🏽👃🏾👃🏿🦰🦱🦲🦳👣👀👁️👁👁️‍🗨️👁‍🗨️👁️‍🗨👁‍🗨🧠🦴🦷👅👄💋💘❤️❤💓💔💕💖💗💙💚💛🧡💜🖤💝💞💟❣️❣💌💤💢💣💥💦💨💫💬🗨️🗨🗯️🗯💭🕳️🕳👓🕶️🕶🥽🥼👔👕👖🧣🧤🧥🧦👗👘👙👚👛👜👝🛍️🛍🎒👞👟🥾🥿👠👡👢👑👒🎩🎓🧢⛑️⛑📿💄💍💎🐵🐒🦍🐶🐕🐩🐺🦊🦝🐱🐈🦁🐯🐅🐆🐴🐎🦄🦓🦌🐮🐂🐃🐄🐷🐖🐗🐽🐏🐑🐐🐪🐫🦙🦒🐘🦏🦛🐭🐁🐀🐹🐰🐇🐿️🐿🦔🦇🐻🐨🐼🦘🦡🐾🦃🐔🐓🐣🐤🐥🐦🐧🕊️🕊🦅🦆🦢🦉🦚🦜🐸🐊🐢🦎🐍🐲🐉🦕🦖🐳🐋🐬🐟🐠🐡🦈🐙🐚🦀🦞🦐🦑🐌🦋🐛🐜🐝🐞🦗🕷️🕷🕸️🕸🦂🦟🦠💐🌸💮🏵️🏵🌹🥀🌺🌻🌼🌷🌱🌲🌳🌴🌵🌾🌿☘️☘🍀🍁🍂🍃🍇🍈🍉🍊🍋🍌🍍🥭🍎🍏🍐🍑🍒🍓🥝🍅🥥🥑🍆🥔🥕🌽🌶️🌶🥒🥬🥦🍄🥜🌰🍞🥐🥖🥨🥯🥞🧀🍖🍗🥩🥓🍔🍟🍕🌭🥪🌮🌯🥙🥚🍳🥘🍲🥣🥗🍿🧂🥫🍱🍘🍙🍚🍛🍜🍝🍠🍢🍣🍤🍥🥮🍡🥟🥠🥡🍦🍧🍨🍩🍪🎂🍰🧁🥧🍫🍬🍭🍮🍯🍼🥛☕🍵🍶🍾🍷🍸🍹🍺🍻🥂🥃🥤🥢🍽️🍽🍴🥄🔪🏺🌍🌎🌏🌐🗺️🗺🗾🧭🏔️🏔⛰️⛰🌋🗻🏕️🏕🏖️🏖🏜️🏜🏝️🏝🏞️🏞🏟️🏟🏛️🏛🏗️🏗🧱🏘️🏘🏚️🏚🏠🏡🏢🏣🏤🏥🏦🏨🏩🏪🏫🏬🏭🏯🏰💒🗼🗽⛪🕌🕍⛩️⛩🕋⛲⛺🌁🌃🏙️🏙🌄🌅🌆🌇🌉♨️♨🌌🎠🎡🎢💈🎪🚂🚃🚄🚅🚆🚇🚈🚉🚊🚝🚞🚋🚌🚍🚎🚐🚑🚒🚓🚔🚕🚖🚗🚘🚙🚚🚛🚜🚲🛴🛹🛵🚏🛣️🛣🛤️🛤🛢️🛢⛽🚨🚥🚦🛑🚧⚓⛵🛶🚤🛳️🛳⛴️⛴🛥️🛥🚢✈️✈🛩️🛩🛫🛬💺🚁🚟🚠🚡🛰️🛰🚀🛸🛎️🛎🧳⌛⏳⌚⏰⏱️⏱⏲️⏲🕰️🕰🕛🕧🕐🕜🕑🕝🕒🕞🕓🕟🕔🕠🕕🕡🕖🕢🕗🕣🕘🕤🕙🕥🕚🕦🌑🌒🌓🌔🌕🌖🌗🌘🌙🌚🌛🌜🌡️🌡☀️☀🌝🌞⭐🌟🌠☁️☁⛅⛈️⛈🌤️🌤🌥️🌥🌦️🌦🌧️🌧🌨️🌨🌩️🌩🌪️🌪🌫️🌫🌬️🌬🌀🌈🌂☂️☂☔⛱️⛱⚡❄️❄☃️☃⛄☄️☄🔥💧🌊🎃🎄🎆🎇🧨✨🎈🎉🎊🎋🎍🎎🎏🎐🎑🧧🎀🎁🎗️🎗🎟️🎟🎫🎖️🎖🏆🏅🥇🥈🥉⚽⚾🥎🏀🏐🏈🏉🎾🥏🎳🏏🏑🏒🥍🏓🏸🥊🥋🥅⛳⛸️⛸🎣🎽🎿🛷🥌🎯🎱🔮🧿🎮🕹️🕹🎰🎲🧩🧸♠️♠♥️♥♦️♦♣️♣♟️♟🃏🀄🎴🎭🖼️🖼🎨🧵🧶🔇🔈🔉🔊📢📣📯🔔🔕🎼🎵🎶🎙️🎙🎚️🎚🎛️🎛🎤🎧📻🎷🎸🎹🎺🎻🥁📱📲☎️☎📞📟📠🔋🔌💻🖥️🖥🖨️🖨⌨️⌨🖱️🖱🖲️🖲💽💾💿📀🧮🎥🎞️🎞📽️📽🎬📺📷📸📹📼🔍🔎🕯️🕯💡🔦🏮📔📕📖📗📘📙📚📓📒📃📜📄📰🗞️🗞📑🔖🏷️🏷💰💴💵💶💷💸💳🧾💹💱💲✉️✉📧📨📩📤📥📦📫📪📬📭📮🗳️🗳✏️✏✒️✒🖋️🖋🖊️🖊🖌️🖌🖍️🖍📝💼📁📂🗂️🗂📅📆🗒️🗒🗓️🗓📇📈📉📊📋📌📍📎🖇️🖇📏📐✂️✂🗃️🗃🗄️🗄🗑️🗑🔒🔓🔏🔐🔑🗝️🗝🔨⛏️⛏⚒️⚒🛠️🛠🗡️🗡⚔️⚔🔫🏹🛡️🛡🔧🔩⚙️⚙🗜️🗜⚖️⚖🔗⛓️⛓🧰🧲⚗️⚗🧪🧫🧬🔬🔭📡💉💊🚪🛏️🛏🛋️🛋🚽🚿🛁🧴🧷🧹🧺🧻🧼🧽🧯🛒🚬⚰️⚰⚱️⚱🗿🏧🚮🚰♿🚹🚺🚻🚼🚾🛂🛃🛄🛅⚠️⚠🚸⛔🚫🚳🚭🚯🚱🚷📵🔞☢️☢☣️☣⬆️⬆↗️↗➡️➡↘️↘⬇️⬇↙️↙⬅️⬅↖️↖↕️↕↔️↔↩️↩↪️↪⤴️⤴⤵️⤵🔃🔄🔙🔚🔛🔜🔝🛐⚛️⚛🕉️🕉✡️✡☸️☸☯️☯✝️✝☦️☦☪️☪☮️☮🕎🔯♈♉♊♋♌♍♎♏♐♑♒♓⛎🔀🔁🔂▶️▶⏩⏭️⏭⏯️⏯◀️◀⏪⏮️⏮🔼⏫🔽⏬⏸️⏸⏹️⏹⏺️⏺⏏️⏏🎦🔅🔆📶📳📴♀️♀♂️♂⚕️⚕♾️♾♻️♻⚜️⚜🔱📛🔰⭕✅☑️☑✔️✔✖️✖❌❎➕➖➗➰➿〽️〽✳️✳✴️✴❇️❇‼️‼⁉️⁉❓❔❕❗〰️〰©️©®️®™️™#️⃣#⃣*️⃣*⃣0️⃣0⃣1️⃣1⃣2️⃣2⃣3️⃣3⃣4️⃣4⃣5️⃣5⃣6️⃣6⃣7️⃣7⃣8️⃣8⃣9️⃣9⃣🔟💯🔠🔡🔢🔣🔤🅰️🅰🆎🅱️🅱🆑🆒🆓ℹ️ℹ🆔Ⓜ️Ⓜ🆕🆖🅾️🅾🆗🅿️🅿🆘🆙🆚🈁🈂️🈂🈷️🈷🈶🈯🉐🈹🈚🈲🉑🈸🈴🈳㊗️㊗㊙️㊙🈺🈵▪️▪▫️▫◻️◻◼️◼◽◾⬛⬜🔶🔷🔸🔹🔺🔻💠🔘🔲🔳⚪⚫🔴🔵🏁🚩🎌🏴🏳️🏳🏳️‍🌈🏳‍🌈🏴‍☠️🏴‍☠🇦🇨🇦🇩🇦🇪🇦🇫🇦🇬🇦🇮🇦🇱🇦🇲🇦🇴🇦🇶🇦🇷🇦🇸🇦🇹🇦🇺🇦🇼🇦🇽🇦🇿🇧🇦🇧🇧🇧🇩🇧🇪🇧🇫🇧🇬🇧🇭🇧🇮🇧🇯🇧🇱🇧🇲🇧🇳🇧🇴🇧🇶🇧🇷🇧🇸🇧🇹🇧🇻🇧🇼🇧🇾🇧🇿🇨🇦🇨🇨🇨🇩🇨🇫🇨🇬🇨🇭🇨🇮🇨🇰🇨🇱🇨🇲🇨🇳🇨🇴🇨🇵🇨🇷🇨🇺🇨🇻🇨🇼🇨🇽🇨🇾🇨🇿🇩🇪🇩🇬🇩🇯🇩🇰🇩🇲🇩🇴🇩🇿🇪🇦🇪🇨🇪🇪🇪🇬🇪🇭🇪🇷🇪🇸🇪🇹🇪🇺🇫🇮🇫🇯🇫🇰🇫🇲🇫🇴🇫🇷🇬🇦🇬🇧🇬🇩🇬🇪🇬🇫🇬🇬🇬🇭🇬🇮🇬🇱🇬🇲🇬🇳🇬🇵🇬🇶🇬🇷🇬🇸🇬🇹🇬🇺🇬🇼🇬🇾🇭🇰🇭🇲🇭🇳🇭🇷🇭🇹🇭🇺🇮🇨🇮🇩🇮🇪🇮🇱🇮🇲🇮🇳🇮🇴🇮🇶🇮🇷🇮🇸🇮🇹🇯🇪🇯🇲🇯🇴🇯🇵🇰🇪🇰🇬🇰🇭🇰🇮🇰🇲🇰🇳🇰🇵🇰🇷🇰🇼🇰🇾🇰🇿🇱🇦🇱🇧🇱🇨🇱🇮🇱🇰🇱🇷🇱🇸🇱🇹🇱🇺🇱🇻🇱🇾🇲🇦🇲🇨🇲🇩🇲🇪🇲🇫🇲🇬🇲🇭🇲🇰🇲🇱🇲🇲🇲🇳🇲🇴🇲🇵🇲🇶🇲🇷🇲🇸🇲🇹🇲🇺🇲🇻🇲🇼🇲🇽🇲🇾🇲🇿🇳🇦🇳🇨🇳🇪🇳🇫🇳🇬🇳🇮🇳🇱🇳🇴🇳🇵🇳🇷🇳🇺🇳🇿🇴🇲🇵🇦🇵🇪🇵🇫🇵🇬🇵🇭🇵🇰🇵🇱🇵🇲🇵🇳🇵🇷🇵🇸🇵🇹🇵🇼🇵🇾🇶🇦🇷🇪🇷🇴🇷🇸🇷🇺🇷🇼🇸🇦🇸🇧🇸🇨🇸🇩🇸🇪🇸🇬🇸🇭🇸🇮🇸🇯🇸🇰🇸🇱🇸🇲🇸🇳🇸🇴🇸🇷🇸🇸🇸🇹🇸🇻🇸🇽🇸🇾🇸🇿🇹🇦🇹🇨🇹🇩🇹🇫🇹🇬🇹🇭🇹🇯🇹🇰🇹🇱🇹🇲🇹🇳🇹🇴🇹🇷🇹🇹🇹🇻🇹🇼🇹🇿🇺🇦🇺🇬🇺🇲🇺🇳🇺🇸🇺🇾🇺🇿🇻🇦🇻🇨🇻🇪🇻🇬🇻🇮🇻🇳🇻🇺🇼🇫🇼🇸🇽🇰🇾🇪🇾🇹🇿🇦🇿🇲🇿🇼🏴󠁧󠁢󠁥󠁮󠁧󠁿🏴󠁧󠁢󠁳󠁣󠁴󠁿🏴󠁧󠁢󠁷󠁬󠁳󠁿" + ); + expect(() => emoji.parse(":-)")).toThrow(); + expect(() => emoji.parse("😀 is an emoji")).toThrow(); + expect(() => emoji.parse("😀stuff")).toThrow(); + expect(() => emoji.parse("stuff😀")).toThrow(); +}); + +test("uuid", () => { + const uuid = z.string().uuid("custom error"); + uuid.parse("9491d710-3185-4e06-bea0-6a2f275345e0"); + uuid.parse("d89e7b01-7598-ed11-9d7a-0022489382fd"); // new sequential id + uuid.parse("00000000-0000-0000-0000-000000000000"); + uuid.parse("b3ce60f8-e8b9-40f5-1150-172ede56ff74"); // Variant 0 - RFC 4122: Reserved, NCS backward compatibility + uuid.parse("92e76bf9-28b3-4730-cd7f-cb6bc51f8c09"); // Variant 2 - RFC 4122: Reserved, Microsoft Corporation backward compatibility + const result = uuid.safeParse("9491d710-3185-4e06-bea0-6a2f275345e0X"); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues[0].message).toEqual("custom error"); + } +}); + +test("bad uuid", () => { + const uuid = z.string().uuid("custom error"); + uuid.parse("9491d710-3185-4e06-bea0-6a2f275345e0"); + const result = uuid.safeParse("invalid uuid"); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues[0].message).toEqual("custom error"); + } +}); + +test("nanoid", () => { + const nanoid = z.string().nanoid("custom error"); + nanoid.parse("lfNZluvAxMkf7Q8C5H-QS"); + nanoid.parse("mIU_4PJWikaU8fMbmkouz"); + nanoid.parse("Hb9ZUtUa2JDm_dD-47EGv"); + nanoid.parse("5Noocgv_8vQ9oPijj4ioQ"); + const result = nanoid.safeParse("Xq90uDyhddC53KsoASYJGX"); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues[0].message).toEqual("custom error"); + } +}); + +test("bad nanoid", () => { + const nanoid = z.string().nanoid("custom error"); + nanoid.parse("ySh_984wpDUu7IQRrLXAp"); + const result = nanoid.safeParse("invalid nanoid"); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues[0].message).toEqual("custom error"); + } +}); + +test("cuid", () => { + const cuid = z.string().cuid(); + cuid.parse("ckopqwooh000001la8mbi2im9"); + const result = cuid.safeParse("cifjhdsfhsd-invalid-cuid"); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues[0].message).toEqual("Invalid cuid"); + } +}); + +test("cuid2", () => { + const cuid2 = z.string().cuid2(); + const validStrings = [ + "a", // short string + "tz4a98xxat96iws9zmbrgj3a", // normal string + "kf5vz6ssxe4zjcb409rjgo747tc5qjazgptvotk6", // longer than require("@paralleldrive/cuid2").bigLength + ]; + for (const s of validStrings) { + cuid2.parse(s); + } + + const invalidStrings = [ + "", // empty string + "tz4a98xxat96iws9zMbrgj3a", // include uppercase + "tz4a98xxat96iws-zmbrgj3a", // involve symbols + ]; + const results = invalidStrings.map((s) => cuid2.safeParse(s)); + expect(results.every((r) => !r.success)).toEqual(true); + if (!results[0].success) { + expect(results[0].error.issues[0].message).toEqual("Invalid cuid2"); + } +}); + +test("ulid", () => { + const ulid = z.string().ulid(); + ulid.parse("01ARZ3NDEKTSV4RRFFQ69G5FAV"); + const result = ulid.safeParse("invalidulid"); + expect(result.success).toEqual(false); + const tooLong = "01ARZ3NDEKTSV4RRFFQ69G5FAVA"; + expect(ulid.safeParse(tooLong).success).toEqual(false); + if (!result.success) { + expect(result.error.issues[0].message).toEqual("Invalid ulid"); + } + const caseInsensitive = ulid.safeParse("01arZ3nDeKTsV4RRffQ69G5FAV"); + expect(caseInsensitive.success).toEqual(true); +}); + +test("regex", () => { + z.string() + .regex(/^moo+$/) + .parse("mooooo"); + expect(() => z.string().uuid().parse("purr")).toThrow(); +}); + +test("regexp error message", () => { + const result = z + .string() + .regex(/^moo+$/) + .safeParse("boooo"); + if (!result.success) { + expect(result.error.issues[0].message).toEqual("Invalid"); + } else { + throw new Error("validation should have failed"); + } + + expect(() => z.string().uuid().parse("purr")).toThrow(); +}); + +test("regex lastIndex reset", () => { + const schema = z.string().regex(/^\d+$/g); + expect(schema.safeParse("123").success).toEqual(true); + expect(schema.safeParse("123").success).toEqual(true); + expect(schema.safeParse("123").success).toEqual(true); + expect(schema.safeParse("123").success).toEqual(true); + expect(schema.safeParse("123").success).toEqual(true); +}); + +test("checks getters", () => { + expect(z.string().email().isEmail).toEqual(true); + expect(z.string().email().isURL).toEqual(false); + expect(z.string().email().isCUID).toEqual(false); + expect(z.string().email().isCUID2).toEqual(false); + expect(z.string().email().isUUID).toEqual(false); + expect(z.string().email().isNANOID).toEqual(false); + expect(z.string().email().isIP).toEqual(false); + expect(z.string().email().isCIDR).toEqual(false); + expect(z.string().email().isULID).toEqual(false); + + expect(z.string().url().isEmail).toEqual(false); + expect(z.string().url().isURL).toEqual(true); + expect(z.string().url().isCUID).toEqual(false); + expect(z.string().url().isCUID2).toEqual(false); + expect(z.string().url().isUUID).toEqual(false); + expect(z.string().url().isNANOID).toEqual(false); + expect(z.string().url().isIP).toEqual(false); + expect(z.string().url().isCIDR).toEqual(false); + expect(z.string().url().isULID).toEqual(false); + + expect(z.string().cuid().isEmail).toEqual(false); + expect(z.string().cuid().isURL).toEqual(false); + expect(z.string().cuid().isCUID).toEqual(true); + expect(z.string().cuid().isCUID2).toEqual(false); + expect(z.string().cuid().isUUID).toEqual(false); + expect(z.string().cuid().isNANOID).toEqual(false); + expect(z.string().cuid().isIP).toEqual(false); + expect(z.string().cuid().isCIDR).toEqual(false); + expect(z.string().cuid().isULID).toEqual(false); + + expect(z.string().cuid2().isEmail).toEqual(false); + expect(z.string().cuid2().isURL).toEqual(false); + expect(z.string().cuid2().isCUID).toEqual(false); + expect(z.string().cuid2().isCUID2).toEqual(true); + expect(z.string().cuid2().isUUID).toEqual(false); + expect(z.string().cuid2().isNANOID).toEqual(false); + expect(z.string().cuid2().isIP).toEqual(false); + expect(z.string().cuid2().isCIDR).toEqual(false); + expect(z.string().cuid2().isULID).toEqual(false); + + expect(z.string().uuid().isEmail).toEqual(false); + expect(z.string().uuid().isURL).toEqual(false); + expect(z.string().uuid().isCUID).toEqual(false); + expect(z.string().uuid().isCUID2).toEqual(false); + expect(z.string().uuid().isUUID).toEqual(true); + expect(z.string().uuid().isNANOID).toEqual(false); + expect(z.string().uuid().isIP).toEqual(false); + expect(z.string().uuid().isCIDR).toEqual(false); + expect(z.string().uuid().isULID).toEqual(false); + + expect(z.string().nanoid().isEmail).toEqual(false); + expect(z.string().nanoid().isURL).toEqual(false); + expect(z.string().nanoid().isCUID).toEqual(false); + expect(z.string().nanoid().isCUID2).toEqual(false); + expect(z.string().nanoid().isUUID).toEqual(false); + expect(z.string().nanoid().isNANOID).toEqual(true); + expect(z.string().nanoid().isIP).toEqual(false); + expect(z.string().nanoid().isCIDR).toEqual(false); + expect(z.string().nanoid().isULID).toEqual(false); + + expect(z.string().ip().isEmail).toEqual(false); + expect(z.string().ip().isURL).toEqual(false); + expect(z.string().ip().isCUID).toEqual(false); + expect(z.string().ip().isCUID2).toEqual(false); + expect(z.string().ip().isUUID).toEqual(false); + expect(z.string().ip().isNANOID).toEqual(false); + expect(z.string().ip().isIP).toEqual(true); + expect(z.string().ip().isCIDR).toEqual(false); + expect(z.string().ip().isULID).toEqual(false); + + expect(z.string().cidr().isEmail).toEqual(false); + expect(z.string().cidr().isURL).toEqual(false); + expect(z.string().cidr().isCUID).toEqual(false); + expect(z.string().cidr().isCUID2).toEqual(false); + expect(z.string().cidr().isUUID).toEqual(false); + expect(z.string().cidr().isNANOID).toEqual(false); + expect(z.string().cidr().isIP).toEqual(false); + expect(z.string().cidr().isCIDR).toEqual(true); + expect(z.string().cidr().isULID).toEqual(false); + + expect(z.string().ulid().isEmail).toEqual(false); + expect(z.string().ulid().isURL).toEqual(false); + expect(z.string().ulid().isCUID).toEqual(false); + expect(z.string().ulid().isCUID2).toEqual(false); + expect(z.string().ulid().isUUID).toEqual(false); + expect(z.string().ulid().isNANOID).toEqual(false); + expect(z.string().ulid().isIP).toEqual(false); + expect(z.string().ulid().isCIDR).toEqual(false); + expect(z.string().ulid().isULID).toEqual(true); +}); + +test("min max getters", () => { + expect(z.string().min(5).minLength).toEqual(5); + expect(z.string().min(5).min(10).minLength).toEqual(10); + expect(z.string().minLength).toEqual(null); + + expect(z.string().max(5).maxLength).toEqual(5); + expect(z.string().max(5).max(1).maxLength).toEqual(1); + expect(z.string().maxLength).toEqual(null); +}); + +test("trim", () => { + expect(z.string().trim().min(2).parse(" 12 ")).toEqual("12"); + + // ordering of methods is respected + expect(z.string().min(2).trim().parse(" 1 ")).toEqual("1"); + expect(() => z.string().trim().min(2).parse(" 1 ")).toThrow(); +}); + +test("lowerCase", () => { + expect(z.string().toLowerCase().parse("ASDF")).toEqual("asdf"); + expect(z.string().toUpperCase().parse("asdf")).toEqual("ASDF"); +}); + +test("datetime", () => { + const a = z.string().datetime({}); + expect(a.isDatetime).toEqual(true); + + const b = z.string().datetime({ offset: true }); + expect(b.isDatetime).toEqual(true); + + const c = z.string().datetime({ precision: 3 }); + expect(c.isDatetime).toEqual(true); + + const d = z.string().datetime({ offset: true, precision: 0 }); + expect(d.isDatetime).toEqual(true); + + const { isDatetime } = z.string().datetime(); + expect(isDatetime).toEqual(true); +}); + +test("datetime parsing", () => { + const datetime = z.string().datetime(); + datetime.parse("1970-01-01T00:00:00.000Z"); + datetime.parse("2022-10-13T09:52:31.816Z"); + datetime.parse("2022-10-13T09:52:31.8162314Z"); + datetime.parse("1970-01-01T00:00:00Z"); + datetime.parse("2022-10-13T09:52:31Z"); + datetime.parse("2022-10-13T09:52Z"); + expect(() => datetime.parse("")).toThrow(); + expect(() => datetime.parse("foo")).toThrow(); + expect(() => datetime.parse("2020-10-14")).toThrow(); + expect(() => datetime.parse("T18:45:12.123")).toThrow(); + expect(() => datetime.parse("2020-10-14T17:42:29+00:00")).toThrow(); + expect(() => datetime.parse("2020-10-14T17:42.123+00:00")).toThrow(); + + const datetimeNoMs = z.string().datetime({ precision: 0 }); + datetimeNoMs.parse("1970-01-01T00:00:00Z"); + datetimeNoMs.parse("2022-10-13T09:52:31Z"); + datetimeNoMs.parse("2022-10-13T09:52Z"); + expect(() => datetimeNoMs.parse("tuna")).toThrow(); + expect(() => datetimeNoMs.parse("1970-01-01T00:00:00.000Z")).toThrow(); + expect(() => datetimeNoMs.parse("1970-01-01T00:00:00.Z")).toThrow(); + expect(() => datetimeNoMs.parse("2022-10-13T09:52:31.816Z")).toThrow(); + + const datetime3Ms = z.string().datetime({ precision: 3 }); + datetime3Ms.parse("1970-01-01T00:00:00.000Z"); + datetime3Ms.parse("2022-10-13T09:52:31.123Z"); + expect(() => datetime3Ms.parse("tuna")).toThrow(); + expect(() => datetime3Ms.parse("1970-01-01T00:00:00.1Z")).toThrow(); + expect(() => datetime3Ms.parse("1970-01-01T00:00:00.12Z")).toThrow(); + expect(() => datetime3Ms.parse("2022-10-13T09:52:31Z")).toThrow(); + expect(() => datetime3Ms.parse("2022-10-13T09:52Z")).toThrow(); + + const datetimeOffset = z.string().datetime({ offset: true }); + datetimeOffset.parse("1970-01-01T00:00:00.000Z"); + datetimeOffset.parse("2022-10-13T09:52:31.816234134Z"); + datetimeOffset.parse("1970-01-01T00:00:00Z"); + datetimeOffset.parse("2022-10-13T09:52:31.4Z"); + datetimeOffset.parse("2020-10-14T17:42:29+00:00"); + datetimeOffset.parse("2020-10-14T17:42:29+03:15"); + datetimeOffset.parse("2020-10-14T17:42:29+0315"); + datetimeOffset.parse("2020-10-14T17:42+0315"); + expect(() => datetimeOffset.parse("2020-10-14T17:42:29+03")); + expect(() => datetimeOffset.parse("tuna")).toThrow(); + expect(() => datetimeOffset.parse("2022-10-13T09:52:31.Z")).toThrow(); + + const datetimeOffsetNoMs = z.string().datetime({ offset: true, precision: 0 }); + datetimeOffsetNoMs.parse("1970-01-01T00:00:00Z"); + datetimeOffsetNoMs.parse("2022-10-13T09:52:31Z"); + datetimeOffsetNoMs.parse("2020-10-14T17:42:29+00:00"); + datetimeOffsetNoMs.parse("2020-10-14T17:42:29+0000"); + datetimeOffsetNoMs.parse("2020-10-14T17:42+0000"); + expect(() => datetimeOffsetNoMs.parse("2020-10-14T17:42:29+00")).toThrow(); + expect(() => datetimeOffsetNoMs.parse("tuna")).toThrow(); + expect(() => datetimeOffsetNoMs.parse("1970-01-01T00:00:00.000Z")).toThrow(); + expect(() => datetimeOffsetNoMs.parse("1970-01-01T00:00:00.Z")).toThrow(); + expect(() => datetimeOffsetNoMs.parse("2022-10-13T09:52:31.816Z")).toThrow(); + expect(() => datetimeOffsetNoMs.parse("2020-10-14T17:42:29.124+00:00")).toThrow(); + + const datetimeOffset4Ms = z.string().datetime({ offset: true, precision: 4 }); + datetimeOffset4Ms.parse("1970-01-01T00:00:00.1234Z"); + datetimeOffset4Ms.parse("2020-10-14T17:42:29.1234+00:00"); + datetimeOffset4Ms.parse("2020-10-14T17:42:29.1234+0000"); + expect(() => datetimeOffset4Ms.parse("2020-10-14T17:42:29.1234+00")).toThrow(); + expect(() => datetimeOffset4Ms.parse("tuna")).toThrow(); + expect(() => datetimeOffset4Ms.parse("1970-01-01T00:00:00.123Z")).toThrow(); + expect(() => datetimeOffset4Ms.parse("2020-10-14T17:42:29.124+00:00")).toThrow(); + expect(() => datetimeOffset4Ms.parse("2020-10-14T17:42+00:00")).toThrow(); +}); + +test("date", () => { + const a = z.string().date(); + expect(a.isDate).toEqual(true); +}); + +test("date parsing", () => { + const date = z.string().date(); + date.parse("1970-01-01"); + date.parse("2022-01-31"); + date.parse("2022-03-31"); + date.parse("2022-04-30"); + date.parse("2022-05-31"); + date.parse("2022-06-30"); + date.parse("2022-07-31"); + date.parse("2022-08-31"); + date.parse("2022-09-30"); + date.parse("2022-10-31"); + date.parse("2022-11-30"); + date.parse("2022-12-31"); + + date.parse("2000-02-29"); + date.parse("2400-02-29"); + expect(() => date.parse("2022-02-29")).toThrow(); + expect(() => date.parse("2100-02-29")).toThrow(); + expect(() => date.parse("2200-02-29")).toThrow(); + expect(() => date.parse("2300-02-29")).toThrow(); + expect(() => date.parse("2500-02-29")).toThrow(); + + expect(() => date.parse("")).toThrow(); + expect(() => date.parse("foo")).toThrow(); + expect(() => date.parse("200-01-01")).toThrow(); + expect(() => date.parse("20000-01-01")).toThrow(); + expect(() => date.parse("2000-0-01")).toThrow(); + expect(() => date.parse("2000-011-01")).toThrow(); + expect(() => date.parse("2000-01-0")).toThrow(); + expect(() => date.parse("2000-01-011")).toThrow(); + expect(() => date.parse("2000/01/01")).toThrow(); + expect(() => date.parse("01-01-2022")).toThrow(); + expect(() => date.parse("01/01/2022")).toThrow(); + expect(() => date.parse("2000-01-01 00:00:00Z")).toThrow(); + expect(() => date.parse("2020-10-14T17:42:29+00:00")).toThrow(); + expect(() => date.parse("2020-10-14T17:42:29Z")).toThrow(); + expect(() => date.parse("2020-10-14T17:42:29")).toThrow(); + expect(() => date.parse("2020-10-14T17:42:29.123Z")).toThrow(); + + expect(() => date.parse("2000-00-12")).toThrow(); + expect(() => date.parse("2000-12-00")).toThrow(); + expect(() => date.parse("2000-01-32")).toThrow(); + expect(() => date.parse("2000-13-01")).toThrow(); + expect(() => date.parse("2000-21-01")).toThrow(); + + expect(() => date.parse("2000-02-30")).toThrow(); + expect(() => date.parse("2000-02-31")).toThrow(); + expect(() => date.parse("2000-04-31")).toThrow(); + expect(() => date.parse("2000-06-31")).toThrow(); + expect(() => date.parse("2000-09-31")).toThrow(); + expect(() => date.parse("2000-11-31")).toThrow(); +}); + +test("time", () => { + const a = z.string().time(); + expect(a.isTime).toEqual(true); +}); + +test("time parsing", () => { + const time = z.string().time(); + time.parse("00:00:00"); + time.parse("23:00:00"); + time.parse("00:59:00"); + time.parse("00:00:59"); + time.parse("23:59:59"); + time.parse("09:52:31"); + time.parse("23:59:59.9999999"); + time.parse("23:59"); + expect(() => time.parse("")).toThrow(); + expect(() => time.parse("foo")).toThrow(); + expect(() => time.parse("00:00:00Z")).toThrow(); + expect(() => time.parse("0:00:00")).toThrow(); + expect(() => time.parse("00:0:00")).toThrow(); + expect(() => time.parse("00:00:0")).toThrow(); + expect(() => time.parse("00:00:00.000+00:00")).toThrow(); + + expect(() => time.parse("24:00:00")).toThrow(); + expect(() => time.parse("00:60:00")).toThrow(); + expect(() => time.parse("00:00:60")).toThrow(); + expect(() => time.parse("24:60:60")).toThrow(); + expect(() => time.parse("24:60")).toThrow(); + + const time2 = z.string().time({ precision: 2 }); + time2.parse("00:00:00.00"); + time2.parse("09:52:31.12"); + time2.parse("23:59:59.99"); + expect(() => time2.parse("")).toThrow(); + expect(() => time2.parse("foo")).toThrow(); + expect(() => time2.parse("00:00:00")).toThrow(); + expect(() => time2.parse("00:00:00.00Z")).toThrow(); + expect(() => time2.parse("00:00:00.0")).toThrow(); + expect(() => time2.parse("00:00:00.000")).toThrow(); + expect(() => time2.parse("00:00:00.00+00:00")).toThrow(); + expect(() => time2.parse("23:59")).toThrow(); + + // const time3 = z.string().time({ offset: true }); + // time3.parse("00:00:00Z"); + // time3.parse("09:52:31Z"); + // time3.parse("00:00:00+00:00"); + // time3.parse("00:00:00+0000"); + // time3.parse("00:00:00.000Z"); + // time3.parse("00:00:00.000+00:00"); + // time3.parse("00:00:00.000+0000"); + // expect(() => time3.parse("")).toThrow(); + // expect(() => time3.parse("foo")).toThrow(); + // expect(() => time3.parse("00:00:00")).toThrow(); + // expect(() => time3.parse("00:00:00.000")).toThrow(); + + // const time4 = z.string().time({ offset: true, precision: 0 }); + // time4.parse("00:00:00Z"); + // time4.parse("09:52:31Z"); + // time4.parse("00:00:00+00:00"); + // time4.parse("00:00:00+0000"); + // expect(() => time4.parse("")).toThrow(); + // expect(() => time4.parse("foo")).toThrow(); + // expect(() => time4.parse("00:00:00.0")).toThrow(); + // expect(() => time4.parse("00:00:00.000")).toThrow(); + // expect(() => time4.parse("00:00:00.000+00:00")).toThrow(); +}); + +test("duration", () => { + const duration = z.string().duration(); + expect(duration.isDuration).toEqual(true); + + const validDurations = [ + "P3Y6M4DT12H30M5S", + "P2Y9M3DT12H31M8.001S", + "+P3Y6M4DT12H30M5S", + "-PT0.001S", + "+PT0.001S", + "PT0,001S", + "PT12H30M5S", + "-P2M1D", + "P-2M-1D", + "-P5DT10H", + "P-5DT-10H", + "P1Y", + "P2MT30M", + "PT6H", + "P5W", + "P0.5Y", + "P0,5Y", + "P42YT7.004M", + ]; + + const invalidDurations = ["foo bar", "", " ", "P", "T1H", "P0.5Y1D", "P0,5Y6M", "P1YT"]; + + for (const val of validDurations) { + const result = duration.safeParse(val); + if (!result.success) { + throw Error(`Valid duration could not be parsed: ${val}`); + } + } + + for (const val of invalidDurations) { + const result = duration.safeParse(val); + + if (result.success) { + throw Error(`Invalid duration was successful parsed: ${val}`); + } + + expect(result.error.issues[0].message).toEqual("Invalid duration"); + } +}); + +test("IP validation", () => { + const ip = z.string().ip(); + expect(ip.safeParse("122.122.122.122").success).toBe(true); + + const ipv4 = z.string().ip({ version: "v4" }); + expect(() => ipv4.parse("6097:adfa:6f0b:220d:db08:5021:6191:7990")).toThrow(); + + const ipv6 = z.string().ip({ version: "v6" }); + expect(() => ipv6.parse("254.164.77.1")).toThrow(); + + const validIPs = [ + "1e5e:e6c8:daac:514b:114b:e360:d8c0:682c", + "9d4:c956:420f:5788:4339:9b3b:2418:75c3", + "474f:4c83::4e40:a47:ff95:0cda", + "d329:0:25b4:db47:a9d1:0:4926:0000", + "e48:10fb:1499:3e28:e4b6:dea5:4692:912c", + "114.71.82.94", + "0.0.0.0", + "37.85.236.115", + "2001:4888:50:ff00:500:d::", + "2001:4888:50:ff00:0500:000d:000:0000", + "2001:4888:50:ff00:0500:000d:0000:0000", + ]; + + const invalidIPs = [ + "d329:1be4:25b4:db47:a9d1:dc71:4926:992c:14af", + "d5e7:7214:2b78::3906:85e6:53cc:709:32ba", + "8f69::c757:395e:976e::3441", + "54cb::473f:d516:0.255.256.22", + "54cb::473f:d516:192.168.1", + "256.0.4.4", + "-1.0.555.4", + "0.0.0.0.0", + "1.1.1", + ]; + // no parameters check IPv4 or IPv6 + const ipSchema = z.string().ip(); + expect(validIPs.every((ip) => ipSchema.safeParse(ip).success)).toBe(true); + expect(invalidIPs.every((ip) => ipSchema.safeParse(ip).success === false)).toBe(true); +}); + +test("CIDR validation", () => { + const ipv4Cidr = z.string().cidr({ version: "v4" }); + expect(() => ipv4Cidr.parse("2001:0db8:85a3::8a2e:0370:7334/64")).toThrow(); + + const ipv6Cidr = z.string().cidr({ version: "v6" }); + expect(() => ipv6Cidr.parse("192.168.0.1/24")).toThrow(); + + const validCidrs = [ + "192.168.0.0/24", + "10.0.0.0/8", + "203.0.113.0/24", + "192.0.2.0/24", + "127.0.0.0/8", + "172.16.0.0/12", + "192.168.1.0/24", + "fc00::/7", + "fd00::/8", + "2001:db8::/32", + "2607:f0d0:1002:51::4/64", + "2001:0db8:85a3:0000:0000:8a2e:0370:7334/128", + "2001:0db8:1234:0000::/64", + ]; + + const invalidCidrs = [ + "192.168.1.1/33", + "10.0.0.1/-1", + "192.168.1.1/24/24", + "192.168.1.0/abc", + "2001:db8::1/129", + "2001:db8::1/-1", + "2001:db8::1/64/64", + "2001:db8::1/abc", + ]; + + // no parameters check IPv4 or IPv6 + const cidrSchema = z.string().cidr(); + expect(validCidrs.every((ip) => cidrSchema.safeParse(ip).success)).toBe(true); + expect(invalidCidrs.every((ip) => cidrSchema.safeParse(ip).success === false)).toBe(true); +}); diff --git a/node_modules/zod/src/v3/tests/transformer.test.ts b/node_modules/zod/src/v3/tests/transformer.test.ts new file mode 100644 index 0000000..ddd9e9a --- /dev/null +++ b/node_modules/zod/src/v3/tests/transformer.test.ts @@ -0,0 +1,233 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; + +const stringToNumber = z.string().transform((arg) => Number.parseFloat(arg)); +// const numberToString = z +// .transformer(z.number()) +// .transform((n) => String(n)); +const asyncNumberToString = z.number().transform(async (n) => String(n)); + +test("transform ctx.addIssue with parse", () => { + const strs = ["foo", "bar"]; + + expect(() => { + z.string() + .transform((data, ctx) => { + const i = strs.indexOf(data); + if (i === -1) { + ctx.addIssue({ + code: "custom", + message: `${data} is not one of our allowed strings`, + }); + } + return data.length; + }) + .parse("asdf"); + }).toThrow( + JSON.stringify( + [ + { + code: "custom", + message: "asdf is not one of our allowed strings", + path: [], + }, + ], + null, + 2 + ) + ); +}); + +test("transform ctx.addIssue with parseAsync", async () => { + const strs = ["foo", "bar"]; + + const result = await z + .string() + .transform(async (data, ctx) => { + const i = strs.indexOf(data); + if (i === -1) { + ctx.addIssue({ + code: "custom", + message: `${data} is not one of our allowed strings`, + }); + } + return data.length; + }) + .safeParseAsync("asdf"); + + expect(JSON.parse(JSON.stringify(result))).toEqual({ + success: false, + error: { + issues: [ + { + code: "custom", + message: "asdf is not one of our allowed strings", + path: [], + }, + ], + name: "ZodError", + }, + }); +}); + +test("z.NEVER in transform", () => { + const foo = z + .number() + .optional() + .transform((val, ctx) => { + if (!val) { + ctx.addIssue({ code: z.ZodIssueCode.custom, message: "bad" }); + return z.NEVER; + } + return val; + }); + type foo = z.infer; + util.assertEqual(true); + const arg = foo.safeParse(undefined); + if (!arg.success) { + expect(arg.error.issues[0].message).toEqual("bad"); + } +}); + +test("basic transformations", () => { + const r1 = z + .string() + .transform((data) => data.length) + .parse("asdf"); + expect(r1).toEqual(4); +}); + +test("coercion", () => { + const numToString = z.number().transform((n) => String(n)); + const data = z + .object({ + id: numToString, + }) + .parse({ id: 5 }); + + expect(data).toEqual({ id: "5" }); +}); + +test("async coercion", async () => { + const numToString = z.number().transform(async (n) => String(n)); + const data = await z + .object({ + id: numToString, + }) + .parseAsync({ id: 5 }); + + expect(data).toEqual({ id: "5" }); +}); + +test("sync coercion async error", async () => { + expect(() => + z + .object({ + id: asyncNumberToString, + }) + .parse({ id: 5 }) + ).toThrow(); + // expect(data).toEqual({ id: '5' }); +}); + +test("default", () => { + const data = z.string().default("asdf").parse(undefined); // => "asdf" + expect(data).toEqual("asdf"); +}); + +test("dynamic default", () => { + const data = z + .string() + .default(() => "string") + .parse(undefined); // => "asdf" + expect(data).toEqual("string"); +}); + +test("default when property is null or undefined", () => { + const data = z + .object({ + foo: z.boolean().nullable().default(true), + bar: z.boolean().default(true), + }) + .parse({ foo: null }); + + expect(data).toEqual({ foo: null, bar: true }); +}); + +test("default with falsy values", () => { + const schema = z.object({ + emptyStr: z.string().default("def"), + zero: z.number().default(5), + falseBoolean: z.boolean().default(true), + }); + const input = { emptyStr: "", zero: 0, falseBoolean: true }; + const output = schema.parse(input); + // defaults are not supposed to be used + expect(output).toEqual(input); +}); + +test("object typing", () => { + const t1 = z.object({ + stringToNumber, + }); + + type t1 = z.input; + type t2 = z.output; + + util.assertEqual(true); + util.assertEqual(true); +}); + +test("transform method overloads", () => { + const t1 = z.string().transform((val) => val.toUpperCase()); + expect(t1.parse("asdf")).toEqual("ASDF"); + + const t2 = z.string().transform((val) => val.length); + expect(t2.parse("asdf")).toEqual(4); +}); + +test("multiple transformers", () => { + const doubler = stringToNumber.transform((val) => { + return val * 2; + }); + expect(doubler.parse("5")).toEqual(10); +}); + +test("short circuit on dirty", () => { + const schema = z + .string() + .refine(() => false) + .transform((val) => val.toUpperCase()); + const result = schema.safeParse("asdf"); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues[0].code).toEqual(z.ZodIssueCode.custom); + } + + const result2 = schema.safeParse(1234); + expect(result2.success).toEqual(false); + if (!result2.success) { + expect(result2.error.issues[0].code).toEqual(z.ZodIssueCode.invalid_type); + } +}); + +test("async short circuit on dirty", async () => { + const schema = z + .string() + .refine(() => false) + .transform((val) => val.toUpperCase()); + const result = await schema.spa("asdf"); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues[0].code).toEqual(z.ZodIssueCode.custom); + } + + const result2 = await schema.spa(1234); + expect(result2.success).toEqual(false); + if (!result2.success) { + expect(result2.error.issues[0].code).toEqual(z.ZodIssueCode.invalid_type); + } +}); diff --git a/node_modules/zod/src/v3/tests/tuple.test.ts b/node_modules/zod/src/v3/tests/tuple.test.ts new file mode 100644 index 0000000..e525d3f --- /dev/null +++ b/node_modules/zod/src/v3/tests/tuple.test.ts @@ -0,0 +1,90 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { ZodError } from "../ZodError.js"; +import { util } from "../helpers/util.js"; + +const testTuple = z.tuple([z.string(), z.object({ name: z.literal("Rudy") }), z.array(z.literal("blue"))]); +const testData = ["asdf", { name: "Rudy" }, ["blue"]]; +const badData = [123, { name: "Rudy2" }, ["blue", "red"]]; + +test("tuple inference", () => { + const args1 = z.tuple([z.string()]); + const returns1 = z.number(); + const func1 = z.function(args1, returns1); + type func1 = z.TypeOf; + util.assertEqual number>(true); +}); + +test("successful validation", () => { + const val = testTuple.parse(testData); + expect(val).toEqual(["asdf", { name: "Rudy" }, ["blue"]]); +}); + +test("successful async validation", async () => { + const val = await testTuple.parseAsync(testData); + return expect(val).toEqual(testData); +}); + +test("failed validation", () => { + const checker = () => { + testTuple.parse([123, { name: "Rudy2" }, ["blue", "red"]] as any); + }; + try { + checker(); + } catch (err) { + if (err instanceof ZodError) { + expect(err.issues.length).toEqual(3); + } + } +}); + +test("failed async validation", async () => { + const res = await testTuple.safeParse(badData); + expect(res.success).toEqual(false); + if (!res.success) { + expect(res.error.issues.length).toEqual(3); + } + // try { + // checker(); + // } catch (err) { + // if (err instanceof ZodError) { + // expect(err.issues.length).toEqual(3); + // } + // } +}); + +test("tuple with transformers", () => { + const stringToNumber = z.string().transform((val) => val.length); + const val = z.tuple([stringToNumber]); + + type t1 = z.input; + util.assertEqual(true); + type t2 = z.output; + util.assertEqual(true); + expect(val.parse(["1234"])).toEqual([4]); +}); + +test("tuple with rest schema", () => { + const myTuple = z.tuple([z.string(), z.number()]).rest(z.boolean()); + expect(myTuple.parse(["asdf", 1234, true, false, true])).toEqual(["asdf", 1234, true, false, true]); + + expect(myTuple.parse(["asdf", 1234])).toEqual(["asdf", 1234]); + + expect(() => myTuple.parse(["asdf", 1234, "asdf"])).toThrow(); + type t1 = z.output; + + util.assertEqual(true); +}); + +test("parse should fail given sparse array as tuple", () => { + expect(() => testTuple.parse(new Array(3))).toThrow(); +}); + +// test('tuple with optional elements', () => { +// const result = z +// .tuple([z.string(), z.number().optional()]) +// .safeParse(['asdf']); +// expect(result).toEqual(['asdf']); +// }); diff --git a/node_modules/zod/src/v3/tests/unions.test.ts b/node_modules/zod/src/v3/tests/unions.test.ts new file mode 100644 index 0000000..2c3dc67 --- /dev/null +++ b/node_modules/zod/src/v3/tests/unions.test.ts @@ -0,0 +1,57 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +test("function parsing", () => { + const schema = z.union([z.string().refine(() => false), z.number().refine(() => false)]); + const result = schema.safeParse("asdf"); + expect(result.success).toEqual(false); +}); + +test("union 2", () => { + const result = z.union([z.number(), z.string().refine(() => false)]).safeParse("a"); + expect(result.success).toEqual(false); +}); + +test("return valid over invalid", () => { + const schema = z.union([ + z.object({ + email: z.string().email(), + }), + z.string(), + ]); + expect(schema.parse("asdf")).toEqual("asdf"); + expect(schema.parse({ email: "asdlkjf@lkajsdf.com" })).toEqual({ + email: "asdlkjf@lkajsdf.com", + }); +}); + +test("return dirty result over aborted", () => { + const result = z.union([z.number(), z.string().refine(() => false)]).safeParse("a"); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues).toEqual([ + { + code: "custom", + message: "Invalid input", + path: [], + }, + ]); + } +}); + +test("options getter", async () => { + const union = z.union([z.string(), z.number()]); + union.options[0].parse("asdf"); + union.options[1].parse(1234); + await union.options[0].parseAsync("asdf"); + await union.options[1].parseAsync(1234); +}); + +test("readonly union", async () => { + const options = [z.string(), z.number()] as const; + const union = z.union(options); + union.parse("asdf"); + union.parse(12); +}); diff --git a/node_modules/zod/src/v3/tests/validations.test.ts b/node_modules/zod/src/v3/tests/validations.test.ts new file mode 100644 index 0000000..66f41da --- /dev/null +++ b/node_modules/zod/src/v3/tests/validations.test.ts @@ -0,0 +1,133 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +test("array min", async () => { + try { + await z.array(z.string()).min(4).parseAsync([]); + } catch (err) { + expect((err as z.ZodError).issues[0].message).toEqual("Array must contain at least 4 element(s)"); + } +}); + +test("array max", async () => { + try { + await z.array(z.string()).max(2).parseAsync(["asdf", "asdf", "asdf"]); + } catch (err) { + expect((err as z.ZodError).issues[0].message).toEqual("Array must contain at most 2 element(s)"); + } +}); + +test("array length", async () => { + try { + await z.array(z.string()).length(2).parseAsync(["asdf", "asdf", "asdf"]); + } catch (err) { + expect((err as z.ZodError).issues[0].message).toEqual("Array must contain exactly 2 element(s)"); + } + + try { + await z.array(z.string()).length(2).parseAsync(["asdf"]); + } catch (err) { + expect((err as z.ZodError).issues[0].message).toEqual("Array must contain exactly 2 element(s)"); + } +}); + +test("string length", async () => { + try { + await z.string().length(4).parseAsync("asd"); + } catch (err) { + expect((err as z.ZodError).issues[0].message).toEqual("String must contain exactly 4 character(s)"); + } + + try { + await z.string().length(4).parseAsync("asdaa"); + } catch (err) { + expect((err as z.ZodError).issues[0].message).toEqual("String must contain exactly 4 character(s)"); + } +}); + +test("string min", async () => { + try { + await z.string().min(4).parseAsync("asd"); + } catch (err) { + expect((err as z.ZodError).issues[0].message).toEqual("String must contain at least 4 character(s)"); + } +}); + +test("string max", async () => { + try { + await z.string().max(4).parseAsync("aasdfsdfsd"); + } catch (err) { + expect((err as z.ZodError).issues[0].message).toEqual("String must contain at most 4 character(s)"); + } +}); + +test("number min", async () => { + try { + await z.number().gte(3).parseAsync(2); + } catch (err) { + expect((err as z.ZodError).issues[0].message).toEqual("Number must be greater than or equal to 3"); + } +}); + +test("number max", async () => { + try { + await z.number().lte(3).parseAsync(4); + } catch (err) { + expect((err as z.ZodError).issues[0].message).toEqual("Number must be less than or equal to 3"); + } +}); + +test("number nonnegative", async () => { + try { + await z.number().nonnegative().parseAsync(-1); + } catch (err) { + expect((err as z.ZodError).issues[0].message).toEqual("Number must be greater than or equal to 0"); + } +}); + +test("number nonpositive", async () => { + try { + await z.number().nonpositive().parseAsync(1); + } catch (err) { + expect((err as z.ZodError).issues[0].message).toEqual("Number must be less than or equal to 0"); + } +}); + +test("number negative", async () => { + try { + await z.number().negative().parseAsync(1); + } catch (err) { + expect((err as z.ZodError).issues[0].message).toEqual("Number must be less than 0"); + } +}); + +test("number positive", async () => { + try { + await z.number().positive().parseAsync(-1); + } catch (err) { + expect((err as z.ZodError).issues[0].message).toEqual("Number must be greater than 0"); + } +}); + +test("instantiation", () => { + z.string().min(5); + z.string().max(5); + z.string().length(5); + z.string().email(); + z.string().url(); + z.string().uuid(); + z.string().min(5, { message: "Must be 5 or more characters long" }); + z.string().max(5, { message: "Must be 5 or fewer characters long" }); + z.string().length(5, { message: "Must be exactly 5 characters long" }); + z.string().email({ message: "Invalid email address." }); + z.string().url({ message: "Invalid url" }); + z.string().uuid({ message: "Invalid UUID" }); +}); + +test("int", async () => { + const int = z.number().int(); + int.parse(4); + expect(() => int.parse(3.5)).toThrow(); +}); diff --git a/node_modules/zod/src/v3/tests/void.test.ts b/node_modules/zod/src/v3/tests/void.test.ts new file mode 100644 index 0000000..b128f11 --- /dev/null +++ b/node_modules/zod/src/v3/tests/void.test.ts @@ -0,0 +1,15 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; +test("void", () => { + const v = z.void(); + v.parse(undefined); + + expect(() => v.parse(null)).toThrow(); + expect(() => v.parse("")).toThrow(); + + type v = z.infer; + util.assertEqual(true); +}); diff --git a/node_modules/zod/src/v3/types.ts b/node_modules/zod/src/v3/types.ts new file mode 100644 index 0000000..b10e84f --- /dev/null +++ b/node_modules/zod/src/v3/types.ts @@ -0,0 +1,5136 @@ +import { + type IssueData, + type StringValidation, + type ZodCustomIssue, + ZodError, + type ZodErrorMap, + type ZodIssue, + ZodIssueCode, +} from "./ZodError.js"; +import { defaultErrorMap, getErrorMap } from "./errors.js"; +import type { enumUtil } from "./helpers/enumUtil.js"; +import { errorUtil } from "./helpers/errorUtil.js"; +import { + type AsyncParseReturnType, + DIRTY, + INVALID, + OK, + type ParseContext, + type ParseInput, + type ParseParams, + type ParsePath, + type ParseReturnType, + ParseStatus, + type SyncParseReturnType, + addIssueToContext, + isAborted, + isAsync, + isDirty, + isValid, + makeIssue, +} from "./helpers/parseUtil.js"; +import type { partialUtil } from "./helpers/partialUtil.js"; +import type { Primitive } from "./helpers/typeAliases.js"; +import { util, ZodParsedType, getParsedType, type objectUtil } from "./helpers/util.js"; +import type { StandardSchemaV1 } from "./standard-schema.js"; + +/////////////////////////////////////// +/////////////////////////////////////// +////////// ////////// +////////// ZodType ////////// +////////// ////////// +/////////////////////////////////////// +/////////////////////////////////////// + +export interface RefinementCtx { + addIssue: (arg: IssueData) => void; + path: (string | number)[]; +} +export type ZodRawShape = { [k: string]: ZodTypeAny }; +export type ZodTypeAny = ZodType; +export type TypeOf> = T["_output"]; +export type input> = T["_input"]; +export type output> = T["_output"]; +export type { TypeOf as infer }; + +export type CustomErrorParams = Partial>; +export interface ZodTypeDef { + errorMap?: ZodErrorMap | undefined; + description?: string | undefined; +} + +class ParseInputLazyPath implements ParseInput { + parent: ParseContext; + data: any; + _path: ParsePath; + _key: string | number | (string | number)[]; + _cachedPath: ParsePath = []; + constructor(parent: ParseContext, value: any, path: ParsePath, key: string | number | (string | number)[]) { + this.parent = parent; + this.data = value; + this._path = path; + this._key = key; + } + get path() { + if (!this._cachedPath.length) { + if (Array.isArray(this._key)) { + this._cachedPath.push(...this._path, ...this._key); + } else { + this._cachedPath.push(...this._path, this._key); + } + } + + return this._cachedPath; + } +} + +const handleResult = ( + ctx: ParseContext, + result: SyncParseReturnType +): { success: true; data: Output } | { success: false; error: ZodError } => { + if (isValid(result)) { + return { success: true, data: result.value }; + } else { + if (!ctx.common.issues.length) { + throw new Error("Validation failed but no issues detected."); + } + + return { + success: false, + get error() { + if ((this as any)._error) return (this as any)._error as Error; + const error = new ZodError(ctx.common.issues); + (this as any)._error = error; + return (this as any)._error; + }, + }; + } +}; + +export type RawCreateParams = + | { + errorMap?: ZodErrorMap | undefined; + invalid_type_error?: string | undefined; + required_error?: string | undefined; + message?: string | undefined; + description?: string | undefined; + } + | undefined; +export type ProcessedCreateParams = { + errorMap?: ZodErrorMap | undefined; + description?: string | undefined; +}; +function processCreateParams(params: RawCreateParams): ProcessedCreateParams { + if (!params) return {}; + const { errorMap, invalid_type_error, required_error, description } = params; + if (errorMap && (invalid_type_error || required_error)) { + throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); + } + if (errorMap) return { errorMap: errorMap, description }; + const customMap: ZodErrorMap = (iss, ctx) => { + const { message } = params; + + if (iss.code === "invalid_enum_value") { + return { message: message ?? ctx.defaultError }; + } + if (typeof ctx.data === "undefined") { + return { message: message ?? required_error ?? ctx.defaultError }; + } + if (iss.code !== "invalid_type") return { message: ctx.defaultError }; + return { message: message ?? invalid_type_error ?? ctx.defaultError }; + }; + return { errorMap: customMap, description }; +} + +export type SafeParseSuccess = { + success: true; + data: Output; + error?: never; +}; +export type SafeParseError = { + success: false; + error: ZodError; + data?: never; +}; + +export type SafeParseReturnType = SafeParseSuccess | SafeParseError; + +export abstract class ZodType { + readonly _type!: Output; + readonly _output!: Output; + readonly _input!: Input; + readonly _def!: Def; + + get description(): string | undefined { + return this._def.description; + } + + "~standard": StandardSchemaV1.Props; + + abstract _parse(input: ParseInput): ParseReturnType; + + _getType(input: ParseInput): string { + return getParsedType(input.data); + } + + _getOrReturnCtx(input: ParseInput, ctx?: ParseContext | undefined): ParseContext { + return ( + ctx || { + common: input.parent.common, + data: input.data, + + parsedType: getParsedType(input.data), + + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent, + } + ); + } + + _processInputParams(input: ParseInput): { + status: ParseStatus; + ctx: ParseContext; + } { + return { + status: new ParseStatus(), + ctx: { + common: input.parent.common, + data: input.data, + + parsedType: getParsedType(input.data), + + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent, + }, + }; + } + + _parseSync(input: ParseInput): SyncParseReturnType { + const result = this._parse(input); + if (isAsync(result)) { + throw new Error("Synchronous parse encountered promise."); + } + return result; + } + + _parseAsync(input: ParseInput): AsyncParseReturnType { + const result = this._parse(input); + return Promise.resolve(result); + } + + parse(data: unknown, params?: util.InexactPartial): Output { + const result = this.safeParse(data, params); + if (result.success) return result.data; + throw result.error; + } + + safeParse(data: unknown, params?: util.InexactPartial): SafeParseReturnType { + const ctx: ParseContext = { + common: { + issues: [], + async: params?.async ?? false, + contextualErrorMap: params?.errorMap, + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data), + }; + const result = this._parseSync({ data, path: ctx.path, parent: ctx }); + + return handleResult(ctx, result); + } + + "~validate"(data: unknown): StandardSchemaV1.Result | Promise> { + const ctx: ParseContext = { + common: { + issues: [], + async: !!(this["~standard"] as any).async, + }, + path: [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data), + }; + + if (!(this["~standard"] as any).async) { + try { + const result = this._parseSync({ data, path: [], parent: ctx }); + return isValid(result) + ? { + value: result.value, + } + : { + issues: ctx.common.issues, + }; + } catch (err: any) { + if ((err as Error)?.message?.toLowerCase()?.includes("encountered")) { + (this["~standard"] as any).async = true; + } + (ctx as any).common = { + issues: [], + async: true, + }; + } + } + + return this._parseAsync({ data, path: [], parent: ctx }).then((result) => + isValid(result) + ? { + value: result.value, + } + : { + issues: ctx.common.issues, + } + ); + } + + async parseAsync(data: unknown, params?: util.InexactPartial): Promise { + const result = await this.safeParseAsync(data, params); + if (result.success) return result.data; + throw result.error; + } + + async safeParseAsync( + data: unknown, + params?: util.InexactPartial + ): Promise> { + const ctx: ParseContext = { + common: { + issues: [], + contextualErrorMap: params?.errorMap, + async: true, + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data), + }; + + const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); + const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); + return handleResult(ctx, result); + } + + /** Alias of safeParseAsync */ + spa = this.safeParseAsync; + + refine( + check: (arg: Output) => arg is RefinedOutput, + message?: string | CustomErrorParams | ((arg: Output) => CustomErrorParams) + ): ZodEffects; + refine( + check: (arg: Output) => unknown | Promise, + message?: string | CustomErrorParams | ((arg: Output) => CustomErrorParams) + ): ZodEffects; + refine( + check: (arg: Output) => unknown, + message?: string | CustomErrorParams | ((arg: Output) => CustomErrorParams) + ): ZodEffects { + const getIssueProperties = (val: Output) => { + if (typeof message === "string" || typeof message === "undefined") { + return { message }; + } else if (typeof message === "function") { + return message(val); + } else { + return message; + } + }; + return this._refinement((val, ctx) => { + const result = check(val); + const setError = () => + ctx.addIssue({ + code: ZodIssueCode.custom, + ...getIssueProperties(val), + }); + if (typeof Promise !== "undefined" && result instanceof Promise) { + return result.then((data) => { + if (!data) { + setError(); + return false; + } else { + return true; + } + }); + } + if (!result) { + setError(); + return false; + } else { + return true; + } + }); + } + + refinement( + check: (arg: Output) => arg is RefinedOutput, + refinementData: IssueData | ((arg: Output, ctx: RefinementCtx) => IssueData) + ): ZodEffects; + refinement( + check: (arg: Output) => boolean, + refinementData: IssueData | ((arg: Output, ctx: RefinementCtx) => IssueData) + ): ZodEffects; + refinement( + check: (arg: Output) => unknown, + refinementData: IssueData | ((arg: Output, ctx: RefinementCtx) => IssueData) + ): ZodEffects { + return this._refinement((val, ctx) => { + if (!check(val)) { + ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); + return false; + } else { + return true; + } + }); + } + + _refinement(refinement: RefinementEffect["refinement"]): ZodEffects { + return new ZodEffects({ + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "refinement", refinement }, + }); + } + + superRefine( + refinement: (arg: Output, ctx: RefinementCtx) => arg is RefinedOutput + ): ZodEffects; + superRefine(refinement: (arg: Output, ctx: RefinementCtx) => void): ZodEffects; + superRefine(refinement: (arg: Output, ctx: RefinementCtx) => Promise): ZodEffects; + superRefine( + refinement: (arg: Output, ctx: RefinementCtx) => unknown | Promise + ): ZodEffects { + return this._refinement(refinement); + } + + constructor(def: Def) { + this._def = def; + this.parse = this.parse.bind(this); + this.safeParse = this.safeParse.bind(this); + this.parseAsync = this.parseAsync.bind(this); + this.safeParseAsync = this.safeParseAsync.bind(this); + this.spa = this.spa.bind(this); + this.refine = this.refine.bind(this); + this.refinement = this.refinement.bind(this); + this.superRefine = this.superRefine.bind(this); + this.optional = this.optional.bind(this); + this.nullable = this.nullable.bind(this); + this.nullish = this.nullish.bind(this); + this.array = this.array.bind(this); + this.promise = this.promise.bind(this); + this.or = this.or.bind(this); + this.and = this.and.bind(this); + this.transform = this.transform.bind(this); + this.brand = this.brand.bind(this); + this.default = this.default.bind(this); + this.catch = this.catch.bind(this); + this.describe = this.describe.bind(this); + this.pipe = this.pipe.bind(this); + this.readonly = this.readonly.bind(this); + this.isNullable = this.isNullable.bind(this); + this.isOptional = this.isOptional.bind(this); + this["~standard"] = { + version: 1, + vendor: "zod", + validate: (data) => this["~validate"](data), + }; + } + + optional(): ZodOptional { + return ZodOptional.create(this, this._def) as any; + } + nullable(): ZodNullable { + return ZodNullable.create(this, this._def) as any; + } + nullish(): ZodOptional> { + return this.nullable().optional(); + } + array(): ZodArray { + return ZodArray.create(this); + } + promise(): ZodPromise { + return ZodPromise.create(this, this._def); + } + + or(option: T): ZodUnion<[this, T]> { + return ZodUnion.create([this, option], this._def) as any; + } + + and(incoming: T): ZodIntersection { + return ZodIntersection.create(this, incoming, this._def); + } + + transform( + transform: (arg: Output, ctx: RefinementCtx) => NewOut | Promise + ): ZodEffects { + return new ZodEffects({ + ...processCreateParams(this._def), + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "transform", transform }, + }) as any; + } + + default(def: util.noUndefined): ZodDefault; + default(def: () => util.noUndefined): ZodDefault; + default(def: any) { + const defaultValueFunc = typeof def === "function" ? def : () => def; + + return new ZodDefault({ + ...processCreateParams(this._def), + innerType: this, + defaultValue: defaultValueFunc, + typeName: ZodFirstPartyTypeKind.ZodDefault, + }) as any; + } + + brand(brand?: B): ZodBranded; + brand(): ZodBranded { + return new ZodBranded({ + typeName: ZodFirstPartyTypeKind.ZodBranded, + type: this, + ...processCreateParams(this._def), + }); + } + + catch(def: Output): ZodCatch; + catch(def: (ctx: { error: ZodError; input: Input }) => Output): ZodCatch; + catch(def: any) { + const catchValueFunc = typeof def === "function" ? def : () => def; + + return new ZodCatch({ + ...processCreateParams(this._def), + innerType: this, + catchValue: catchValueFunc, + typeName: ZodFirstPartyTypeKind.ZodCatch, + }) as any; + } + + describe(description: string): this { + const This = (this as any).constructor; + return new This({ + ...this._def, + description, + }); + } + + pipe(target: T): ZodPipeline { + return ZodPipeline.create(this, target); + } + readonly(): ZodReadonly { + return ZodReadonly.create(this); + } + + isOptional(): boolean { + return this.safeParse(undefined).success; + } + isNullable(): boolean { + return this.safeParse(null).success; + } +} + +///////////////////////////////////////// +///////////////////////////////////////// +////////// ////////// +////////// ZodString ////////// +////////// ////////// +///////////////////////////////////////// +///////////////////////////////////////// +export type IpVersion = "v4" | "v6"; +export type ZodStringCheck = + | { kind: "min"; value: number; message?: string | undefined } + | { kind: "max"; value: number; message?: string | undefined } + | { kind: "length"; value: number; message?: string | undefined } + | { kind: "email"; message?: string | undefined } + | { kind: "url"; message?: string | undefined } + | { kind: "emoji"; message?: string | undefined } + | { kind: "uuid"; message?: string | undefined } + | { kind: "nanoid"; message?: string | undefined } + | { kind: "cuid"; message?: string | undefined } + | { kind: "includes"; value: string; position?: number | undefined; message?: string | undefined } + | { kind: "cuid2"; message?: string | undefined } + | { kind: "ulid"; message?: string | undefined } + | { kind: "startsWith"; value: string; message?: string | undefined } + | { kind: "endsWith"; value: string; message?: string | undefined } + | { kind: "regex"; regex: RegExp; message?: string | undefined } + | { kind: "trim"; message?: string | undefined } + | { kind: "toLowerCase"; message?: string | undefined } + | { kind: "toUpperCase"; message?: string | undefined } + | { kind: "jwt"; alg?: string; message?: string | undefined } + | { + kind: "datetime"; + offset: boolean; + local: boolean; + precision: number | null; + message?: string | undefined; + } + | { + kind: "date"; + // withDate: true; + message?: string | undefined; + } + | { + kind: "time"; + precision: number | null; + message?: string | undefined; + } + | { kind: "duration"; message?: string | undefined } + | { kind: "ip"; version?: IpVersion | undefined; message?: string | undefined } + | { kind: "cidr"; version?: IpVersion | undefined; message?: string | undefined } + | { kind: "base64"; message?: string | undefined } + | { kind: "base64url"; message?: string | undefined }; + +export interface ZodStringDef extends ZodTypeDef { + checks: ZodStringCheck[]; + typeName: ZodFirstPartyTypeKind.ZodString; + coerce: boolean; +} + +const cuidRegex = /^c[^\s-]{8,}$/i; +const cuid2Regex = /^[0-9a-z]+$/; +const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; +// const uuidRegex = +// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i; +const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; +const nanoidRegex = /^[a-z0-9_-]{21}$/i; +const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; +const durationRegex = + /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; + +// from https://stackoverflow.com/a/46181/1550155 +// old version: too slow, didn't support unicode +// const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i; +//old email regex +// const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i; +// eslint-disable-next-line +// const emailRegex = +// /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/; +// const emailRegex = +// /^[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])?)*$/; +// const emailRegex = +// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i; +const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; +// const emailRegex = +// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i; + +// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression +const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; +let emojiRegex: RegExp; + +// faster, simpler, safer +const ipv4Regex = + /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; +const ipv4CidrRegex = + /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; + +// const ipv6Regex = +// /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/; +const ipv6Regex = + /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; +const ipv6CidrRegex = + /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; + +// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript +const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; + +// https://base64.guru/standards/base64url +const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; + +// simple +// const dateRegexSource = `\\d{4}-\\d{2}-\\d{2}`; +// no leap year validation +// const dateRegexSource = `\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\d|2\\d))`; +// with leap year validation +const dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; +const dateRegex = new RegExp(`^${dateRegexSource}$`); + +function timeRegexSource(args: { precision?: number | null }) { + let secondsRegexSource = `[0-5]\\d`; + if (args.precision) { + secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; + } else if (args.precision == null) { + secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; + } + + const secondsQuantifier = args.precision ? "+" : "?"; // require seconds if precision is nonzero + return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; +} + +function timeRegex(args: { + offset?: boolean; + local?: boolean; + precision?: number | null; +}) { + return new RegExp(`^${timeRegexSource(args)}$`); +} + +// Adapted from https://stackoverflow.com/a/3143231 +export function datetimeRegex(args: { + precision?: number | null; + offset?: boolean; + local?: boolean; +}) { + let regex = `${dateRegexSource}T${timeRegexSource(args)}`; + + const opts: string[] = []; + opts.push(args.local ? `Z?` : `Z`); + if (args.offset) opts.push(`([+-]\\d{2}:?\\d{2})`); + regex = `${regex}(${opts.join("|")})`; + return new RegExp(`^${regex}$`); +} + +function isValidIP(ip: string, version?: IpVersion) { + if ((version === "v4" || !version) && ipv4Regex.test(ip)) { + return true; + } + if ((version === "v6" || !version) && ipv6Regex.test(ip)) { + return true; + } + + return false; +} + +function isValidJWT(jwt: string, alg?: string): boolean { + if (!jwtRegex.test(jwt)) return false; + try { + const [header] = jwt.split("."); + if (!header) return false; + // Convert base64url to base64 + const base64 = header + .replace(/-/g, "+") + .replace(/_/g, "/") + .padEnd(header.length + ((4 - (header.length % 4)) % 4), "="); + const decoded = JSON.parse(atob(base64)); + if (typeof decoded !== "object" || decoded === null) return false; + if ("typ" in decoded && decoded?.typ !== "JWT") return false; + if (!decoded.alg) return false; + if (alg && decoded.alg !== alg) return false; + return true; + } catch { + return false; + } +} + +function isValidCidr(ip: string, version?: IpVersion) { + if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) { + return true; + } + if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) { + return true; + } + + return false; +} + +export class ZodString extends ZodType { + _parse(input: ParseInput): ParseReturnType { + if (this._def.coerce) { + input.data = String(input.data); + } + const parsedType = this._getType(input); + + if (parsedType !== ZodParsedType.string) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.string, + received: ctx.parsedType, + }); + return INVALID; + } + + const status = new ParseStatus(); + let ctx: undefined | ParseContext = undefined; + + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.length < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "max") { + if (input.data.length > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "length") { + const tooBig = input.data.length > check.value; + const tooSmall = input.data.length < check.value; + if (tooBig || tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + if (tooBig) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message, + }); + } else if (tooSmall) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message, + }); + } + status.dirty(); + } + } else if (check.kind === "email") { + if (!emailRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "email", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "emoji") { + if (!emojiRegex) { + emojiRegex = new RegExp(_emojiRegex, "u"); + } + if (!emojiRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "emoji", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "uuid") { + if (!uuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "uuid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "nanoid") { + if (!nanoidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "nanoid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "cuid") { + if (!cuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "cuid2") { + if (!cuid2Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid2", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "ulid") { + if (!ulidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ulid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "url") { + try { + new URL(input.data); + } catch { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "url", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "regex") { + check.regex.lastIndex = 0; + const testResult = check.regex.test(input.data); + if (!testResult) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "regex", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "trim") { + input.data = input.data.trim(); + } else if (check.kind === "includes") { + if (!(input.data as string).includes(check.value, check.position)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { includes: check.value, position: check.position }, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "toLowerCase") { + input.data = input.data.toLowerCase(); + } else if (check.kind === "toUpperCase") { + input.data = input.data.toUpperCase(); + } else if (check.kind === "startsWith") { + if (!(input.data as string).startsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { startsWith: check.value }, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "endsWith") { + if (!(input.data as string).endsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { endsWith: check.value }, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "datetime") { + const regex = datetimeRegex(check); + + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "datetime", + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "date") { + const regex = dateRegex; + + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "date", + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "time") { + const regex = timeRegex(check); + + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "time", + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "duration") { + if (!durationRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "duration", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "ip") { + if (!isValidIP(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ip", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "jwt") { + if (!isValidJWT(input.data, check.alg)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "jwt", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "cidr") { + if (!isValidCidr(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cidr", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "base64") { + if (!base64Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "base64", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "base64url") { + if (!base64urlRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "base64url", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else { + util.assertNever(check); + } + } + + return { status: status.value, value: input.data }; + } + + protected _regex(regex: RegExp, validation: StringValidation, message?: errorUtil.ErrMessage) { + return this.refinement((data) => regex.test(data), { + validation, + code: ZodIssueCode.invalid_string, + ...errorUtil.errToObj(message), + }); + } + + _addCheck(check: ZodStringCheck) { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + + email(message?: errorUtil.ErrMessage) { + return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); + } + + url(message?: errorUtil.ErrMessage) { + return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); + } + + emoji(message?: errorUtil.ErrMessage) { + return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); + } + + uuid(message?: errorUtil.ErrMessage) { + return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); + } + nanoid(message?: errorUtil.ErrMessage) { + return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); + } + cuid(message?: errorUtil.ErrMessage) { + return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); + } + + cuid2(message?: errorUtil.ErrMessage) { + return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); + } + ulid(message?: errorUtil.ErrMessage) { + return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); + } + base64(message?: errorUtil.ErrMessage) { + return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); + } + base64url(message?: errorUtil.ErrMessage) { + // base64url encoding is a modification of base64 that can safely be used in URLs and filenames + return this._addCheck({ + kind: "base64url", + ...errorUtil.errToObj(message), + }); + } + + jwt(options?: { alg?: string; message?: string | undefined }) { + return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); + } + + ip(options?: string | { version?: IpVersion; message?: string | undefined }) { + return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); + } + + cidr(options?: string | { version?: IpVersion; message?: string | undefined }) { + return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); + } + + datetime( + options?: + | string + | { + message?: string | undefined; + precision?: number | null; + offset?: boolean; + local?: boolean; + } + ) { + if (typeof options === "string") { + return this._addCheck({ + kind: "datetime", + precision: null, + offset: false, + local: false, + message: options, + }); + } + return this._addCheck({ + kind: "datetime", + + precision: typeof options?.precision === "undefined" ? null : options?.precision, + offset: options?.offset ?? false, + local: options?.local ?? false, + ...errorUtil.errToObj(options?.message), + }); + } + + date(message?: string) { + return this._addCheck({ kind: "date", message }); + } + + time( + options?: + | string + | { + message?: string | undefined; + precision?: number | null; + } + ) { + if (typeof options === "string") { + return this._addCheck({ + kind: "time", + precision: null, + message: options, + }); + } + return this._addCheck({ + kind: "time", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + ...errorUtil.errToObj(options?.message), + }); + } + + duration(message?: errorUtil.ErrMessage) { + return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); + } + + regex(regex: RegExp, message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "regex", + regex: regex, + ...errorUtil.errToObj(message), + }); + } + + includes(value: string, options?: { message?: string; position?: number }) { + return this._addCheck({ + kind: "includes", + value: value, + position: options?.position, + ...errorUtil.errToObj(options?.message), + }); + } + + startsWith(value: string, message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "startsWith", + value: value, + ...errorUtil.errToObj(message), + }); + } + + endsWith(value: string, message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "endsWith", + value: value, + ...errorUtil.errToObj(message), + }); + } + + min(minLength: number, message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "min", + value: minLength, + ...errorUtil.errToObj(message), + }); + } + + max(maxLength: number, message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "max", + value: maxLength, + ...errorUtil.errToObj(message), + }); + } + + length(len: number, message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "length", + value: len, + ...errorUtil.errToObj(message), + }); + } + + /** + * Equivalent to `.min(1)` + */ + nonempty(message?: errorUtil.ErrMessage) { + return this.min(1, errorUtil.errToObj(message)); + } + + trim() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "trim" }], + }); + } + + toLowerCase() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toLowerCase" }], + }); + } + + toUpperCase() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toUpperCase" }], + }); + } + + get isDatetime() { + return !!this._def.checks.find((ch) => ch.kind === "datetime"); + } + + get isDate() { + return !!this._def.checks.find((ch) => ch.kind === "date"); + } + + get isTime() { + return !!this._def.checks.find((ch) => ch.kind === "time"); + } + get isDuration() { + return !!this._def.checks.find((ch) => ch.kind === "duration"); + } + + get isEmail() { + return !!this._def.checks.find((ch) => ch.kind === "email"); + } + + get isURL() { + return !!this._def.checks.find((ch) => ch.kind === "url"); + } + + get isEmoji() { + return !!this._def.checks.find((ch) => ch.kind === "emoji"); + } + + get isUUID() { + return !!this._def.checks.find((ch) => ch.kind === "uuid"); + } + get isNANOID() { + return !!this._def.checks.find((ch) => ch.kind === "nanoid"); + } + get isCUID() { + return !!this._def.checks.find((ch) => ch.kind === "cuid"); + } + + get isCUID2() { + return !!this._def.checks.find((ch) => ch.kind === "cuid2"); + } + get isULID() { + return !!this._def.checks.find((ch) => ch.kind === "ulid"); + } + get isIP() { + return !!this._def.checks.find((ch) => ch.kind === "ip"); + } + get isCIDR() { + return !!this._def.checks.find((ch) => ch.kind === "cidr"); + } + get isBase64() { + return !!this._def.checks.find((ch) => ch.kind === "base64"); + } + get isBase64url() { + // base64url encoding is a modification of base64 that can safely be used in URLs and filenames + return !!this._def.checks.find((ch) => ch.kind === "base64url"); + } + + get minLength() { + let min: number | null = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) min = ch.value; + } + } + return min; + } + + get maxLength() { + let max: number | null = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) max = ch.value; + } + } + return max; + } + + static create = (params?: RawCreateParams & { coerce?: true }): ZodString => { + return new ZodString({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodString, + coerce: params?.coerce ?? false, + ...processCreateParams(params), + }); + }; +} + +///////////////////////////////////////// +///////////////////////////////////////// +////////// ////////// +////////// ZodNumber ////////// +////////// ////////// +///////////////////////////////////////// +///////////////////////////////////////// +export type ZodNumberCheck = + | { kind: "min"; value: number; inclusive: boolean; message?: string | undefined } + | { kind: "max"; value: number; inclusive: boolean; message?: string | undefined } + | { kind: "int"; message?: string | undefined } + | { kind: "multipleOf"; value: number; message?: string | undefined } + | { kind: "finite"; message?: string | undefined }; + +// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034 +function floatSafeRemainder(val: number, step: number) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); + return (valInt % stepInt) / 10 ** decCount; +} + +export interface ZodNumberDef extends ZodTypeDef { + checks: ZodNumberCheck[]; + typeName: ZodFirstPartyTypeKind.ZodNumber; + coerce: boolean; +} + +export class ZodNumber extends ZodType { + _parse(input: ParseInput): ParseReturnType { + if (this._def.coerce) { + input.data = Number(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.number) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.number, + received: ctx.parsedType, + }); + return INVALID; + } + + let ctx: undefined | ParseContext = undefined; + const status = new ParseStatus(); + + for (const check of this._def.checks) { + if (check.kind === "int") { + if (!util.isInteger(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: "integer", + received: "float", + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "min") { + const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "max") { + const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "multipleOf") { + if (floatSafeRemainder(input.data, check.value) !== 0) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "finite") { + if (!Number.isFinite(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_finite, + message: check.message, + }); + status.dirty(); + } + } else { + util.assertNever(check); + } + } + + return { status: status.value, value: input.data }; + } + + static create = (params?: RawCreateParams & { coerce?: boolean }): ZodNumber => { + return new ZodNumber({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodNumber, + coerce: params?.coerce || false, + ...processCreateParams(params), + }); + }; + + gte(value: number, message?: errorUtil.ErrMessage) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + min = this.gte; + + gt(value: number, message?: errorUtil.ErrMessage) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + + lte(value: number, message?: errorUtil.ErrMessage) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + max = this.lte; + + lt(value: number, message?: errorUtil.ErrMessage) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + + protected setLimit(kind: "min" | "max", value: number, inclusive: boolean, message?: string) { + return new ZodNumber({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message), + }, + ], + }); + } + + _addCheck(check: ZodNumberCheck) { + return new ZodNumber({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + + int(message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "int", + message: errorUtil.toString(message), + }); + } + + positive(message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: false, + message: errorUtil.toString(message), + }); + } + + negative(message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: false, + message: errorUtil.toString(message), + }); + } + + nonpositive(message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: true, + message: errorUtil.toString(message), + }); + } + + nonnegative(message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: true, + message: errorUtil.toString(message), + }); + } + + multipleOf(value: number, message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "multipleOf", + value: value, + message: errorUtil.toString(message), + }); + } + step = this.multipleOf; + + finite(message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "finite", + message: errorUtil.toString(message), + }); + } + + safe(message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "min", + inclusive: true, + value: Number.MIN_SAFE_INTEGER, + message: errorUtil.toString(message), + })._addCheck({ + kind: "max", + inclusive: true, + value: Number.MAX_SAFE_INTEGER, + message: errorUtil.toString(message), + }); + } + + get minValue() { + let min: number | null = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) min = ch.value; + } + } + return min; + } + + get maxValue() { + let max: number | null = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) max = ch.value; + } + } + return max; + } + + get isInt() { + return !!this._def.checks.find((ch) => ch.kind === "int" || (ch.kind === "multipleOf" && util.isInteger(ch.value))); + } + + get isFinite() { + let max: number | null = null; + let min: number | null = null; + for (const ch of this._def.checks) { + if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { + return true; + } else if (ch.kind === "min") { + if (min === null || ch.value > min) min = ch.value; + } else if (ch.kind === "max") { + if (max === null || ch.value < max) max = ch.value; + } + } + return Number.isFinite(min) && Number.isFinite(max); + } +} + +///////////////////////////////////////// +///////////////////////////////////////// +////////// ////////// +////////// ZodBigInt ////////// +////////// ////////// +///////////////////////////////////////// +///////////////////////////////////////// +export type ZodBigIntCheck = + | { kind: "min"; value: bigint; inclusive: boolean; message?: string | undefined } + | { kind: "max"; value: bigint; inclusive: boolean; message?: string | undefined } + | { kind: "multipleOf"; value: bigint; message?: string | undefined }; + +export interface ZodBigIntDef extends ZodTypeDef { + checks: ZodBigIntCheck[]; + typeName: ZodFirstPartyTypeKind.ZodBigInt; + coerce: boolean; +} + +export class ZodBigInt extends ZodType { + _parse(input: ParseInput): ParseReturnType { + if (this._def.coerce) { + try { + input.data = BigInt(input.data); + } catch { + return this._getInvalidInput(input); + } + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.bigint) { + return this._getInvalidInput(input); + } + + let ctx: undefined | ParseContext = undefined; + const status = new ParseStatus(); + + for (const check of this._def.checks) { + if (check.kind === "min") { + const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + type: "bigint", + minimum: check.value, + inclusive: check.inclusive, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "max") { + const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + type: "bigint", + maximum: check.value, + inclusive: check.inclusive, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "multipleOf") { + if (input.data % check.value !== BigInt(0)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message, + }); + status.dirty(); + } + } else { + util.assertNever(check); + } + } + + return { status: status.value, value: input.data }; + } + + _getInvalidInput(input: ParseInput) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.bigint, + received: ctx.parsedType, + }); + return INVALID; + } + + static create = (params?: RawCreateParams & { coerce?: boolean }): ZodBigInt => { + return new ZodBigInt({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodBigInt, + coerce: params?.coerce ?? false, + ...processCreateParams(params), + }); + }; + + gte(value: bigint, message?: errorUtil.ErrMessage) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + min = this.gte; + + gt(value: bigint, message?: errorUtil.ErrMessage) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + + lte(value: bigint, message?: errorUtil.ErrMessage) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + max = this.lte; + + lt(value: bigint, message?: errorUtil.ErrMessage) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + + protected setLimit(kind: "min" | "max", value: bigint, inclusive: boolean, message?: string) { + return new ZodBigInt({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message), + }, + ], + }); + } + + _addCheck(check: ZodBigIntCheck) { + return new ZodBigInt({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + + positive(message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message), + }); + } + + negative(message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message), + }); + } + + nonpositive(message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message), + }); + } + + nonnegative(message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message), + }); + } + + multipleOf(value: bigint, message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message), + }); + } + + get minValue() { + let min: bigint | null = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) min = ch.value; + } + } + return min; + } + + get maxValue() { + let max: bigint | null = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) max = ch.value; + } + } + return max; + } +} + +////////////////////////////////////////// +////////////////////////////////////////// +////////// /////////// +////////// ZodBoolean ////////// +////////// /////////// +////////////////////////////////////////// +////////////////////////////////////////// +export interface ZodBooleanDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodBoolean; + coerce: boolean; +} + +export class ZodBoolean extends ZodType { + _parse(input: ParseInput): ParseReturnType { + if (this._def.coerce) { + input.data = Boolean(input.data); + } + const parsedType = this._getType(input); + + if (parsedType !== ZodParsedType.boolean) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.boolean, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } + + static create = (params?: RawCreateParams & { coerce?: boolean }): ZodBoolean => { + return new ZodBoolean({ + typeName: ZodFirstPartyTypeKind.ZodBoolean, + coerce: params?.coerce || false, + ...processCreateParams(params), + }); + }; +} + +/////////////////////////////////////// +/////////////////////////////////////// +////////// //////// +////////// ZodDate //////// +////////// //////// +/////////////////////////////////////// +/////////////////////////////////////// +export type ZodDateCheck = + | { kind: "min"; value: number; message?: string | undefined } + | { kind: "max"; value: number; message?: string | undefined }; +export interface ZodDateDef extends ZodTypeDef { + checks: ZodDateCheck[]; + coerce: boolean; + typeName: ZodFirstPartyTypeKind.ZodDate; +} + +export class ZodDate extends ZodType { + _parse(input: ParseInput): ParseReturnType { + if (this._def.coerce) { + input.data = new Date(input.data); + } + const parsedType = this._getType(input); + + if (parsedType !== ZodParsedType.date) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.date, + received: ctx.parsedType, + }); + return INVALID; + } + + if (Number.isNaN(input.data.getTime())) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_date, + }); + return INVALID; + } + + const status = new ParseStatus(); + let ctx: undefined | ParseContext = undefined; + + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.getTime() < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + message: check.message, + inclusive: true, + exact: false, + minimum: check.value, + type: "date", + }); + status.dirty(); + } + } else if (check.kind === "max") { + if (input.data.getTime() > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + message: check.message, + inclusive: true, + exact: false, + maximum: check.value, + type: "date", + }); + status.dirty(); + } + } else { + util.assertNever(check); + } + } + + return { + status: status.value, + value: new Date((input.data as Date).getTime()), + }; + } + + _addCheck(check: ZodDateCheck) { + return new ZodDate({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + + min(minDate: Date, message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "min", + value: minDate.getTime(), + message: errorUtil.toString(message), + }); + } + + max(maxDate: Date, message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "max", + value: maxDate.getTime(), + message: errorUtil.toString(message), + }); + } + + get minDate() { + let min: number | null = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) min = ch.value; + } + } + + return min != null ? new Date(min) : null; + } + + get maxDate() { + let max: number | null = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) max = ch.value; + } + } + + return max != null ? new Date(max) : null; + } + + static create = (params?: RawCreateParams & { coerce?: boolean }): ZodDate => { + return new ZodDate({ + checks: [], + coerce: params?.coerce || false, + typeName: ZodFirstPartyTypeKind.ZodDate, + ...processCreateParams(params), + }); + }; +} + +//////////////////////////////////////////// +//////////////////////////////////////////// +////////// ////////// +////////// ZodSymbol ////////// +////////// ////////// +//////////////////////////////////////////// +//////////////////////////////////////////// +export interface ZodSymbolDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodSymbol; +} + +export class ZodSymbol extends ZodType { + _parse(input: ParseInput): ParseReturnType { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.symbol) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.symbol, + received: ctx.parsedType, + }); + return INVALID; + } + + return OK(input.data); + } + + static create = (params?: RawCreateParams): ZodSymbol => { + return new ZodSymbol({ + typeName: ZodFirstPartyTypeKind.ZodSymbol, + ...processCreateParams(params), + }); + }; +} + +//////////////////////////////////////////// +//////////////////////////////////////////// +////////// ////////// +////////// ZodUndefined ////////// +////////// ////////// +//////////////////////////////////////////// +//////////////////////////////////////////// +export interface ZodUndefinedDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodUndefined; +} + +export class ZodUndefined extends ZodType { + _parse(input: ParseInput): ParseReturnType { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.undefined, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } + params?: RawCreateParams; + + static create = (params?: RawCreateParams): ZodUndefined => { + return new ZodUndefined({ + typeName: ZodFirstPartyTypeKind.ZodUndefined, + ...processCreateParams(params), + }); + }; +} + +/////////////////////////////////////// +/////////////////////////////////////// +////////// ////////// +////////// ZodNull ////////// +////////// ////////// +/////////////////////////////////////// +/////////////////////////////////////// +export interface ZodNullDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodNull; +} + +export class ZodNull extends ZodType { + _parse(input: ParseInput): ParseReturnType { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.null) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.null, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } + static create = (params?: RawCreateParams): ZodNull => { + return new ZodNull({ + typeName: ZodFirstPartyTypeKind.ZodNull, + ...processCreateParams(params), + }); + }; +} + +////////////////////////////////////// +////////////////////////////////////// +////////// ////////// +////////// ZodAny ////////// +////////// ////////// +////////////////////////////////////// +////////////////////////////////////// +export interface ZodAnyDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodAny; +} + +export class ZodAny extends ZodType { + // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject. + _any = true as const; + _parse(input: ParseInput): ParseReturnType { + return OK(input.data); + } + static create = (params?: RawCreateParams): ZodAny => { + return new ZodAny({ + typeName: ZodFirstPartyTypeKind.ZodAny, + ...processCreateParams(params), + }); + }; +} + +////////////////////////////////////////// +////////////////////////////////////////// +////////// ////////// +////////// ZodUnknown ////////// +////////// ////////// +////////////////////////////////////////// +////////////////////////////////////////// +export interface ZodUnknownDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodUnknown; +} + +export class ZodUnknown extends ZodType { + // required + _unknown = true as const; + _parse(input: ParseInput): ParseReturnType { + return OK(input.data); + } + + static create = (params?: RawCreateParams): ZodUnknown => { + return new ZodUnknown({ + typeName: ZodFirstPartyTypeKind.ZodUnknown, + ...processCreateParams(params), + }); + }; +} + +//////////////////////////////////////// +//////////////////////////////////////// +////////// ////////// +////////// ZodNever ////////// +////////// ////////// +//////////////////////////////////////// +//////////////////////////////////////// +export interface ZodNeverDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodNever; +} + +export class ZodNever extends ZodType { + _parse(input: ParseInput): ParseReturnType { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.never, + received: ctx.parsedType, + }); + return INVALID; + } + static create = (params?: RawCreateParams): ZodNever => { + return new ZodNever({ + typeName: ZodFirstPartyTypeKind.ZodNever, + ...processCreateParams(params), + }); + }; +} + +/////////////////////////////////////// +/////////////////////////////////////// +////////// ////////// +////////// ZodVoid ////////// +////////// ////////// +/////////////////////////////////////// +/////////////////////////////////////// +export interface ZodVoidDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodVoid; +} + +export class ZodVoid extends ZodType { + _parse(input: ParseInput): ParseReturnType { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.void, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } + + static create = (params?: RawCreateParams): ZodVoid => { + return new ZodVoid({ + typeName: ZodFirstPartyTypeKind.ZodVoid, + ...processCreateParams(params), + }); + }; +} + +//////////////////////////////////////// +//////////////////////////////////////// +////////// ////////// +////////// ZodArray ////////// +////////// ////////// +//////////////////////////////////////// +//////////////////////////////////////// +export interface ZodArrayDef extends ZodTypeDef { + type: T; + typeName: ZodFirstPartyTypeKind.ZodArray; + exactLength: { value: number; message?: string | undefined } | null; + minLength: { value: number; message?: string | undefined } | null; + maxLength: { value: number; message?: string | undefined } | null; +} + +export type ArrayCardinality = "many" | "atleastone"; +export type arrayOutputType< + T extends ZodTypeAny, + Cardinality extends ArrayCardinality = "many", +> = Cardinality extends "atleastone" ? [T["_output"], ...T["_output"][]] : T["_output"][]; + +export class ZodArray extends ZodType< + arrayOutputType, + ZodArrayDef, + Cardinality extends "atleastone" ? [T["_input"], ...T["_input"][]] : T["_input"][] +> { + _parse(input: ParseInput): ParseReturnType { + const { ctx, status } = this._processInputParams(input); + + const def = this._def; + + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType, + }); + return INVALID; + } + + if (def.exactLength !== null) { + const tooBig = ctx.data.length > def.exactLength.value; + const tooSmall = ctx.data.length < def.exactLength.value; + if (tooBig || tooSmall) { + addIssueToContext(ctx, { + code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, + minimum: (tooSmall ? def.exactLength.value : undefined) as number, + maximum: (tooBig ? def.exactLength.value : undefined) as number, + type: "array", + inclusive: true, + exact: true, + message: def.exactLength.message, + }); + status.dirty(); + } + } + + if (def.minLength !== null) { + if (ctx.data.length < def.minLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.minLength.message, + }); + status.dirty(); + } + } + + if (def.maxLength !== null) { + if (ctx.data.length > def.maxLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.maxLength.message, + }); + status.dirty(); + } + } + + if (ctx.common.async) { + return Promise.all( + ([...ctx.data] as any[]).map((item, i) => { + return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + }) + ).then((result) => { + return ParseStatus.mergeArray(status, result); + }); + } + + const result = ([...ctx.data] as any[]).map((item, i) => { + return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + }); + + return ParseStatus.mergeArray(status, result); + } + + get element() { + return this._def.type; + } + + min(minLength: number, message?: errorUtil.ErrMessage): this { + return new ZodArray({ + ...this._def, + minLength: { value: minLength, message: errorUtil.toString(message) }, + }) as any; + } + + max(maxLength: number, message?: errorUtil.ErrMessage): this { + return new ZodArray({ + ...this._def, + maxLength: { value: maxLength, message: errorUtil.toString(message) }, + }) as any; + } + + length(len: number, message?: errorUtil.ErrMessage): this { + return new ZodArray({ + ...this._def, + exactLength: { value: len, message: errorUtil.toString(message) }, + }) as any; + } + + nonempty(message?: errorUtil.ErrMessage): ZodArray { + return this.min(1, message) as any; + } + + static create = (schema: El, params?: RawCreateParams): ZodArray => { + return new ZodArray({ + type: schema, + minLength: null, + maxLength: null, + exactLength: null, + typeName: ZodFirstPartyTypeKind.ZodArray, + ...processCreateParams(params), + }); + }; +} + +export type ZodNonEmptyArray = ZodArray; + +///////////////////////////////////////// +///////////////////////////////////////// +////////// ////////// +////////// ZodObject ////////// +////////// ////////// +///////////////////////////////////////// +///////////////////////////////////////// + +export type UnknownKeysParam = "passthrough" | "strict" | "strip"; + +export interface ZodObjectDef< + T extends ZodRawShape = ZodRawShape, + UnknownKeys extends UnknownKeysParam = UnknownKeysParam, + Catchall extends ZodTypeAny = ZodTypeAny, +> extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodObject; + shape: () => T; + catchall: Catchall; + unknownKeys: UnknownKeys; +} + +export type mergeTypes = { + [k in keyof A | keyof B]: k extends keyof B ? B[k] : k extends keyof A ? A[k] : never; +}; + +export type objectOutputType< + Shape extends ZodRawShape, + Catchall extends ZodTypeAny, + UnknownKeys extends UnknownKeysParam = UnknownKeysParam, +> = objectUtil.flatten>> & + CatchallOutput & + PassthroughType; + +export type baseObjectOutputType = { + [k in keyof Shape]: Shape[k]["_output"]; +}; + +export type objectInputType< + Shape extends ZodRawShape, + Catchall extends ZodTypeAny, + UnknownKeys extends UnknownKeysParam = UnknownKeysParam, +> = objectUtil.flatten> & CatchallInput & PassthroughType; +export type baseObjectInputType = objectUtil.addQuestionMarks<{ + [k in keyof Shape]: Shape[k]["_input"]; +}>; + +export type CatchallOutput = ZodType extends T ? unknown : { [k: string]: T["_output"] }; + +export type CatchallInput = ZodType extends T ? unknown : { [k: string]: T["_input"] }; + +export type PassthroughType = T extends "passthrough" ? { [k: string]: unknown } : unknown; + +export type deoptional = T extends ZodOptional + ? deoptional + : T extends ZodNullable + ? ZodNullable> + : T; + +export type SomeZodObject = ZodObject; + +export type noUnrecognized = { + [k in keyof Obj]: k extends keyof Shape ? Obj[k] : never; +}; + +function deepPartialify(schema: ZodTypeAny): any { + if (schema instanceof ZodObject) { + const newShape: any = {}; + + for (const key in schema.shape) { + const fieldSchema = schema.shape[key]; + newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); + } + return new ZodObject({ + ...schema._def, + shape: () => newShape, + }) as any; + } else if (schema instanceof ZodArray) { + return new ZodArray({ + ...schema._def, + type: deepPartialify(schema.element), + }); + } else if (schema instanceof ZodOptional) { + return ZodOptional.create(deepPartialify(schema.unwrap())); + } else if (schema instanceof ZodNullable) { + return ZodNullable.create(deepPartialify(schema.unwrap())); + } else if (schema instanceof ZodTuple) { + return ZodTuple.create(schema.items.map((item: any) => deepPartialify(item))); + } else { + return schema; + } +} + +export class ZodObject< + T extends ZodRawShape, + UnknownKeys extends UnknownKeysParam = UnknownKeysParam, + Catchall extends ZodTypeAny = ZodTypeAny, + Output = objectOutputType, + Input = objectInputType, +> extends ZodType, Input> { + private _cached: { shape: T; keys: string[] } | null = null; + + _getCached(): { shape: T; keys: string[] } { + if (this._cached !== null) return this._cached; + const shape = this._def.shape(); + const keys = util.objectKeys(shape); + this._cached = { shape, keys }; + return this._cached; + } + + _parse(input: ParseInput): ParseReturnType { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.object) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType, + }); + return INVALID; + } + + const { status, ctx } = this._processInputParams(input); + + const { shape, keys: shapeKeys } = this._getCached(); + const extraKeys: string[] = []; + + if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { + for (const key in ctx.data) { + if (!shapeKeys.includes(key)) { + extraKeys.push(key); + } + } + } + + const pairs: { + key: ParseReturnType; + value: ParseReturnType; + alwaysSet?: boolean; + }[] = []; + for (const key of shapeKeys) { + const keyValidator = shape[key]!; + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), + alwaysSet: key in ctx.data, + }); + } + + if (this._def.catchall instanceof ZodNever) { + const unknownKeys = this._def.unknownKeys; + + if (unknownKeys === "passthrough") { + for (const key of extraKeys) { + pairs.push({ + key: { status: "valid", value: key }, + value: { status: "valid", value: ctx.data[key] }, + }); + } + } else if (unknownKeys === "strict") { + if (extraKeys.length > 0) { + addIssueToContext(ctx, { + code: ZodIssueCode.unrecognized_keys, + keys: extraKeys, + }); + status.dirty(); + } + } else if (unknownKeys === "strip") { + } else { + throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); + } + } else { + // run catchall validation + const catchall = this._def.catchall; + + for (const key of extraKeys) { + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: catchall._parse( + new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value) + ), + alwaysSet: key in ctx.data, + }); + } + } + + if (ctx.common.async) { + return Promise.resolve() + .then(async () => { + const syncPairs: any[] = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value, + alwaysSet: pair.alwaysSet, + }); + } + return syncPairs; + }) + .then((syncPairs) => { + return ParseStatus.mergeObjectSync(status, syncPairs); + }); + } else { + return ParseStatus.mergeObjectSync(status, pairs as any); + } + } + + get shape() { + return this._def.shape(); + } + + strict(message?: errorUtil.ErrMessage): ZodObject { + errorUtil.errToObj; + return new ZodObject({ + ...this._def, + unknownKeys: "strict", + ...(message !== undefined + ? { + errorMap: (issue, ctx) => { + const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError; + if (issue.code === "unrecognized_keys") + return { + message: errorUtil.errToObj(message).message ?? defaultError, + }; + return { + message: defaultError, + }; + }, + } + : {}), + }) as any; + } + + strip(): ZodObject { + return new ZodObject({ + ...this._def, + unknownKeys: "strip", + }) as any; + } + + passthrough(): ZodObject { + return new ZodObject({ + ...this._def, + unknownKeys: "passthrough", + }) as any; + } + + /** + * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped. + * If you want to pass through unknown properties, use `.passthrough()` instead. + */ + nonstrict = this.passthrough; + + // const AugmentFactory = + // (def: Def) => + // ( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, Augmentation>, + // Def["unknownKeys"], + // Def["catchall"] + // > => { + // return new ZodObject({ + // ...def, + // shape: () => ({ + // ...def.shape(), + // ...augmentation, + // }), + // }) as any; + // }; + extend( + augmentation: Augmentation + ): ZodObject, UnknownKeys, Catchall> { + return new ZodObject({ + ...this._def, + shape: () => ({ + ...this._def.shape(), + ...augmentation, + }), + }) as any; + } + // extend< + // Augmentation extends ZodRawShape, + // NewOutput extends util.flatten<{ + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }>, + // NewInput extends util.flatten<{ + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // }> + // >( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, + // UnknownKeys, + // Catchall, + // NewOutput, + // NewInput + // > { + // return new ZodObject({ + // ...this._def, + // shape: () => ({ + // ...this._def.shape(), + // ...augmentation, + // }), + // }) as any; + // } + /** + * @deprecated Use `.extend` instead + * */ + augment = this.extend; + + /** + * Prior to zod@1.0.12 there was a bug in the + * inferred type of merged objects. Please + * upgrade if you are experiencing issues. + */ + merge( + merging: Incoming + ): ZodObject, Incoming["_def"]["unknownKeys"], Incoming["_def"]["catchall"]> { + const merged: any = new ZodObject({ + unknownKeys: merging._def.unknownKeys, + catchall: merging._def.catchall, + shape: () => ({ + ...this._def.shape(), + ...merging._def.shape(), + }), + typeName: ZodFirstPartyTypeKind.ZodObject, + }) as any; + return merged; + } + // merge< + // Incoming extends AnyZodObject, + // Augmentation extends Incoming["shape"], + // NewOutput extends { + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }, + // NewInput extends { + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // } + // >( + // merging: Incoming + // ): ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"], + // NewOutput, + // NewInput + // > { + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + + setKey( + key: Key, + schema: Schema + ): ZodObject { + return this.augment({ [key]: schema }) as any; + } + // merge( + // merging: Incoming + // ): //ZodObject = (merging) => { + // ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"] + // > { + // // const mergedShape = objectUtil.mergeShapes( + // // this._def.shape(), + // // merging._def.shape() + // // ); + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + + catchall(index: Index): ZodObject { + return new ZodObject({ + ...this._def, + catchall: index, + }) as any; + } + + pick>( + mask: Mask + ): ZodObject>, UnknownKeys, Catchall> { + const shape: any = {}; + + for (const key of util.objectKeys(mask)) { + if (mask[key] && this.shape[key]) { + shape[key] = this.shape[key]; + } + } + + return new ZodObject({ + ...this._def, + shape: () => shape, + }) as any; + } + + omit>( + mask: Mask + ): ZodObject, UnknownKeys, Catchall> { + const shape: any = {}; + + for (const key of util.objectKeys(this.shape)) { + if (!mask[key]) { + shape[key] = this.shape[key]; + } + } + + return new ZodObject({ + ...this._def, + shape: () => shape, + }) as any; + } + + /** + * @deprecated + */ + deepPartial(): partialUtil.DeepPartial { + return deepPartialify(this); + } + + partial(): ZodObject<{ [k in keyof T]: ZodOptional }, UnknownKeys, Catchall>; + partial>( + mask: Mask + ): ZodObject< + objectUtil.noNever<{ + [k in keyof T]: k extends keyof Mask ? ZodOptional : T[k]; + }>, + UnknownKeys, + Catchall + >; + partial(mask?: any) { + const newShape: any = {}; + + for (const key of util.objectKeys(this.shape)) { + const fieldSchema = this.shape[key]!; + + if (mask && !mask[key]) { + newShape[key] = fieldSchema; + } else { + newShape[key] = fieldSchema.optional(); + } + } + + return new ZodObject({ + ...this._def, + shape: () => newShape, + }) as any; + } + + required(): ZodObject<{ [k in keyof T]: deoptional }, UnknownKeys, Catchall>; + required>( + mask: Mask + ): ZodObject< + objectUtil.noNever<{ + [k in keyof T]: k extends keyof Mask ? deoptional : T[k]; + }>, + UnknownKeys, + Catchall + >; + required(mask?: any) { + const newShape: any = {}; + + for (const key of util.objectKeys(this.shape)) { + if (mask && !mask[key]) { + newShape[key] = this.shape[key]; + } else { + const fieldSchema = this.shape[key]; + let newField = fieldSchema; + + while (newField instanceof ZodOptional) { + newField = (newField as ZodOptional)._def.innerType; + } + + newShape[key] = newField; + } + } + + return new ZodObject({ + ...this._def, + shape: () => newShape, + }) as any; + } + + keyof(): ZodEnum> { + return createZodEnum(util.objectKeys(this.shape) as [string, ...string[]]) as any; + } + + static create = ( + shape: Shape, + params?: RawCreateParams + ): ZodObject< + Shape, + "strip", + ZodTypeAny, + objectOutputType, + objectInputType + > => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }) as any; + }; + + static strictCreate = ( + shape: Shape, + params?: RawCreateParams + ): ZodObject => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strict", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }) as any; + }; + + static lazycreate = ( + shape: () => Shape, + params?: RawCreateParams + ): ZodObject => { + return new ZodObject({ + shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }) as any; + }; +} + +export type AnyZodObject = ZodObject; + +//////////////////////////////////////// +//////////////////////////////////////// +////////// ////////// +////////// ZodUnion ////////// +////////// ////////// +//////////////////////////////////////// +//////////////////////////////////////// +export type ZodUnionOptions = Readonly<[ZodTypeAny, ...ZodTypeAny[]]>; +export interface ZodUnionDef> + extends ZodTypeDef { + options: T; + typeName: ZodFirstPartyTypeKind.ZodUnion; +} + +export class ZodUnion extends ZodType< + T[number]["_output"], + ZodUnionDef, + T[number]["_input"] +> { + _parse(input: ParseInput): ParseReturnType { + const { ctx } = this._processInputParams(input); + const options = this._def.options; + + function handleResults(results: { ctx: ParseContext; result: SyncParseReturnType }[]) { + // return first issue-free validation if it exists + for (const result of results) { + if (result.result.status === "valid") { + return result.result; + } + } + + for (const result of results) { + if (result.result.status === "dirty") { + // add issues from dirty option + + ctx.common.issues.push(...result.ctx.common.issues); + return result.result; + } + } + + // return invalid + const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); + + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors, + }); + return INVALID; + } + + if (ctx.common.async) { + return Promise.all( + options.map(async (option) => { + const childCtx: ParseContext = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + parent: null, + }; + return { + result: await option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: childCtx, + }), + ctx: childCtx, + }; + }) + ).then(handleResults); + } else { + let dirty: undefined | { result: DIRTY; ctx: ParseContext } = undefined; + const issues: ZodIssue[][] = []; + for (const option of options) { + const childCtx: ParseContext = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + parent: null, + }; + const result = option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: childCtx, + }); + + if (result.status === "valid") { + return result; + } else if (result.status === "dirty" && !dirty) { + dirty = { result, ctx: childCtx }; + } + + if (childCtx.common.issues.length) { + issues.push(childCtx.common.issues); + } + } + + if (dirty) { + ctx.common.issues.push(...dirty.ctx.common.issues); + return dirty.result; + } + + const unionErrors = issues.map((issues) => new ZodError(issues)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors, + }); + + return INVALID; + } + } + + get options() { + return this._def.options; + } + + static create = >( + types: Options, + params?: RawCreateParams + ): ZodUnion => { + return new ZodUnion({ + options: types, + typeName: ZodFirstPartyTypeKind.ZodUnion, + ...processCreateParams(params), + }); + }; +} + +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// +////////// ////////// +////////// ZodDiscriminatedUnion ////////// +////////// ////////// +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// + +const getDiscriminator = (type: T): Primitive[] => { + if (type instanceof ZodLazy) { + return getDiscriminator(type.schema); + } else if (type instanceof ZodEffects) { + return getDiscriminator(type.innerType()); + } else if (type instanceof ZodLiteral) { + return [type.value]; + } else if (type instanceof ZodEnum) { + return type.options; + } else if (type instanceof ZodNativeEnum) { + // eslint-disable-next-line ban/ban + return util.objectValues(type.enum); + } else if (type instanceof ZodDefault) { + return getDiscriminator(type._def.innerType); + } else if (type instanceof ZodUndefined) { + return [undefined]; + } else if (type instanceof ZodNull) { + return [null]; + } else if (type instanceof ZodOptional) { + return [undefined, ...getDiscriminator(type.unwrap())]; + } else if (type instanceof ZodNullable) { + return [null, ...getDiscriminator(type.unwrap())]; + } else if (type instanceof ZodBranded) { + return getDiscriminator(type.unwrap()); + } else if (type instanceof ZodReadonly) { + return getDiscriminator(type.unwrap()); + } else if (type instanceof ZodCatch) { + return getDiscriminator(type._def.innerType); + } else { + return []; + } +}; + +export type ZodDiscriminatedUnionOption = ZodObject< + { [key in Discriminator]: ZodTypeAny } & ZodRawShape, + UnknownKeysParam, + ZodTypeAny +>; + +export interface ZodDiscriminatedUnionDef< + Discriminator extends string, + Options extends readonly ZodDiscriminatedUnionOption[] = ZodDiscriminatedUnionOption[], +> extends ZodTypeDef { + discriminator: Discriminator; + options: Options; + optionsMap: Map>; + typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion; +} + +export class ZodDiscriminatedUnion< + Discriminator extends string, + Options extends readonly ZodDiscriminatedUnionOption[], +> extends ZodType, ZodDiscriminatedUnionDef, input> { + _parse(input: ParseInput): ParseReturnType { + const { ctx } = this._processInputParams(input); + + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType, + }); + return INVALID; + } + + const discriminator = this.discriminator; + + const discriminatorValue: string = ctx.data[discriminator]; + + const option = this.optionsMap.get(discriminatorValue); + + if (!option) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union_discriminator, + options: Array.from(this.optionsMap.keys()), + path: [discriminator], + }); + return INVALID; + } + + if (ctx.common.async) { + return option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }) as any; + } else { + return option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }) as any; + } + } + + get discriminator() { + return this._def.discriminator; + } + + get options() { + return this._def.options; + } + + get optionsMap() { + return this._def.optionsMap; + } + + /** + * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. + * However, it only allows a union of objects, all of which need to share a discriminator property. This property must + * have a different value for each object in the union. + * @param discriminator the name of the discriminator property + * @param types an array of object schemas + * @param params + */ + static create< + Discriminator extends string, + Types extends readonly [ + ZodDiscriminatedUnionOption, + ...ZodDiscriminatedUnionOption[], + ], + >( + discriminator: Discriminator, + options: Types, + params?: RawCreateParams + ): ZodDiscriminatedUnion { + // Get all the valid discriminator values + const optionsMap: Map = new Map(); + + // try { + for (const type of options) { + const discriminatorValues = getDiscriminator(type.shape[discriminator]); + if (!discriminatorValues.length) { + throw new Error( + `A discriminator value for key \`${discriminator}\` could not be extracted from all schema options` + ); + } + for (const value of discriminatorValues) { + if (optionsMap.has(value)) { + throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); + } + + optionsMap.set(value, type); + } + } + + return new ZodDiscriminatedUnion< + Discriminator, + // DiscriminatorValue, + Types + >({ + typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, + discriminator, + options, + optionsMap, + ...processCreateParams(params), + }); + } +} + +/////////////////////////////////////////////// +/////////////////////////////////////////////// +////////// ////////// +////////// ZodIntersection ////////// +////////// ////////// +/////////////////////////////////////////////// +/////////////////////////////////////////////// +export interface ZodIntersectionDef + extends ZodTypeDef { + left: T; + right: U; + typeName: ZodFirstPartyTypeKind.ZodIntersection; +} + +function mergeValues(a: any, b: any): { valid: true; data: any } | { valid: false } { + const aType = getParsedType(a); + const bType = getParsedType(b); + + if (a === b) { + return { valid: true, data: a }; + } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { + const bKeys = util.objectKeys(b); + const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); + + const newObj: any = { ...a, ...b }; + for (const key of sharedKeys) { + const sharedValue = mergeValues(a[key], b[key]); + if (!sharedValue.valid) { + return { valid: false }; + } + newObj[key] = sharedValue.data; + } + + return { valid: true, data: newObj }; + } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { + if (a.length !== b.length) { + return { valid: false }; + } + + const newArray: unknown[] = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = mergeValues(itemA, itemB); + + if (!sharedValue.valid) { + return { valid: false }; + } + + newArray.push(sharedValue.data); + } + + return { valid: true, data: newArray }; + } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { + return { valid: true, data: a }; + } else { + return { valid: false }; + } +} + +export class ZodIntersection extends ZodType< + T["_output"] & U["_output"], + ZodIntersectionDef, + T["_input"] & U["_input"] +> { + _parse(input: ParseInput): ParseReturnType { + const { status, ctx } = this._processInputParams(input); + const handleParsed = ( + parsedLeft: SyncParseReturnType, + parsedRight: SyncParseReturnType + ): SyncParseReturnType => { + if (isAborted(parsedLeft) || isAborted(parsedRight)) { + return INVALID; + } + + const merged = mergeValues(parsedLeft.value, parsedRight.value); + + if (!merged.valid) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_intersection_types, + }); + return INVALID; + } + + if (isDirty(parsedLeft) || isDirty(parsedRight)) { + status.dirty(); + } + + return { status: status.value, value: merged.data }; + }; + + if (ctx.common.async) { + return Promise.all([ + this._def.left._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), + this._def.right._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), + ]).then(([left, right]: any) => handleParsed(left, right)); + } else { + return handleParsed( + this._def.left._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), + this._def.right._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }) + ); + } + } + + static create = ( + left: TSchema, + right: USchema, + params?: RawCreateParams + ): ZodIntersection => { + return new ZodIntersection({ + left: left, + right: right, + typeName: ZodFirstPartyTypeKind.ZodIntersection, + ...processCreateParams(params), + }); + }; +} + +//////////////////////////////////////// +//////////////////////////////////////// +////////// ////////// +////////// ZodTuple ////////// +////////// ////////// +//////////////////////////////////////// +//////////////////////////////////////// +export type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]]; +export type AssertArray = T extends any[] ? T : never; +export type OutputTypeOfTuple = AssertArray<{ + [k in keyof T]: T[k] extends ZodType ? T[k]["_output"] : never; +}>; +export type OutputTypeOfTupleWithRest< + T extends ZodTupleItems | [], + Rest extends ZodTypeAny | null = null, +> = Rest extends ZodTypeAny ? [...OutputTypeOfTuple, ...Rest["_output"][]] : OutputTypeOfTuple; + +export type InputTypeOfTuple = AssertArray<{ + [k in keyof T]: T[k] extends ZodType ? T[k]["_input"] : never; +}>; +export type InputTypeOfTupleWithRest< + T extends ZodTupleItems | [], + Rest extends ZodTypeAny | null = null, +> = Rest extends ZodTypeAny ? [...InputTypeOfTuple, ...Rest["_input"][]] : InputTypeOfTuple; + +export interface ZodTupleDef + extends ZodTypeDef { + items: T; + rest: Rest; + typeName: ZodFirstPartyTypeKind.ZodTuple; +} + +export type AnyZodTuple = ZodTuple<[ZodTypeAny, ...ZodTypeAny[]] | [], ZodTypeAny | null>; +// type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]]; +export class ZodTuple< + T extends ZodTupleItems | [] = ZodTupleItems, + Rest extends ZodTypeAny | null = null, +> extends ZodType, ZodTupleDef, InputTypeOfTupleWithRest> { + _parse(input: ParseInput): ParseReturnType { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType, + }); + return INVALID; + } + + if (ctx.data.length < this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: this._def.items.length, + inclusive: true, + exact: false, + type: "array", + }); + + return INVALID; + } + + const rest = this._def.rest; + + if (!rest && ctx.data.length > this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: this._def.items.length, + inclusive: true, + exact: false, + type: "array", + }); + status.dirty(); + } + + const items = ([...ctx.data] as any[]) + .map((item, itemIndex) => { + const schema = this._def.items[itemIndex] || this._def.rest; + if (!schema) return null as any as SyncParseReturnType; + return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); + }) + .filter((x) => !!x); // filter nulls + + if (ctx.common.async) { + return Promise.all(items).then((results) => { + return ParseStatus.mergeArray(status, results); + }); + } else { + return ParseStatus.mergeArray(status, items as SyncParseReturnType[]); + } + } + + get items() { + return this._def.items; + } + + rest(rest: RestSchema): ZodTuple { + return new ZodTuple({ + ...this._def, + rest, + }); + } + + static create = ( + schemas: Items, + params?: RawCreateParams + ): ZodTuple => { + if (!Array.isArray(schemas)) { + throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); + } + return new ZodTuple({ + items: schemas, + typeName: ZodFirstPartyTypeKind.ZodTuple, + rest: null, + ...processCreateParams(params), + }); + }; +} + +///////////////////////////////////////// +///////////////////////////////////////// +////////// ////////// +////////// ZodRecord ////////// +////////// ////////// +///////////////////////////////////////// +///////////////////////////////////////// +export interface ZodRecordDef + extends ZodTypeDef { + valueType: Value; + keyType: Key; + typeName: ZodFirstPartyTypeKind.ZodRecord; +} + +export type KeySchema = ZodType; +export type RecordType = [string] extends [K] + ? Record + : [number] extends [K] + ? Record + : [symbol] extends [K] + ? Record + : [BRAND] extends [K] + ? Record + : Partial>; +export class ZodRecord extends ZodType< + RecordType, + ZodRecordDef, + RecordType +> { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input: ParseInput): ParseReturnType { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType, + }); + return INVALID; + } + + const pairs: { + key: ParseReturnType; + value: ParseReturnType; + alwaysSet: boolean; + }[] = []; + + const keyType = this._def.keyType; + const valueType = this._def.valueType; + + for (const key in ctx.data) { + pairs.push({ + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), + value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), + alwaysSet: key in ctx.data, + }); + } + + if (ctx.common.async) { + return ParseStatus.mergeObjectAsync(status, pairs); + } else { + return ParseStatus.mergeObjectSync(status, pairs as any); + } + } + + get element() { + return this._def.valueType; + } + + static create(valueType: Value, params?: RawCreateParams): ZodRecord; + static create( + keySchema: Keys, + valueType: Value, + params?: RawCreateParams + ): ZodRecord; + static create(first: any, second?: any, third?: any): ZodRecord { + if (second instanceof ZodType) { + return new ZodRecord({ + keyType: first, + valueType: second, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(third), + }); + } + + return new ZodRecord({ + keyType: ZodString.create(), + valueType: first, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(second), + }); + } +} + +////////////////////////////////////// +////////////////////////////////////// +////////// ////////// +////////// ZodMap ////////// +////////// ////////// +////////////////////////////////////// +////////////////////////////////////// +export interface ZodMapDef + extends ZodTypeDef { + valueType: Value; + keyType: Key; + typeName: ZodFirstPartyTypeKind.ZodMap; +} + +export class ZodMap extends ZodType< + Map, + ZodMapDef, + Map +> { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input: ParseInput): ParseReturnType { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.map) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.map, + received: ctx.parsedType, + }); + return INVALID; + } + + const keyType = this._def.keyType; + const valueType = this._def.valueType; + + const pairs = [...(ctx.data as Map).entries()].map(([key, value], index) => { + return { + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), + value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])), + }; + }); + + if (ctx.common.async) { + const finalMap = new Map(); + return Promise.resolve().then(async () => { + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + }); + } else { + const finalMap = new Map(); + for (const pair of pairs) { + const key = pair.key as SyncParseReturnType; + const value = pair.value as SyncParseReturnType; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + } + } + static create = ( + keyType: KeySchema, + valueType: ValueSchema, + params?: RawCreateParams + ): ZodMap => { + return new ZodMap({ + valueType, + keyType, + typeName: ZodFirstPartyTypeKind.ZodMap, + ...processCreateParams(params), + }); + }; +} + +////////////////////////////////////// +////////////////////////////////////// +////////// ////////// +////////// ZodSet ////////// +////////// ////////// +////////////////////////////////////// +////////////////////////////////////// +export interface ZodSetDef extends ZodTypeDef { + valueType: Value; + typeName: ZodFirstPartyTypeKind.ZodSet; + minSize: { value: number; message?: string | undefined } | null; + maxSize: { value: number; message?: string | undefined } | null; +} + +export class ZodSet extends ZodType< + Set, + ZodSetDef, + Set +> { + _parse(input: ParseInput): ParseReturnType { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.set) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.set, + received: ctx.parsedType, + }); + return INVALID; + } + + const def = this._def; + + if (def.minSize !== null) { + if (ctx.data.size < def.minSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.minSize.message, + }); + status.dirty(); + } + } + + if (def.maxSize !== null) { + if (ctx.data.size > def.maxSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.maxSize.message, + }); + status.dirty(); + } + } + + const valueType = this._def.valueType; + + function finalizeSet(elements: SyncParseReturnType[]) { + const parsedSet = new Set(); + for (const element of elements) { + if (element.status === "aborted") return INVALID; + if (element.status === "dirty") status.dirty(); + parsedSet.add(element.value); + } + return { status: status.value, value: parsedSet }; + } + + const elements = [...(ctx.data as Set).values()].map((item, i) => + valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)) + ); + + if (ctx.common.async) { + return Promise.all(elements).then((elements) => finalizeSet(elements)); + } else { + return finalizeSet(elements as SyncParseReturnType[]); + } + } + + min(minSize: number, message?: errorUtil.ErrMessage): this { + return new ZodSet({ + ...this._def, + minSize: { value: minSize, message: errorUtil.toString(message) }, + }) as any; + } + + max(maxSize: number, message?: errorUtil.ErrMessage): this { + return new ZodSet({ + ...this._def, + maxSize: { value: maxSize, message: errorUtil.toString(message) }, + }) as any; + } + + size(size: number, message?: errorUtil.ErrMessage): this { + return this.min(size, message).max(size, message) as any; + } + + nonempty(message?: errorUtil.ErrMessage): ZodSet { + return this.min(1, message) as any; + } + + static create = ( + valueType: ValueSchema, + params?: RawCreateParams + ): ZodSet => { + return new ZodSet({ + valueType, + minSize: null, + maxSize: null, + typeName: ZodFirstPartyTypeKind.ZodSet, + ...processCreateParams(params), + }); + }; +} + +/////////////////////////////////////////// +/////////////////////////////////////////// +////////// ////////// +////////// ZodFunction ////////// +////////// ////////// +/////////////////////////////////////////// +/////////////////////////////////////////// +export interface ZodFunctionDef< + Args extends ZodTuple = ZodTuple, + Returns extends ZodTypeAny = ZodTypeAny, +> extends ZodTypeDef { + args: Args; + returns: Returns; + typeName: ZodFirstPartyTypeKind.ZodFunction; +} + +export type OuterTypeOfFunction< + Args extends ZodTuple, + Returns extends ZodTypeAny, +> = Args["_input"] extends Array ? (...args: Args["_input"]) => Returns["_output"] : never; + +export type InnerTypeOfFunction< + Args extends ZodTuple, + Returns extends ZodTypeAny, +> = Args["_output"] extends Array ? (...args: Args["_output"]) => Returns["_input"] : never; + +export class ZodFunction, Returns extends ZodTypeAny> extends ZodType< + OuterTypeOfFunction, + ZodFunctionDef, + InnerTypeOfFunction +> { + _parse(input: ParseInput): ParseReturnType { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.function) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.function, + received: ctx.parsedType, + }); + return INVALID; + } + + function makeArgsIssue(args: any, error: ZodError): ZodIssue { + return makeIssue({ + data: args, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter( + (x) => !!x + ), + issueData: { + code: ZodIssueCode.invalid_arguments, + argumentsError: error, + }, + }); + } + + function makeReturnsIssue(returns: any, error: ZodError): ZodIssue { + return makeIssue({ + data: returns, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter( + (x) => !!x + ), + issueData: { + code: ZodIssueCode.invalid_return_type, + returnTypeError: error, + }, + }); + } + + const params = { errorMap: ctx.common.contextualErrorMap }; + const fn = ctx.data; + + if (this._def.returns instanceof ZodPromise) { + // Would love a way to avoid disabling this rule, but we need + // an alias (using an arrow function was what caused 2651). + // eslint-disable-next-line @typescript-eslint/no-this-alias + const me = this; + return OK(async function (this: any, ...args: any[]) { + const error = new ZodError([]); + const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { + error.addIssue(makeArgsIssue(args, e)); + throw error; + }); + const result = await Reflect.apply(fn, this, parsedArgs as any); + const parsedReturns = await (me._def.returns as unknown as ZodPromise)._def.type + .parseAsync(result, params) + .catch((e) => { + error.addIssue(makeReturnsIssue(result, e)); + throw error; + }); + return parsedReturns; + }); + } else { + // Would love a way to avoid disabling this rule, but we need + // an alias (using an arrow function was what caused 2651). + // eslint-disable-next-line @typescript-eslint/no-this-alias + const me = this; + return OK(function (this: any, ...args: any[]) { + const parsedArgs = me._def.args.safeParse(args, params); + if (!parsedArgs.success) { + throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); + } + const result = Reflect.apply(fn, this, parsedArgs.data); + const parsedReturns = me._def.returns.safeParse(result, params); + if (!parsedReturns.success) { + throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); + } + return parsedReturns.data; + }) as any; + } + } + + parameters() { + return this._def.args; + } + + returnType() { + return this._def.returns; + } + + args[0]>( + ...items: Items + ): ZodFunction, Returns> { + return new ZodFunction({ + ...this._def, + args: ZodTuple.create(items).rest(ZodUnknown.create()) as any, + }); + } + + returns>(returnType: NewReturnType): ZodFunction { + return new ZodFunction({ + ...this._def, + returns: returnType, + }); + } + + implement>( + func: F + ): ReturnType extends Returns["_output"] + ? (...args: Args["_input"]) => ReturnType + : OuterTypeOfFunction { + const validatedFunc = this.parse(func); + return validatedFunc as any; + } + + strictImplement(func: InnerTypeOfFunction): InnerTypeOfFunction { + const validatedFunc = this.parse(func); + return validatedFunc as any; + } + + validate = this.implement; + + static create(): ZodFunction, ZodUnknown>; + static create>(args: T): ZodFunction; + static create(args: T, returns: U): ZodFunction; + static create, U extends ZodTypeAny = ZodUnknown>( + args: T, + returns: U, + params?: RawCreateParams + ): ZodFunction; + static create(args?: AnyZodTuple, returns?: ZodTypeAny, params?: RawCreateParams) { + return new ZodFunction({ + args: (args ? args : ZodTuple.create([]).rest(ZodUnknown.create())) as any, + returns: returns || ZodUnknown.create(), + typeName: ZodFirstPartyTypeKind.ZodFunction, + ...processCreateParams(params), + }) as any; + } +} + +/////////////////////////////////////// +/////////////////////////////////////// +////////// ////////// +////////// ZodLazy ////////// +////////// ////////// +/////////////////////////////////////// +/////////////////////////////////////// +export interface ZodLazyDef extends ZodTypeDef { + getter: () => T; + typeName: ZodFirstPartyTypeKind.ZodLazy; +} + +export class ZodLazy extends ZodType, ZodLazyDef, input> { + get schema(): T { + return this._def.getter(); + } + + _parse(input: ParseInput): ParseReturnType { + const { ctx } = this._processInputParams(input); + const lazySchema = this._def.getter(); + return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); + } + + static create = (getter: () => Inner, params?: RawCreateParams): ZodLazy => { + return new ZodLazy({ + getter: getter, + typeName: ZodFirstPartyTypeKind.ZodLazy, + ...processCreateParams(params), + }); + }; +} + +////////////////////////////////////////// +////////////////////////////////////////// +////////// ////////// +////////// ZodLiteral ////////// +////////// ////////// +////////////////////////////////////////// +////////////////////////////////////////// +export interface ZodLiteralDef extends ZodTypeDef { + value: T; + typeName: ZodFirstPartyTypeKind.ZodLiteral; +} + +export class ZodLiteral extends ZodType, T> { + _parse(input: ParseInput): ParseReturnType { + if (input.data !== this._def.value) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_literal, + expected: this._def.value, + }); + return INVALID; + } + return { status: "valid", value: input.data }; + } + + get value() { + return this._def.value; + } + + static create = (value: Value, params?: RawCreateParams): ZodLiteral => { + return new ZodLiteral({ + value: value, + typeName: ZodFirstPartyTypeKind.ZodLiteral, + ...processCreateParams(params), + }); + }; +} + +/////////////////////////////////////// +/////////////////////////////////////// +////////// ////////// +////////// ZodEnum ////////// +////////// ////////// +/////////////////////////////////////// +/////////////////////////////////////// +export type ArrayKeys = keyof any[]; +export type Indices = Exclude; + +export type EnumValues = readonly [T, ...T[]]; + +export type Values = { + [k in T[number]]: k; +}; + +export interface ZodEnumDef extends ZodTypeDef { + values: T; + typeName: ZodFirstPartyTypeKind.ZodEnum; +} + +export type Writeable = { -readonly [P in keyof T]: T[P] }; + +export type FilterEnum = Values extends [] + ? [] + : Values extends [infer Head, ...infer Rest] + ? Head extends ToExclude + ? FilterEnum + : [Head, ...FilterEnum] + : never; + +export type typecast = A extends T ? A : never; + +function createZodEnum>( + values: T, + params?: RawCreateParams +): ZodEnum>; +function createZodEnum(values: T, params?: RawCreateParams): ZodEnum; +function createZodEnum(values: [string, ...string[]], params?: RawCreateParams) { + return new ZodEnum({ + values, + typeName: ZodFirstPartyTypeKind.ZodEnum, + ...processCreateParams(params), + }); +} + +export class ZodEnum extends ZodType, T[number]> { + _cache: Set | undefined; + + _parse(input: ParseInput): ParseReturnType { + if (typeof input.data !== "string") { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues) as "string", + received: ctx.parsedType, + code: ZodIssueCode.invalid_type, + }); + return INVALID; + } + + if (!this._cache) { + this._cache = new Set(this._def.values); + } + + if (!this._cache.has(input.data)) { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues, + }); + return INVALID; + } + return OK(input.data); + } + + get options() { + return this._def.values; + } + + get enum(): Values { + const enumValues: any = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + + get Values(): Values { + const enumValues: any = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + + get Enum(): Values { + const enumValues: any = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + + extract( + values: ToExtract, + newDef: RawCreateParams = this._def + ): ZodEnum> { + return ZodEnum.create(values, { + ...this._def, + ...newDef, + }) as any; + } + + exclude( + values: ToExclude, + newDef: RawCreateParams = this._def + ): ZodEnum>, [string, ...string[]]>> { + return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)) as FilterEnum, { + ...this._def, + ...newDef, + }) as any; + } + + static create = createZodEnum; +} + +///////////////////////////////////////////// +///////////////////////////////////////////// +////////// ////////// +////////// ZodNativeEnum ////////// +////////// ////////// +///////////////////////////////////////////// +///////////////////////////////////////////// +export interface ZodNativeEnumDef extends ZodTypeDef { + values: T; + typeName: ZodFirstPartyTypeKind.ZodNativeEnum; +} + +export type EnumLike = { [k: string]: string | number; [nu: number]: string }; + +export class ZodNativeEnum extends ZodType, T[keyof T]> { + _cache: Set | undefined; + _parse(input: ParseInput): ParseReturnType { + const nativeEnumValues = util.getValidEnumValues(this._def.values); + + const ctx = this._getOrReturnCtx(input); + if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { + const expectedValues = util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues) as "string", + received: ctx.parsedType, + code: ZodIssueCode.invalid_type, + }); + return INVALID; + } + + if (!this._cache) { + this._cache = new Set(util.getValidEnumValues(this._def.values)); + } + + if (!this._cache.has(input.data)) { + const expectedValues = util.objectValues(nativeEnumValues); + + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues, + }); + return INVALID; + } + return OK(input.data); + } + + get enum() { + return this._def.values; + } + + static create = (values: Elements, params?: RawCreateParams): ZodNativeEnum => { + return new ZodNativeEnum({ + values: values, + typeName: ZodFirstPartyTypeKind.ZodNativeEnum, + ...processCreateParams(params), + }); + }; +} + +////////////////////////////////////////// +////////////////////////////////////////// +////////// ////////// +////////// ZodPromise ////////// +////////// ////////// +////////////////////////////////////////// +////////////////////////////////////////// +export interface ZodPromiseDef extends ZodTypeDef { + type: T; + typeName: ZodFirstPartyTypeKind.ZodPromise; +} + +export class ZodPromise extends ZodType< + Promise, + ZodPromiseDef, + Promise +> { + unwrap() { + return this._def.type; + } + + _parse(input: ParseInput): ParseReturnType { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.promise, + received: ctx.parsedType, + }); + return INVALID; + } + + const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); + + return OK( + promisified.then((data: any) => { + return this._def.type.parseAsync(data, { + path: ctx.path, + errorMap: ctx.common.contextualErrorMap, + }); + }) + ); + } + + static create = (schema: Inner, params?: RawCreateParams): ZodPromise => { + return new ZodPromise({ + type: schema, + typeName: ZodFirstPartyTypeKind.ZodPromise, + ...processCreateParams(params), + }); + }; +} + +////////////////////////////////////////////// +////////////////////////////////////////////// +////////// ////////// +////////// ZodEffects ////////// +////////// ////////// +////////////////////////////////////////////// +////////////////////////////////////////////// + +export type Refinement = (arg: T, ctx: RefinementCtx) => any; +export type SuperRefinement = (arg: T, ctx: RefinementCtx) => void | Promise; + +export type RefinementEffect = { + type: "refinement"; + refinement: (arg: T, ctx: RefinementCtx) => any; +}; +export type TransformEffect = { + type: "transform"; + transform: (arg: T, ctx: RefinementCtx) => any; +}; +export type PreprocessEffect = { + type: "preprocess"; + transform: (arg: T, ctx: RefinementCtx) => any; +}; +export type Effect = RefinementEffect | TransformEffect | PreprocessEffect; + +export interface ZodEffectsDef extends ZodTypeDef { + schema: T; + typeName: ZodFirstPartyTypeKind.ZodEffects; + effect: Effect; +} + +export class ZodEffects, Input = input> extends ZodType< + Output, + ZodEffectsDef, + Input +> { + innerType() { + return this._def.schema; + } + + sourceType(): T { + return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects + ? (this._def.schema as unknown as ZodEffects).sourceType() + : (this._def.schema as T); + } + + _parse(input: ParseInput): ParseReturnType { + const { status, ctx } = this._processInputParams(input); + + const effect = this._def.effect || null; + + const checkCtx: RefinementCtx = { + addIssue: (arg: IssueData) => { + addIssueToContext(ctx, arg); + if (arg.fatal) { + status.abort(); + } else { + status.dirty(); + } + }, + get path() { + return ctx.path; + }, + }; + + checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); + + if (effect.type === "preprocess") { + const processed = effect.transform(ctx.data, checkCtx); + + if (ctx.common.async) { + return Promise.resolve(processed).then(async (processed) => { + if (status.value === "aborted") return INVALID; + + const result = await this._def.schema._parseAsync({ + data: processed, + path: ctx.path, + parent: ctx, + }); + if (result.status === "aborted") return INVALID; + if (result.status === "dirty") return DIRTY(result.value); + if (status.value === "dirty") return DIRTY(result.value); + return result; + }); + } else { + if (status.value === "aborted") return INVALID; + const result = this._def.schema._parseSync({ + data: processed, + path: ctx.path, + parent: ctx, + }); + if (result.status === "aborted") return INVALID; + if (result.status === "dirty") return DIRTY(result.value); + if (status.value === "dirty") return DIRTY(result.value); + return result; + } + } + if (effect.type === "refinement") { + const executeRefinement = (acc: unknown): any => { + const result = effect.refinement(acc, checkCtx); + if (ctx.common.async) { + return Promise.resolve(result); + } + if (result instanceof Promise) { + throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); + } + return acc; + }; + + if (ctx.common.async === false) { + const inner = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inner.status === "aborted") return INVALID; + if (inner.status === "dirty") status.dirty(); + + // return value is ignored + executeRefinement(inner.value); + return { status: status.value, value: inner.value }; + } else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { + if (inner.status === "aborted") return INVALID; + if (inner.status === "dirty") status.dirty(); + + return executeRefinement(inner.value).then(() => { + return { status: status.value, value: inner.value }; + }); + }); + } + } + + if (effect.type === "transform") { + if (ctx.common.async === false) { + const base = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + + if (!isValid(base)) return INVALID; + + const result = effect.transform(base.value, checkCtx); + if (result instanceof Promise) { + throw new Error( + `Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.` + ); + } + + return { status: status.value, value: result }; + } else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { + if (!isValid(base)) return INVALID; + + return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ + status: status.value, + value: result, + })); + }); + } + } + + util.assertNever(effect); + } + + static create = ( + schema: I, + effect: Effect, + params?: RawCreateParams + ): ZodEffects => { + return new ZodEffects({ + schema, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect, + ...processCreateParams(params), + }); + }; + + static createWithPreprocess = ( + preprocess: (arg: unknown, ctx: RefinementCtx) => unknown, + schema: I, + params?: RawCreateParams + ): ZodEffects => { + return new ZodEffects({ + schema, + effect: { type: "preprocess", transform: preprocess }, + typeName: ZodFirstPartyTypeKind.ZodEffects, + ...processCreateParams(params), + }); + }; +} + +export { ZodEffects as ZodTransformer }; + +/////////////////////////////////////////// +/////////////////////////////////////////// +////////// ////////// +////////// ZodOptional ////////// +////////// ////////// +/////////////////////////////////////////// +/////////////////////////////////////////// +export interface ZodOptionalDef extends ZodTypeDef { + innerType: T; + typeName: ZodFirstPartyTypeKind.ZodOptional; +} + +export type ZodOptionalType = ZodOptional; + +export class ZodOptional extends ZodType< + T["_output"] | undefined, + ZodOptionalDef, + T["_input"] | undefined +> { + _parse(input: ParseInput): ParseReturnType { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType.undefined) { + return OK(undefined); + } + return this._def.innerType._parse(input); + } + + unwrap() { + return this._def.innerType; + } + + static create = (type: Inner, params?: RawCreateParams): ZodOptional => { + return new ZodOptional({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodOptional, + ...processCreateParams(params), + }) as any; + }; +} + +/////////////////////////////////////////// +/////////////////////////////////////////// +////////// ////////// +////////// ZodNullable ////////// +////////// ////////// +/////////////////////////////////////////// +/////////////////////////////////////////// +export interface ZodNullableDef extends ZodTypeDef { + innerType: T; + typeName: ZodFirstPartyTypeKind.ZodNullable; +} + +export type ZodNullableType = ZodNullable; + +export class ZodNullable extends ZodType< + T["_output"] | null, + ZodNullableDef, + T["_input"] | null +> { + _parse(input: ParseInput): ParseReturnType { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType.null) { + return OK(null); + } + return this._def.innerType._parse(input); + } + + unwrap() { + return this._def.innerType; + } + + static create = (type: Inner, params?: RawCreateParams): ZodNullable => { + return new ZodNullable({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodNullable, + ...processCreateParams(params), + }) as any; + }; +} + +//////////////////////////////////////////// +//////////////////////////////////////////// +////////// ////////// +////////// ZodDefault ////////// +////////// ////////// +//////////////////////////////////////////// +//////////////////////////////////////////// +export interface ZodDefaultDef extends ZodTypeDef { + innerType: T; + defaultValue: () => util.noUndefined; + typeName: ZodFirstPartyTypeKind.ZodDefault; +} + +export class ZodDefault extends ZodType< + util.noUndefined, + ZodDefaultDef, + T["_input"] | undefined +> { + _parse(input: ParseInput): ParseReturnType { + const { ctx } = this._processInputParams(input); + let data = ctx.data; + if (ctx.parsedType === ZodParsedType.undefined) { + data = this._def.defaultValue(); + } + return this._def.innerType._parse({ + data, + path: ctx.path, + parent: ctx, + }); + } + + removeDefault() { + return this._def.innerType; + } + + static create = ( + type: Inner, + params: RawCreateParams & { + default: Inner["_input"] | (() => util.noUndefined); + } + ): ZodDefault => { + return new ZodDefault({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodDefault, + defaultValue: typeof params.default === "function" ? params.default : () => params.default as any, + ...processCreateParams(params), + }) as any; + }; +} + +////////////////////////////////////////// +////////////////////////////////////////// +////////// ////////// +////////// ZodCatch ////////// +////////// ////////// +////////////////////////////////////////// +////////////////////////////////////////// +export interface ZodCatchDef extends ZodTypeDef { + innerType: T; + catchValue: (ctx: { error: ZodError; input: unknown }) => T["_input"]; + typeName: ZodFirstPartyTypeKind.ZodCatch; +} + +export class ZodCatch extends ZodType< + T["_output"], + ZodCatchDef, + unknown // any input will pass validation // T["_input"] +> { + _parse(input: ParseInput): ParseReturnType { + const { ctx } = this._processInputParams(input); + + // newCtx is used to not collect issues from inner types in ctx + const newCtx: ParseContext = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + }; + + const result = this._def.innerType._parse({ + data: newCtx.data, + path: newCtx.path, + parent: { + ...newCtx, + }, + }); + + if (isAsync(result)) { + return result.then((result) => { + return { + status: "valid", + value: + result.status === "valid" + ? result.value + : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data, + }), + }; + }); + } else { + return { + status: "valid", + value: + result.status === "valid" + ? result.value + : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data, + }), + }; + } + } + + removeCatch() { + return this._def.innerType; + } + + static create = ( + type: Inner, + params: RawCreateParams & { + catch: Inner["_output"] | (() => Inner["_output"]); + } + ): ZodCatch => { + return new ZodCatch({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodCatch, + catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, + ...processCreateParams(params), + }); + }; +} + +///////////////////////////////////////// +///////////////////////////////////////// +////////// ////////// +////////// ZodNaN ////////// +////////// ////////// +///////////////////////////////////////// +///////////////////////////////////////// + +export interface ZodNaNDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodNaN; +} + +export class ZodNaN extends ZodType { + _parse(input: ParseInput): ParseReturnType { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.nan) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.nan, + received: ctx.parsedType, + }); + return INVALID; + } + + return { status: "valid", value: input.data }; + } + + static create = (params?: RawCreateParams): ZodNaN => { + return new ZodNaN({ + typeName: ZodFirstPartyTypeKind.ZodNaN, + ...processCreateParams(params), + }); + }; +} + +////////////////////////////////////////// +////////////////////////////////////////// +////////// ////////// +////////// ZodBranded ////////// +////////// ////////// +////////////////////////////////////////// +////////////////////////////////////////// + +export interface ZodBrandedDef extends ZodTypeDef { + type: T; + typeName: ZodFirstPartyTypeKind.ZodBranded; +} + +export const BRAND: unique symbol = Symbol("zod_brand"); +export type BRAND = { + [BRAND]: { [k in T]: true }; +}; + +export class ZodBranded extends ZodType< + T["_output"] & BRAND, + ZodBrandedDef, + T["_input"] +> { + _parse(input: ParseInput): ParseReturnType { + const { ctx } = this._processInputParams(input); + const data = ctx.data; + return this._def.type._parse({ + data, + path: ctx.path, + parent: ctx, + }); + } + + unwrap() { + return this._def.type; + } +} + +//////////////////////////////////////////// +//////////////////////////////////////////// +////////// ////////// +////////// ZodPipeline ////////// +////////// ////////// +//////////////////////////////////////////// +//////////////////////////////////////////// + +export interface ZodPipelineDef extends ZodTypeDef { + in: A; + out: B; + typeName: ZodFirstPartyTypeKind.ZodPipeline; +} + +export class ZodPipeline extends ZodType< + B["_output"], + ZodPipelineDef, + A["_input"] +> { + _parse(input: ParseInput): ParseReturnType { + const { status, ctx } = this._processInputParams(input); + if (ctx.common.async) { + const handleAsync = async () => { + const inResult = await this._def.in._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inResult.status === "aborted") return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return DIRTY(inResult.value); + } else { + return this._def.out._parseAsync({ + data: inResult.value, + path: ctx.path, + parent: ctx, + }); + } + }; + return handleAsync(); + } else { + const inResult = this._def.in._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inResult.status === "aborted") return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return { + status: "dirty", + value: inResult.value, + }; + } else { + return this._def.out._parseSync({ + data: inResult.value, + path: ctx.path, + parent: ctx, + }); + } + } + } + + static create( + a: ASchema, + b: BSchema + ): ZodPipeline { + return new ZodPipeline({ + in: a, + out: b, + typeName: ZodFirstPartyTypeKind.ZodPipeline, + }); + } +} + +/////////////////////////////////////////// +/////////////////////////////////////////// +////////// ////////// +////////// ZodReadonly ////////// +////////// ////////// +/////////////////////////////////////////// +/////////////////////////////////////////// +type BuiltIn = + | (((...args: any[]) => any) | (new (...args: any[]) => any)) + | { readonly [Symbol.toStringTag]: string } + | Date + | Error + | Generator + | Promise + | RegExp; + +type MakeReadonly = T extends Map + ? ReadonlyMap + : T extends Set + ? ReadonlySet + : T extends [infer Head, ...infer Tail] + ? readonly [Head, ...Tail] + : T extends Array + ? ReadonlyArray + : T extends BuiltIn + ? T + : Readonly; + +export interface ZodReadonlyDef extends ZodTypeDef { + innerType: T; + typeName: ZodFirstPartyTypeKind.ZodReadonly; +} + +export class ZodReadonly extends ZodType< + MakeReadonly, + ZodReadonlyDef, + MakeReadonly +> { + _parse(input: ParseInput): ParseReturnType { + const result = this._def.innerType._parse(input); + const freeze = (data: ParseReturnType) => { + if (isValid(data)) { + data.value = Object.freeze(data.value); + } + return data; + }; + return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); + } + + static create = (type: Inner, params?: RawCreateParams): ZodReadonly => { + return new ZodReadonly({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodReadonly, + ...processCreateParams(params), + }) as any; + }; + + unwrap() { + return this._def.innerType; + } +} + +//////////////////////////////////////// +//////////////////////////////////////// +////////// ////////// +////////// z.custom ////////// +////////// ////////// +//////////////////////////////////////// +//////////////////////////////////////// +function cleanParams(params: unknown, data: unknown) { + const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; + + const p2 = typeof p === "string" ? { message: p } : p; + return p2; +} +type CustomParams = CustomErrorParams & { fatal?: boolean }; +export function custom( + check?: (data: any) => any, + _params: string | CustomParams | ((input: any) => CustomParams) = {}, + /** + * @deprecated + * + * Pass `fatal` into the params object instead: + * + * ```ts + * z.string().custom((val) => val.length > 5, { fatal: false }) + * ``` + * + */ + fatal?: boolean +): ZodType { + if (check) + return ZodAny.create().superRefine((data, ctx) => { + const r = check(data); + if (r instanceof Promise) { + return r.then((r) => { + if (!r) { + const params = cleanParams(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + }); + } + if (!r) { + const params = cleanParams(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + return; + }); + return ZodAny.create(); +} + +export { ZodType as Schema, ZodType as ZodSchema }; + +export const late = { + object: ZodObject.lazycreate, +}; + +export enum ZodFirstPartyTypeKind { + ZodString = "ZodString", + ZodNumber = "ZodNumber", + ZodNaN = "ZodNaN", + ZodBigInt = "ZodBigInt", + ZodBoolean = "ZodBoolean", + ZodDate = "ZodDate", + ZodSymbol = "ZodSymbol", + ZodUndefined = "ZodUndefined", + ZodNull = "ZodNull", + ZodAny = "ZodAny", + ZodUnknown = "ZodUnknown", + ZodNever = "ZodNever", + ZodVoid = "ZodVoid", + ZodArray = "ZodArray", + ZodObject = "ZodObject", + ZodUnion = "ZodUnion", + ZodDiscriminatedUnion = "ZodDiscriminatedUnion", + ZodIntersection = "ZodIntersection", + ZodTuple = "ZodTuple", + ZodRecord = "ZodRecord", + ZodMap = "ZodMap", + ZodSet = "ZodSet", + ZodFunction = "ZodFunction", + ZodLazy = "ZodLazy", + ZodLiteral = "ZodLiteral", + ZodEnum = "ZodEnum", + ZodEffects = "ZodEffects", + ZodNativeEnum = "ZodNativeEnum", + ZodOptional = "ZodOptional", + ZodNullable = "ZodNullable", + ZodDefault = "ZodDefault", + ZodCatch = "ZodCatch", + ZodPromise = "ZodPromise", + ZodBranded = "ZodBranded", + ZodPipeline = "ZodPipeline", + ZodReadonly = "ZodReadonly", +} +export type ZodFirstPartySchemaTypes = + | ZodString + | ZodNumber + | ZodNaN + | ZodBigInt + | ZodBoolean + | ZodDate + | ZodUndefined + | ZodNull + | ZodAny + | ZodUnknown + | ZodNever + | ZodVoid + | ZodArray + | ZodObject + | ZodUnion + | ZodDiscriminatedUnion + | ZodIntersection + | ZodTuple + | ZodRecord + | ZodMap + | ZodSet + | ZodFunction + | ZodLazy + | ZodLiteral + | ZodEnum + | ZodEffects + | ZodNativeEnum + | ZodOptional + | ZodNullable + | ZodDefault + | ZodCatch + | ZodPromise + | ZodBranded + | ZodPipeline + | ZodReadonly + | ZodSymbol; + +// requires TS 4.4+ +abstract class Class { + constructor(..._: any[]) {} +} +const instanceOfType = ( + // const instanceOfType = any>( + cls: T, + params: CustomParams = { + message: `Input not instance of ${cls.name}`, + } +) => custom>((data) => data instanceof cls, params); + +const stringType = ZodString.create; +const numberType = ZodNumber.create; +const nanType = ZodNaN.create; +const bigIntType = ZodBigInt.create; +const booleanType = ZodBoolean.create; +const dateType = ZodDate.create; +const symbolType = ZodSymbol.create; +const undefinedType = ZodUndefined.create; +const nullType = ZodNull.create; +const anyType = ZodAny.create; +const unknownType = ZodUnknown.create; +const neverType = ZodNever.create; +const voidType = ZodVoid.create; +const arrayType = ZodArray.create; +const objectType = ZodObject.create; +const strictObjectType = ZodObject.strictCreate; +const unionType = ZodUnion.create; +const discriminatedUnionType = ZodDiscriminatedUnion.create; +const intersectionType = ZodIntersection.create; +const tupleType = ZodTuple.create; +const recordType = ZodRecord.create; +const mapType = ZodMap.create; +const setType = ZodSet.create; +const functionType = ZodFunction.create; +const lazyType = ZodLazy.create; +const literalType = ZodLiteral.create; +const enumType = ZodEnum.create; +const nativeEnumType = ZodNativeEnum.create; +const promiseType = ZodPromise.create; +const effectsType = ZodEffects.create; +const optionalType = ZodOptional.create; +const nullableType = ZodNullable.create; +const preprocessType = ZodEffects.createWithPreprocess; +const pipelineType = ZodPipeline.create; +const ostring = () => stringType().optional(); +const onumber = () => numberType().optional(); +const oboolean = () => booleanType().optional(); + +export const coerce = { + string: ((arg) => ZodString.create({ ...arg, coerce: true })) as (typeof ZodString)["create"], + number: ((arg) => ZodNumber.create({ ...arg, coerce: true })) as (typeof ZodNumber)["create"], + boolean: ((arg) => + ZodBoolean.create({ + ...arg, + coerce: true, + })) as (typeof ZodBoolean)["create"], + bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })) as (typeof ZodBigInt)["create"], + date: ((arg) => ZodDate.create({ ...arg, coerce: true })) as (typeof ZodDate)["create"], +}; + +export { + anyType as any, + arrayType as array, + bigIntType as bigint, + booleanType as boolean, + dateType as date, + discriminatedUnionType as discriminatedUnion, + effectsType as effect, + enumType as enum, + functionType as function, + instanceOfType as instanceof, + intersectionType as intersection, + lazyType as lazy, + literalType as literal, + mapType as map, + nanType as nan, + nativeEnumType as nativeEnum, + neverType as never, + nullType as null, + nullableType as nullable, + numberType as number, + objectType as object, + oboolean, + onumber, + optionalType as optional, + ostring, + pipelineType as pipeline, + preprocessType as preprocess, + promiseType as promise, + recordType as record, + setType as set, + strictObjectType as strictObject, + stringType as string, + symbolType as symbol, + effectsType as transformer, + tupleType as tuple, + undefinedType as undefined, + unionType as union, + unknownType as unknown, + voidType as void, +}; + +export const NEVER = INVALID as never; diff --git a/node_modules/zod/src/v4-mini/index.ts b/node_modules/zod/src/v4-mini/index.ts new file mode 100644 index 0000000..87b293a --- /dev/null +++ b/node_modules/zod/src/v4-mini/index.ts @@ -0,0 +1 @@ +export * from "../v4/mini/index.js"; diff --git a/node_modules/zod/src/v4/classic/checks.ts b/node_modules/zod/src/v4/classic/checks.ts new file mode 100644 index 0000000..1846b2b --- /dev/null +++ b/node_modules/zod/src/v4/classic/checks.ts @@ -0,0 +1,30 @@ +export { + _lt as lt, + _lte as lte, + _gt as gt, + _gte as gte, + _positive as positive, + _negative as negative, + _nonpositive as nonpositive, + _nonnegative as nonnegative, + _multipleOf as multipleOf, + _maxSize as maxSize, + _minSize as minSize, + _size as size, + _maxLength as maxLength, + _minLength as minLength, + _length as length, + _regex as regex, + _lowercase as lowercase, + _uppercase as uppercase, + _includes as includes, + _startsWith as startsWith, + _endsWith as endsWith, + _property as property, + _mime as mime, + _overwrite as overwrite, + _normalize as normalize, + _trim as trim, + _toLowerCase as toLowerCase, + _toUpperCase as toUpperCase, +} from "../core/index.js"; diff --git a/node_modules/zod/src/v4/classic/coerce.ts b/node_modules/zod/src/v4/classic/coerce.ts new file mode 100644 index 0000000..cc400e0 --- /dev/null +++ b/node_modules/zod/src/v4/classic/coerce.ts @@ -0,0 +1,27 @@ +import * as core from "../core/index.js"; +import * as schemas from "./schemas.js"; + +export interface ZodCoercedString extends schemas._ZodString> {} +export function string(params?: string | core.$ZodStringParams): ZodCoercedString { + return core._coercedString(schemas.ZodString, params) as any; +} + +export interface ZodCoercedNumber extends schemas._ZodNumber> {} +export function number(params?: string | core.$ZodNumberParams): ZodCoercedNumber { + return core._coercedNumber(schemas.ZodNumber, params) as ZodCoercedNumber; +} + +export interface ZodCoercedBoolean extends schemas._ZodBoolean> {} +export function boolean(params?: string | core.$ZodBooleanParams): ZodCoercedBoolean { + return core._coercedBoolean(schemas.ZodBoolean, params) as ZodCoercedBoolean; +} + +export interface ZodCoercedBigInt extends schemas._ZodBigInt> {} +export function bigint(params?: string | core.$ZodBigIntParams): ZodCoercedBigInt { + return core._coercedBigint(schemas.ZodBigInt, params) as ZodCoercedBigInt; +} + +export interface ZodCoercedDate extends schemas._ZodDate> {} +export function date(params?: string | core.$ZodDateParams): ZodCoercedDate { + return core._coercedDate(schemas.ZodDate, params) as ZodCoercedDate; +} diff --git a/node_modules/zod/src/v4/classic/compat.ts b/node_modules/zod/src/v4/classic/compat.ts new file mode 100644 index 0000000..f24af19 --- /dev/null +++ b/node_modules/zod/src/v4/classic/compat.ts @@ -0,0 +1,66 @@ +// Zod 3 compat layer + +import * as core from "../core/index.js"; +import type { ZodType } from "./schemas.js"; + +export type { + /** @deprecated Use `z.output` instead. */ + output as TypeOf, + /** @deprecated Use `z.output` instead. */ + output as Infer, + /** @deprecated Use `z.core.$$ZodFirstPartyTypes` instead */ + $ZodTypes as ZodFirstPartySchemaTypes, +} from "../core/index.js"; + +/** @deprecated Use the raw string literal codes instead, e.g. "invalid_type". */ +export const ZodIssueCode = { + invalid_type: "invalid_type", + too_big: "too_big", + too_small: "too_small", + invalid_format: "invalid_format", + not_multiple_of: "not_multiple_of", + unrecognized_keys: "unrecognized_keys", + invalid_union: "invalid_union", + invalid_key: "invalid_key", + invalid_element: "invalid_element", + invalid_value: "invalid_value", + custom: "custom", +} as const; + +/** @deprecated Use `z.$ZodFlattenedError` */ +export type inferFlattenedErrors = core.$ZodFlattenedError, U>; + +/** @deprecated Use `z.$ZodFormattedError` */ +export type inferFormattedError, U = string> = core.$ZodFormattedError< + core.output, + U +>; + +/** Use `z.$brand` instead */ +export type BRAND = { + [core.$brand]: { [k in T]: true }; +}; +export { $brand, config } from "../core/index.js"; + +/** @deprecated Use `z.config(params)` instead. */ +export function setErrorMap(map: core.$ZodErrorMap): void { + core.config({ + customError: map, + }); +} + +/** @deprecated Use `z.config()` instead. */ +export function getErrorMap(): core.$ZodErrorMap | undefined { + return core.config().customError; +} + +export type { + /** @deprecated Use z.ZodType (without generics) instead. */ + ZodType as ZodTypeAny, + /** @deprecated Use `z.ZodType` */ + ZodType as ZodSchema, + /** @deprecated Use `z.ZodType` */ + ZodType as Schema, +}; + +export type ZodRawShape = core.$ZodShape; diff --git a/node_modules/zod/src/v4/classic/errors.ts b/node_modules/zod/src/v4/classic/errors.ts new file mode 100644 index 0000000..5ce4305 --- /dev/null +++ b/node_modules/zod/src/v4/classic/errors.ts @@ -0,0 +1,75 @@ +import * as core from "../core/index.js"; +import { $ZodError } from "../core/index.js"; + +/** @deprecated Use `z.core.$ZodIssue` from `@zod/core` instead, especially if you are building a library on top of Zod. */ +export type ZodIssue = core.$ZodIssue; + +/** An Error-like class used to store Zod validation issues. */ +export interface ZodError extends $ZodError { + /** @deprecated Use the `z.treeifyError(err)` function instead. */ + format(): core.$ZodFormattedError; + format(mapper: (issue: core.$ZodIssue) => U): core.$ZodFormattedError; + /** @deprecated Use the `z.treeifyError(err)` function instead. */ + flatten(): core.$ZodFlattenedError; + flatten(mapper: (issue: core.$ZodIssue) => U): core.$ZodFlattenedError; + /** @deprecated Push directly to `.issues` instead. */ + addIssue(issue: core.$ZodIssue): void; + /** @deprecated Push directly to `.issues` instead. */ + addIssues(issues: core.$ZodIssue[]): void; + + /** @deprecated Check `err.issues.length === 0` instead. */ + isEmpty: boolean; +} + +const initializer = (inst: ZodError, issues: core.$ZodIssue[]) => { + $ZodError.init(inst, issues); + inst.name = "ZodError"; + Object.defineProperties(inst, { + format: { + value: (mapper: any) => core.formatError(inst, mapper), + // enumerable: false, + }, + flatten: { + value: (mapper: any) => core.flattenError(inst, mapper), + // enumerable: false, + }, + addIssue: { + value: (issue: any) => inst.issues.push(issue), + // enumerable: false, + }, + addIssues: { + value: (issues: any) => inst.issues.push(...issues), + // enumerable: false, + }, + isEmpty: { + get() { + return inst.issues.length === 0; + }, + // enumerable: false, + }, + }); + // Object.defineProperty(inst, "isEmpty", { + // get() { + // return inst.issues.length === 0; + // }, + // }); +}; +export const ZodError: core.$constructor = core.$constructor("ZodError", initializer); +export const ZodRealError: core.$constructor = core.$constructor("ZodError", initializer, { + Parent: Error, +}); + +export type { + /** @deprecated Use `z.core.$ZodFlattenedError` instead. */ + $ZodFlattenedError as ZodFlattenedError, + /** @deprecated Use `z.core.$ZodFormattedError` instead. */ + $ZodFormattedError as ZodFormattedError, + /** @deprecated Use `z.core.$ZodErrorMap` instead. */ + $ZodErrorMap as ZodErrorMap, +} from "../core/index.js"; + +/** @deprecated Use `z.core.$ZodRawIssue` instead. */ +export type IssueData = core.$ZodRawIssue; + +// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */ +// export type ErrorMapCtx = core.$ZodErrorMapCtx; diff --git a/node_modules/zod/src/v4/classic/external.ts b/node_modules/zod/src/v4/classic/external.ts new file mode 100644 index 0000000..855f5a7 --- /dev/null +++ b/node_modules/zod/src/v4/classic/external.ts @@ -0,0 +1,50 @@ +export * as core from "../core/index.js"; +export * from "./schemas.js"; +export * from "./checks.js"; +export * from "./errors.js"; +export * from "./parse.js"; +export * from "./compat.js"; + +// zod-specified +import { config } from "../core/index.js"; +import en from "../locales/en.js"; +config(en()); + +export type { infer, output, input } from "../core/index.js"; +export { + globalRegistry, + type GlobalMeta, + registry, + config, + function, + $output, + $input, + $brand, + clone, + regexes, + treeifyError, + prettifyError, + formatError, + flattenError, + toJSONSchema, + TimePrecision, + NEVER, +} from "../core/index.js"; + +export * as locales from "../locales/index.js"; + +// iso +// must be exported from top-level +// https://github.com/colinhacks/zod/issues/4491 +export { ZodISODateTime, ZodISODate, ZodISOTime, ZodISODuration } from "./iso.js"; +export * as iso from "./iso.js"; + +// coerce +export type { + ZodCoercedString, + ZodCoercedNumber, + ZodCoercedBigInt, + ZodCoercedBoolean, + ZodCoercedDate, +} from "./coerce.js"; +export * as coerce from "./coerce.js"; diff --git a/node_modules/zod/src/v4/classic/index.ts b/node_modules/zod/src/v4/classic/index.ts new file mode 100644 index 0000000..f0f7547 --- /dev/null +++ b/node_modules/zod/src/v4/classic/index.ts @@ -0,0 +1,5 @@ +import * as z from "./external.js"; + +export { z }; +export * from "./external.js"; +export default z; diff --git a/node_modules/zod/src/v4/classic/iso.ts b/node_modules/zod/src/v4/classic/iso.ts new file mode 100644 index 0000000..b08696d --- /dev/null +++ b/node_modules/zod/src/v4/classic/iso.ts @@ -0,0 +1,90 @@ +import * as core from "../core/index.js"; +import * as schemas from "./schemas.js"; + +////////////////////////////////////////////// +////////////////////////////////////////////// +////////// ////////// +////////// ZodISODateTime ////////// +////////// ////////// +////////////////////////////////////////////// +////////////////////////////////////////////// + +export interface ZodISODateTime extends schemas.ZodStringFormat { + _zod: core.$ZodISODateTimeInternals; +} +export const ZodISODateTime: core.$constructor = /*@__PURE__*/ core.$constructor( + "ZodISODateTime", + (inst, def) => { + core.$ZodISODateTime.init(inst, def); + schemas.ZodStringFormat.init(inst, def); + } +); + +export function datetime(params?: string | core.$ZodISODateTimeParams): ZodISODateTime { + return core._isoDateTime(ZodISODateTime, params); +} + +////////////////////////////////////////// +////////////////////////////////////////// +////////// ////////// +////////// ZodISODate ////////// +////////// ////////// +////////////////////////////////////////// +////////////////////////////////////////// + +export interface ZodISODate extends schemas.ZodStringFormat { + _zod: core.$ZodISODateInternals; +} +export const ZodISODate: core.$constructor = /*@__PURE__*/ core.$constructor("ZodISODate", (inst, def) => { + core.$ZodISODate.init(inst, def); + schemas.ZodStringFormat.init(inst, def); +}); + +export function date(params?: string | core.$ZodISODateParams): ZodISODate { + return core._isoDate(ZodISODate, params); +} + +// ZodISOTime + +////////////////////////////////////////// +////////////////////////////////////////// +////////// ////////// +////////// ZodISOTime ////////// +////////// ////////// +////////////////////////////////////////// +////////////////////////////////////////// + +export interface ZodISOTime extends schemas.ZodStringFormat { + _zod: core.$ZodISOTimeInternals; +} +export const ZodISOTime: core.$constructor = /*@__PURE__*/ core.$constructor("ZodISOTime", (inst, def) => { + core.$ZodISOTime.init(inst, def); + schemas.ZodStringFormat.init(inst, def); +}); + +export function time(params?: string | core.$ZodISOTimeParams): ZodISOTime { + return core._isoTime(ZodISOTime, params); +} + +////////////////////////////////////////////// +////////////////////////////////////////////// +////////// ////////// +////////// ZodISODuration ////////// +////////// ////////// +////////////////////////////////////////////// +////////////////////////////////////////////// + +export interface ZodISODuration extends schemas.ZodStringFormat { + _zod: core.$ZodISODurationInternals; +} +export const ZodISODuration: core.$constructor = /*@__PURE__*/ core.$constructor( + "ZodISODuration", + (inst, def) => { + core.$ZodISODuration.init(inst, def); + schemas.ZodStringFormat.init(inst, def); + } +); + +export function duration(params?: string | core.$ZodISODurationParams): ZodISODuration { + return core._isoDuration(ZodISODuration, params); +} diff --git a/node_modules/zod/src/v4/classic/parse.ts b/node_modules/zod/src/v4/classic/parse.ts new file mode 100644 index 0000000..0d77e20 --- /dev/null +++ b/node_modules/zod/src/v4/classic/parse.ts @@ -0,0 +1,33 @@ +import * as core from "../core/index.js"; +import { type ZodError, ZodRealError } from "./errors.js"; + +export type ZodSafeParseResult = ZodSafeParseSuccess | ZodSafeParseError; +export type ZodSafeParseSuccess = { success: true; data: T; error?: never }; +export type ZodSafeParseError = { success: false; data?: never; error: ZodError }; + +export const parse: ( + schema: T, + value: unknown, + _ctx?: core.ParseContext, + _params?: { callee?: core.util.AnyFunc; Err?: core.$ZodErrorClass } +) => core.output = /* @__PURE__ */ core._parse(ZodRealError) as any; + +export const parseAsync: ( + schema: T, + value: unknown, + _ctx?: core.ParseContext, + _params?: { callee?: core.util.AnyFunc; Err?: core.$ZodErrorClass } +) => Promise> = /* @__PURE__ */ core._parseAsync(ZodRealError) as any; + +export const safeParse: ( + schema: T, + value: unknown, + _ctx?: core.ParseContext + // _params?: { callee?: core.util.AnyFunc; Err?: core.$ZodErrorClass } +) => ZodSafeParseResult> = /* @__PURE__ */ core._safeParse(ZodRealError) as any; + +export const safeParseAsync: ( + schema: T, + value: unknown, + _ctx?: core.ParseContext +) => Promise>> = /* @__PURE__ */ core._safeParseAsync(ZodRealError) as any; diff --git a/node_modules/zod/src/v4/classic/schemas.ts b/node_modules/zod/src/v4/classic/schemas.ts new file mode 100644 index 0000000..3d09cb6 --- /dev/null +++ b/node_modules/zod/src/v4/classic/schemas.ts @@ -0,0 +1,2054 @@ +import * as core from "../core/index.js"; +import { util } from "../core/index.js"; + +import * as checks from "./checks.js"; +import * as iso from "./iso.js"; +import * as parse from "./parse.js"; + +/////////////////////////////////////////// +/////////////////////////////////////////// +//////////// //////////// +//////////// ZodType //////////// +//////////// //////////// +/////////////////////////////////////////// +/////////////////////////////////////////// + +export interface RefinementCtx extends core.ParsePayload { + addIssue(arg: string | core.$ZodRawIssue | Partial): void; +} + +export interface ZodType< + out Output = unknown, + out Input = unknown, + out Internals extends core.$ZodTypeInternals = core.$ZodTypeInternals, +> extends core.$ZodType { + def: Internals["def"]; + type: Internals["def"]["type"]; + + /** @deprecated Use `.def` instead. */ + _def: Internals["def"]; + /** @deprecated Use `z.output` instead. */ + _output: Internals["output"]; + /** @deprecated Use `z.input` instead. */ + _input: Internals["input"]; + + // base methods + check(...checks: (core.CheckFn> | core.$ZodCheck>)[]): this; + clone(def?: Internals["def"], params?: { parent: boolean }): this; + register( + registry: R, + ...meta: this extends R["_schema"] + ? undefined extends R["_meta"] + ? [core.$replace?] + : [core.$replace] + : ["Incompatible schema"] + ): this; + + brand(value?: T): PropertyKey extends T ? this : core.$ZodBranded; + + // parsing + parse(data: unknown, params?: core.ParseContext): core.output; + safeParse(data: unknown, params?: core.ParseContext): parse.ZodSafeParseResult>; + parseAsync(data: unknown, params?: core.ParseContext): Promise>; + safeParseAsync( + data: unknown, + params?: core.ParseContext + ): Promise>>; + spa: ( + data: unknown, + params?: core.ParseContext + ) => Promise>>; + + // refinements + refine(check: (arg: core.output) => unknown | Promise, params?: string | core.$ZodCustomParams): this; + /** @deprecated Use `.check()` instead. */ + superRefine( + refinement: (arg: core.output, ctx: RefinementCtx>) => void | Promise + ): this; + overwrite(fn: (x: core.output) => core.output): this; + + // wrappers + optional(): ZodOptional; + nonoptional(params?: string | core.$ZodNonOptionalParams): ZodNonOptional; + nullable(): ZodNullable; + nullish(): ZodOptional>; + default(def: core.output): ZodDefault; + default(def: () => util.NoUndefined>): ZodDefault; + prefault(def: () => core.input): ZodPrefault; + prefault(def: core.input): ZodPrefault; + array(): ZodArray; + or(option: T): ZodUnion<[this, T]>; + and(incoming: T): ZodIntersection; + transform( + transform: (arg: core.output, ctx: RefinementCtx>) => NewOut | Promise + ): ZodPipe, core.output>>; + catch(def: core.output): ZodCatch; + catch(def: (ctx: core.$ZodCatchCtx) => core.output): ZodCatch; + pipe>>( + target: T | core.$ZodType> + ): ZodPipe; + readonly(): ZodReadonly; + + /** Returns a new instance that has been registered in `z.globalRegistry` with the specified description */ + describe(description: string): this; + description?: string; + /** Returns the metadata associated with this instance in `z.globalRegistry` */ + meta(): core.$replace | undefined; + /** Returns a new instance that has been registered in `z.globalRegistry` with the specified metadata */ + meta(data: core.$replace): this; + + // helpers + /** @deprecated Try safe-parsing `undefined` (this is what `isOptional` does internally): + * + * ```ts + * const schema = z.string().optional(); + * const isOptional = schema.safeParse(undefined).success; // true + * ``` + */ + isOptional(): boolean; + /** + * @deprecated Try safe-parsing `null` (this is what `isNullable` does internally): + * + * ```ts + * const schema = z.string().nullable(); + * const isNullable = schema.safeParse(null).success; // true + * ``` + */ + isNullable(): boolean; +} + +export interface _ZodType + extends ZodType {} + +export const ZodType: core.$constructor = /*@__PURE__*/ core.$constructor("ZodType", (inst, def) => { + core.$ZodType.init(inst, def); + inst.def = def; + Object.defineProperty(inst, "_def", { value: def }); + + // base methods + inst.check = (...checks) => { + return inst.clone( + { + ...def, + checks: [ + ...(def.checks ?? []), + ...checks.map((ch) => + typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch + ), + ], + } + // { parent: true } + ); + }; + inst.clone = (def, params) => core.clone(inst, def, params); + inst.brand = () => inst as any; + inst.register = ((reg: any, meta: any) => { + reg.add(inst, meta); + return inst; + }) as any; + + // parsing + inst.parse = (data, params) => parse.parse(inst, data, params, { callee: inst.parse }); + inst.safeParse = (data, params) => parse.safeParse(inst, data, params); + inst.parseAsync = async (data, params) => parse.parseAsync(inst, data, params, { callee: inst.parseAsync }); + inst.safeParseAsync = async (data, params) => parse.safeParseAsync(inst, data, params); + inst.spa = inst.safeParseAsync; + + // refinements + inst.refine = (check, params) => inst.check(refine(check, params)); + inst.superRefine = (refinement) => inst.check(superRefine(refinement)); + inst.overwrite = (fn) => inst.check(checks.overwrite(fn)); + + // wrappers + inst.optional = () => optional(inst); + inst.nullable = () => nullable(inst); + inst.nullish = () => optional(nullable(inst)); + inst.nonoptional = (params) => nonoptional(inst, params); + inst.array = () => array(inst); + inst.or = (arg) => union([inst, arg]); + inst.and = (arg) => intersection(inst, arg); + inst.transform = (tx) => pipe(inst, transform(tx as any)) as never; + inst.default = (def) => _default(inst, def); + inst.prefault = (def) => prefault(inst, def); + // inst.coalesce = (def, params) => coalesce(inst, def, params); + inst.catch = (params) => _catch(inst, params); + inst.pipe = (target) => pipe(inst, target); + inst.readonly = () => readonly(inst); + + // meta + inst.describe = (description) => { + const cl = inst.clone(); + core.globalRegistry.add(cl, { description }); + return cl; + }; + Object.defineProperty(inst, "description", { + get() { + return core.globalRegistry.get(inst)?.description; + }, + configurable: true, + }); + inst.meta = (...args: any) => { + if (args.length === 0) { + return core.globalRegistry.get(inst); + } + const cl = inst.clone(); + core.globalRegistry.add(cl, args[0]); + return cl as any; + }; + + // helpers + inst.isOptional = () => inst.safeParse(undefined).success; + inst.isNullable = () => inst.safeParse(null).success; + return inst; +}); + +// ZodString +export interface _ZodString = core.$ZodStringInternals> + extends _ZodType { + format: string | null; + minLength: number | null; + maxLength: number | null; + + // miscellaneous checks + regex(regex: RegExp, params?: string | core.$ZodCheckRegexParams): this; + includes(value: string, params?: core.$ZodCheckIncludesParams): this; + startsWith(value: string, params?: string | core.$ZodCheckStartsWithParams): this; + endsWith(value: string, params?: string | core.$ZodCheckEndsWithParams): this; + min(minLength: number, params?: string | core.$ZodCheckMinLengthParams): this; + max(maxLength: number, params?: string | core.$ZodCheckMaxLengthParams): this; + length(len: number, params?: string | core.$ZodCheckLengthEqualsParams): this; + nonempty(params?: string | core.$ZodCheckMinLengthParams): this; + lowercase(params?: string | core.$ZodCheckLowerCaseParams): this; + uppercase(params?: string | core.$ZodCheckUpperCaseParams): this; + + // transforms + trim(): this; + normalize(form?: "NFC" | "NFD" | "NFKC" | "NFKD" | (string & {})): this; + toLowerCase(): this; + toUpperCase(): this; +} + +/** @internal */ +export const _ZodString: core.$constructor<_ZodString> = /*@__PURE__*/ core.$constructor("_ZodString", (inst, def) => { + core.$ZodString.init(inst, def); + ZodType.init(inst, def); + + const bag = inst._zod.bag; + inst.format = bag.format ?? null; + inst.minLength = bag.minimum ?? null; + inst.maxLength = bag.maximum ?? null; + + // validations + inst.regex = (...args) => inst.check(checks.regex(...args)); + inst.includes = (...args) => inst.check(checks.includes(...args)); + inst.startsWith = (...args) => inst.check(checks.startsWith(...args)); + inst.endsWith = (...args) => inst.check(checks.endsWith(...args)); + inst.min = (...args) => inst.check(checks.minLength(...args)); + inst.max = (...args) => inst.check(checks.maxLength(...args)); + inst.length = (...args) => inst.check(checks.length(...args)); + inst.nonempty = (...args) => inst.check(checks.minLength(1, ...args)); + inst.lowercase = (params) => inst.check(checks.lowercase(params)); + inst.uppercase = (params) => inst.check(checks.uppercase(params)); + + // transforms + inst.trim = () => inst.check(checks.trim()); + inst.normalize = (...args) => inst.check(checks.normalize(...args)); + inst.toLowerCase = () => inst.check(checks.toLowerCase()); + inst.toUpperCase = () => inst.check(checks.toUpperCase()); +}); + +export interface ZodString extends _ZodString> { + // string format checks + + /** @deprecated Use `z.email()` instead. */ + email(params?: string | core.$ZodCheckEmailParams): this; + /** @deprecated Use `z.url()` instead. */ + url(params?: string | core.$ZodCheckURLParams): this; + /** @deprecated Use `z.jwt()` instead. */ + jwt(params?: string | core.$ZodCheckJWTParams): this; + /** @deprecated Use `z.emoji()` instead. */ + emoji(params?: string | core.$ZodCheckEmojiParams): this; + /** @deprecated Use `z.guid()` instead. */ + guid(params?: string | core.$ZodCheckGUIDParams): this; + /** @deprecated Use `z.uuid()` instead. */ + uuid(params?: string | core.$ZodCheckUUIDParams): this; + /** @deprecated Use `z.uuid()` instead. */ + uuidv4(params?: string | core.$ZodCheckUUIDParams): this; + /** @deprecated Use `z.uuid()` instead. */ + uuidv6(params?: string | core.$ZodCheckUUIDParams): this; + /** @deprecated Use `z.uuid()` instead. */ + uuidv7(params?: string | core.$ZodCheckUUIDParams): this; + /** @deprecated Use `z.nanoid()` instead. */ + nanoid(params?: string | core.$ZodCheckNanoIDParams): this; + /** @deprecated Use `z.guid()` instead. */ + guid(params?: string | core.$ZodCheckGUIDParams): this; + /** @deprecated Use `z.cuid()` instead. */ + cuid(params?: string | core.$ZodCheckCUIDParams): this; + /** @deprecated Use `z.cuid2()` instead. */ + cuid2(params?: string | core.$ZodCheckCUID2Params): this; + /** @deprecated Use `z.ulid()` instead. */ + ulid(params?: string | core.$ZodCheckULIDParams): this; + /** @deprecated Use `z.base64()` instead. */ + base64(params?: string | core.$ZodCheckBase64Params): this; + /** @deprecated Use `z.base64url()` instead. */ + base64url(params?: string | core.$ZodCheckBase64URLParams): this; + // /** @deprecated Use `z.jsonString()` instead. */ + // jsonString(params?: string | core.$ZodCheckJSONStringParams): this; + /** @deprecated Use `z.xid()` instead. */ + xid(params?: string | core.$ZodCheckXIDParams): this; + /** @deprecated Use `z.ksuid()` instead. */ + ksuid(params?: string | core.$ZodCheckKSUIDParams): this; + // /** @deprecated Use `z.ipv4()` or `z.ipv6()` instead. */ + // ip(params?: string | (core.$ZodCheckIPv4Params & { version?: "v4" | "v6" })): ZodUnion<[this, this]>; + /** @deprecated Use `z.ipv4()` instead. */ + ipv4(params?: string | core.$ZodCheckIPv4Params): this; + /** @deprecated Use `z.ipv6()` instead. */ + ipv6(params?: string | core.$ZodCheckIPv6Params): this; + /** @deprecated Use `z.cidrv4()` instead. */ + cidrv4(params?: string | core.$ZodCheckCIDRv4Params): this; + /** @deprecated Use `z.cidrv6()` instead. */ + cidrv6(params?: string | core.$ZodCheckCIDRv6Params): this; + /** @deprecated Use `z.e164()` instead. */ + e164(params?: string | core.$ZodCheckE164Params): this; + + // ISO 8601 checks + /** @deprecated Use `z.iso.datetime()` instead. */ + datetime(params?: string | core.$ZodCheckISODateTimeParams): this; + /** @deprecated Use `z.iso.date()` instead. */ + date(params?: string | core.$ZodCheckISODateParams): this; + /** @deprecated Use `z.iso.time()` instead. */ + time( + params?: + | string + // | { + // message?: string | undefined; + // precision?: number | null; + // } + | core.$ZodCheckISOTimeParams + ): this; + /** @deprecated Use `z.iso.duration()` instead. */ + duration(params?: string | core.$ZodCheckISODurationParams): this; +} + +export const ZodString: core.$constructor = /*@__PURE__*/ core.$constructor("ZodString", (inst, def) => { + core.$ZodString.init(inst, def); + _ZodString.init(inst, def); + + inst.email = (params) => inst.check(core._email(ZodEmail, params)); + inst.url = (params) => inst.check(core._url(ZodURL, params)); + inst.jwt = (params) => inst.check(core._jwt(ZodJWT, params)); + inst.emoji = (params) => inst.check(core._emoji(ZodEmoji, params)); + inst.guid = (params) => inst.check(core._guid(ZodGUID, params)); + inst.uuid = (params) => inst.check(core._uuid(ZodUUID, params)); + inst.uuidv4 = (params) => inst.check(core._uuidv4(ZodUUID, params)); + inst.uuidv6 = (params) => inst.check(core._uuidv6(ZodUUID, params)); + inst.uuidv7 = (params) => inst.check(core._uuidv7(ZodUUID, params)); + inst.nanoid = (params) => inst.check(core._nanoid(ZodNanoID, params)); + inst.guid = (params) => inst.check(core._guid(ZodGUID, params)); + inst.cuid = (params) => inst.check(core._cuid(ZodCUID, params)); + inst.cuid2 = (params) => inst.check(core._cuid2(ZodCUID2, params)); + inst.ulid = (params) => inst.check(core._ulid(ZodULID, params)); + inst.base64 = (params) => inst.check(core._base64(ZodBase64, params)); + inst.base64url = (params) => inst.check(core._base64url(ZodBase64URL, params)); + inst.xid = (params) => inst.check(core._xid(ZodXID, params)); + inst.ksuid = (params) => inst.check(core._ksuid(ZodKSUID, params)); + inst.ipv4 = (params) => inst.check(core._ipv4(ZodIPv4, params)); + inst.ipv6 = (params) => inst.check(core._ipv6(ZodIPv6, params)); + inst.cidrv4 = (params) => inst.check(core._cidrv4(ZodCIDRv4, params)); + inst.cidrv6 = (params) => inst.check(core._cidrv6(ZodCIDRv6, params)); + inst.e164 = (params) => inst.check(core._e164(ZodE164, params)); + + // iso + inst.datetime = (params) => inst.check(iso.datetime(params as any)); + inst.date = (params) => inst.check(iso.date(params as any)); + inst.time = (params) => inst.check(iso.time(params as any)); + inst.duration = (params) => inst.check(iso.duration(params as any)); +}); + +export function string(params?: string | core.$ZodStringParams): ZodString; +export function string(params?: string | core.$ZodStringParams): core.$ZodType; +export function string(params?: string | core.$ZodStringParams): ZodString { + return core._string(ZodString, params) as any; +} + +// ZodStringFormat +export interface ZodStringFormat + extends _ZodString> {} +export const ZodStringFormat: core.$constructor = /*@__PURE__*/ core.$constructor( + "ZodStringFormat", + (inst, def) => { + core.$ZodStringFormat.init(inst, def); + _ZodString.init(inst, def); + } +); + +// ZodEmail +export interface ZodEmail extends ZodStringFormat<"email"> { + _zod: core.$ZodEmailInternals; +} +export const ZodEmail: core.$constructor = /*@__PURE__*/ core.$constructor("ZodEmail", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodEmail.init(inst, def); + ZodStringFormat.init(inst, def); +}); + +export function email(params?: string | core.$ZodEmailParams): ZodEmail { + return core._email(ZodEmail, params); +} + +// ZodGUID +export interface ZodGUID extends ZodStringFormat<"guid"> { + _zod: core.$ZodGUIDInternals; +} +export const ZodGUID: core.$constructor = /*@__PURE__*/ core.$constructor("ZodGUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodGUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); + +export function guid(params?: string | core.$ZodGUIDParams): ZodGUID { + return core._guid(ZodGUID, params); +} + +// ZodUUID +export interface ZodUUID extends ZodStringFormat<"uuid"> { + _zod: core.$ZodUUIDInternals; +} +export const ZodUUID: core.$constructor = /*@__PURE__*/ core.$constructor("ZodUUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodUUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); + +export function uuid(params?: string | core.$ZodUUIDParams): ZodUUID { + return core._uuid(ZodUUID, params); +} + +export function uuidv4(params?: string | core.$ZodUUIDv4Params): ZodUUID { + return core._uuidv4(ZodUUID, params); +} + +// ZodUUIDv6 + +export function uuidv6(params?: string | core.$ZodUUIDv6Params): ZodUUID { + return core._uuidv6(ZodUUID, params); +} + +// ZodUUIDv7 + +export function uuidv7(params?: string | core.$ZodUUIDv7Params): ZodUUID { + return core._uuidv7(ZodUUID, params); +} + +// ZodURL +export interface ZodURL extends ZodStringFormat<"url"> { + _zod: core.$ZodURLInternals; +} +export const ZodURL: core.$constructor = /*@__PURE__*/ core.$constructor("ZodURL", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodURL.init(inst, def); + ZodStringFormat.init(inst, def); +}); + +export function url(params?: string | core.$ZodURLParams): ZodURL { + return core._url(ZodURL, params); +} + +// ZodEmoji +export interface ZodEmoji extends ZodStringFormat<"emoji"> { + _zod: core.$ZodEmojiInternals; +} +export const ZodEmoji: core.$constructor = /*@__PURE__*/ core.$constructor("ZodEmoji", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodEmoji.init(inst, def); + ZodStringFormat.init(inst, def); +}); + +export function emoji(params?: string | core.$ZodEmojiParams): ZodEmoji { + return core._emoji(ZodEmoji, params); +} + +// ZodNanoID +export interface ZodNanoID extends ZodStringFormat<"nanoid"> { + _zod: core.$ZodNanoIDInternals; +} +export const ZodNanoID: core.$constructor = /*@__PURE__*/ core.$constructor("ZodNanoID", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodNanoID.init(inst, def); + ZodStringFormat.init(inst, def); +}); + +export function nanoid(params?: string | core.$ZodNanoIDParams): ZodNanoID { + return core._nanoid(ZodNanoID, params); +} + +// ZodCUID +export interface ZodCUID extends ZodStringFormat<"cuid"> { + _zod: core.$ZodCUIDInternals; +} +export const ZodCUID: core.$constructor = /*@__PURE__*/ core.$constructor("ZodCUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodCUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); + +export function cuid(params?: string | core.$ZodCUIDParams): ZodCUID { + return core._cuid(ZodCUID, params); +} + +// ZodCUID2 +export interface ZodCUID2 extends ZodStringFormat<"cuid2"> { + _zod: core.$ZodCUID2Internals; +} +export const ZodCUID2: core.$constructor = /*@__PURE__*/ core.$constructor("ZodCUID2", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodCUID2.init(inst, def); + ZodStringFormat.init(inst, def); +}); + +export function cuid2(params?: string | core.$ZodCUID2Params): ZodCUID2 { + return core._cuid2(ZodCUID2, params); +} + +// ZodULID +export interface ZodULID extends ZodStringFormat<"ulid"> { + _zod: core.$ZodULIDInternals; +} +export const ZodULID: core.$constructor = /*@__PURE__*/ core.$constructor("ZodULID", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodULID.init(inst, def); + ZodStringFormat.init(inst, def); +}); + +export function ulid(params?: string | core.$ZodULIDParams): ZodULID { + return core._ulid(ZodULID, params); +} + +// ZodXID +export interface ZodXID extends ZodStringFormat<"xid"> { + _zod: core.$ZodXIDInternals; +} +export const ZodXID: core.$constructor = /*@__PURE__*/ core.$constructor("ZodXID", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodXID.init(inst, def); + ZodStringFormat.init(inst, def); +}); + +export function xid(params?: string | core.$ZodXIDParams): ZodXID { + return core._xid(ZodXID, params); +} + +// ZodKSUID +export interface ZodKSUID extends ZodStringFormat<"ksuid"> { + _zod: core.$ZodKSUIDInternals; +} +export const ZodKSUID: core.$constructor = /*@__PURE__*/ core.$constructor("ZodKSUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodKSUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); + +export function ksuid(params?: string | core.$ZodKSUIDParams): ZodKSUID { + return core._ksuid(ZodKSUID, params); +} + +// ZodIP +// export interface ZodIP extends ZodStringFormat<"ip"> { +// _zod: core.$ZodIPInternals; +// } +// export const ZodIP: core.$constructor = /*@__PURE__*/ core.$constructor("ZodIP", (inst, def) => { +// // ZodStringFormat.init(inst, def); +// core.$ZodIP.init(inst, def); +// ZodStringFormat.init(inst, def); +// }); + +// export function ip(params?: string | core.$ZodIPParams): ZodIP { +// return core._ip(ZodIP, params); +// } + +// ZodIPv4 +export interface ZodIPv4 extends ZodStringFormat<"ipv4"> { + _zod: core.$ZodIPv4Internals; +} +export const ZodIPv4: core.$constructor = /*@__PURE__*/ core.$constructor("ZodIPv4", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodIPv4.init(inst, def); + ZodStringFormat.init(inst, def); +}); + +export function ipv4(params?: string | core.$ZodIPv4Params): ZodIPv4 { + return core._ipv4(ZodIPv4, params); +} + +// ZodIPv6 +export interface ZodIPv6 extends ZodStringFormat<"ipv6"> { + _zod: core.$ZodIPv6Internals; +} +export const ZodIPv6: core.$constructor = /*@__PURE__*/ core.$constructor("ZodIPv6", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodIPv6.init(inst, def); + ZodStringFormat.init(inst, def); +}); +export function ipv6(params?: string | core.$ZodIPv6Params): ZodIPv6 { + return core._ipv6(ZodIPv6, params); +} + +// ZodCIDRv4 +export interface ZodCIDRv4 extends ZodStringFormat<"cidrv4"> { + _zod: core.$ZodCIDRv4Internals; +} +export const ZodCIDRv4: core.$constructor = /*@__PURE__*/ core.$constructor("ZodCIDRv4", (inst, def) => { + core.$ZodCIDRv4.init(inst, def); + ZodStringFormat.init(inst, def); +}); + +export function cidrv4(params?: string | core.$ZodCIDRv4Params): ZodCIDRv4 { + return core._cidrv4(ZodCIDRv4, params); +} + +// ZodCIDRv6 +export interface ZodCIDRv6 extends ZodStringFormat<"cidrv6"> { + _zod: core.$ZodCIDRv6Internals; +} +export const ZodCIDRv6: core.$constructor = /*@__PURE__*/ core.$constructor("ZodCIDRv6", (inst, def) => { + core.$ZodCIDRv6.init(inst, def); + ZodStringFormat.init(inst, def); +}); + +export function cidrv6(params?: string | core.$ZodCIDRv6Params): ZodCIDRv6 { + return core._cidrv6(ZodCIDRv6, params); +} + +// ZodBase64 +export interface ZodBase64 extends ZodStringFormat<"base64"> { + _zod: core.$ZodBase64Internals; +} +export const ZodBase64: core.$constructor = /*@__PURE__*/ core.$constructor("ZodBase64", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodBase64.init(inst, def); + ZodStringFormat.init(inst, def); +}); +export function base64(params?: string | core.$ZodBase64Params): ZodBase64 { + return core._base64(ZodBase64, params); +} + +// ZodBase64URL +export interface ZodBase64URL extends ZodStringFormat<"base64url"> { + _zod: core.$ZodBase64URLInternals; +} +export const ZodBase64URL: core.$constructor = /*@__PURE__*/ core.$constructor( + "ZodBase64URL", + (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodBase64URL.init(inst, def); + ZodStringFormat.init(inst, def); + } +); +export function base64url(params?: string | core.$ZodBase64URLParams): ZodBase64URL { + return core._base64url(ZodBase64URL, params); +} + +// ZodE164 +export interface ZodE164 extends ZodStringFormat<"e164"> { + _zod: core.$ZodE164Internals; +} +export const ZodE164: core.$constructor = /*@__PURE__*/ core.$constructor("ZodE164", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodE164.init(inst, def); + ZodStringFormat.init(inst, def); +}); + +export function e164(params?: string | core.$ZodE164Params): ZodE164 { + return core._e164(ZodE164, params); +} + +// ZodJWT +export interface ZodJWT extends ZodStringFormat<"jwt"> { + _zod: core.$ZodJWTInternals; +} +export const ZodJWT: core.$constructor = /*@__PURE__*/ core.$constructor("ZodJWT", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodJWT.init(inst, def); + ZodStringFormat.init(inst, def); +}); + +export function jwt(params?: string | core.$ZodJWTParams): ZodJWT { + return core._jwt(ZodJWT, params); +} + +// ZodCustomStringFormat +export interface ZodCustomStringFormat + extends ZodStringFormat, + core.$ZodCustomStringFormat { + _zod: core.$ZodCustomStringFormatInternals; +} +export const ZodCustomStringFormat: core.$constructor = /*@__PURE__*/ core.$constructor( + "ZodCustomStringFormat", + (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodCustomStringFormat.init(inst, def); + ZodStringFormat.init(inst, def); + } +); +export function stringFormat( + format: Format, + fnOrRegex: ((arg: string) => util.MaybeAsync) | RegExp, + _params: string | core.$ZodStringFormatParams = {} +): ZodCustomStringFormat { + return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params) as any; +} + +// ZodNumber +export interface _ZodNumber + extends _ZodType { + gt(value: number, params?: string | core.$ZodCheckGreaterThanParams): this; + /** Identical to .min() */ + gte(value: number, params?: string | core.$ZodCheckGreaterThanParams): this; + min(value: number, params?: string | core.$ZodCheckGreaterThanParams): this; + lt(value: number, params?: string | core.$ZodCheckLessThanParams): this; + /** Identical to .max() */ + lte(value: number, params?: string | core.$ZodCheckLessThanParams): this; + max(value: number, params?: string | core.$ZodCheckLessThanParams): this; + /** Consider `z.int()` instead. This API is considered *legacy*; it will never be removed but a better alternative exists. */ + int(params?: string | core.$ZodCheckNumberFormatParams): this; + /** @deprecated This is now identical to `.int()`. Only numbers in the safe integer range are accepted. */ + safe(params?: string | core.$ZodCheckNumberFormatParams): this; + positive(params?: string | core.$ZodCheckGreaterThanParams): this; + nonnegative(params?: string | core.$ZodCheckGreaterThanParams): this; + negative(params?: string | core.$ZodCheckLessThanParams): this; + nonpositive(params?: string | core.$ZodCheckLessThanParams): this; + multipleOf(value: number, params?: string | core.$ZodCheckMultipleOfParams): this; + /** @deprecated Use `.multipleOf()` instead. */ + step(value: number, params?: string | core.$ZodCheckMultipleOfParams): this; + + /** @deprecated In v4 and later, z.number() does not allow infinite values by default. This is a no-op. */ + finite(params?: unknown): this; + + minValue: number | null; + maxValue: number | null; + /** @deprecated Check the `format` property instead. */ + isInt: boolean; + /** @deprecated Number schemas no longer accept infinite values, so this always returns `true`. */ + isFinite: boolean; + format: string | null; +} + +export interface ZodNumber extends _ZodNumber> {} + +export const ZodNumber: core.$constructor = /*@__PURE__*/ core.$constructor("ZodNumber", (inst, def) => { + core.$ZodNumber.init(inst, def); + ZodType.init(inst, def); + + inst.gt = (value, params) => inst.check(checks.gt(value, params)); + inst.gte = (value, params) => inst.check(checks.gte(value, params)); + inst.min = (value, params) => inst.check(checks.gte(value, params)); + inst.lt = (value, params) => inst.check(checks.lt(value, params)); + inst.lte = (value, params) => inst.check(checks.lte(value, params)); + inst.max = (value, params) => inst.check(checks.lte(value, params)); + inst.int = (params) => inst.check(int(params)); + inst.safe = (params) => inst.check(int(params)); + inst.positive = (params) => inst.check(checks.gt(0, params)); + inst.nonnegative = (params) => inst.check(checks.gte(0, params)); + inst.negative = (params) => inst.check(checks.lt(0, params)); + inst.nonpositive = (params) => inst.check(checks.lte(0, params)); + inst.multipleOf = (value, params) => inst.check(checks.multipleOf(value, params)); + inst.step = (value, params) => inst.check(checks.multipleOf(value, params)); + + // inst.finite = (params) => inst.check(core.finite(params)); + inst.finite = () => inst; + + const bag = inst._zod.bag; + inst.minValue = + Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; + inst.maxValue = + Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; + inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); + inst.isFinite = true; + inst.format = bag.format ?? null; +}); + +export function number(params?: string | core.$ZodNumberParams): ZodNumber { + return core._number(ZodNumber, params) as any; +} + +// ZodNumberFormat +export interface ZodNumberFormat extends ZodNumber { + _zod: core.$ZodNumberFormatInternals; +} +export const ZodNumberFormat: core.$constructor = /*@__PURE__*/ core.$constructor( + "ZodNumberFormat", + (inst, def) => { + core.$ZodNumberFormat.init(inst, def); + ZodNumber.init(inst, def); + } +); + +// int +export interface ZodInt extends ZodNumberFormat {} +export function int(params?: string | core.$ZodCheckNumberFormatParams): ZodInt { + return core._int(ZodNumberFormat, params); +} + +// float32 +export interface ZodFloat32 extends ZodNumberFormat {} +export function float32(params?: string | core.$ZodCheckNumberFormatParams): ZodFloat32 { + return core._float32(ZodNumberFormat, params); +} + +// float64 +export interface ZodFloat64 extends ZodNumberFormat {} +export function float64(params?: string | core.$ZodCheckNumberFormatParams): ZodFloat64 { + return core._float64(ZodNumberFormat, params); +} + +// int32 +export interface ZodInt32 extends ZodNumberFormat {} +export function int32(params?: string | core.$ZodCheckNumberFormatParams): ZodInt32 { + return core._int32(ZodNumberFormat, params); +} + +// uint32 +export interface ZodUInt32 extends ZodNumberFormat {} +export function uint32(params?: string | core.$ZodCheckNumberFormatParams): ZodUInt32 { + return core._uint32(ZodNumberFormat, params); +} + +// boolean +export interface _ZodBoolean extends _ZodType {} +export interface ZodBoolean extends _ZodBoolean> {} +export const ZodBoolean: core.$constructor = /*@__PURE__*/ core.$constructor("ZodBoolean", (inst, def) => { + core.$ZodBoolean.init(inst, def); + ZodType.init(inst, def); +}); + +export function boolean(params?: string | core.$ZodBooleanParams): ZodBoolean { + return core._boolean(ZodBoolean, params) as any; +} + +// bigint +export interface _ZodBigInt extends _ZodType { + gte(value: bigint, params?: string | core.$ZodCheckGreaterThanParams): this; + /** Alias of `.gte()` */ + min(value: bigint, params?: string | core.$ZodCheckGreaterThanParams): this; + gt(value: bigint, params?: string | core.$ZodCheckGreaterThanParams): this; + /** Alias of `.lte()` */ + lte(value: bigint, params?: string | core.$ZodCheckLessThanParams): this; + max(value: bigint, params?: string | core.$ZodCheckLessThanParams): this; + lt(value: bigint, params?: string | core.$ZodCheckLessThanParams): this; + positive(params?: string | core.$ZodCheckGreaterThanParams): this; + negative(params?: string | core.$ZodCheckLessThanParams): this; + nonpositive(params?: string | core.$ZodCheckLessThanParams): this; + nonnegative(params?: string | core.$ZodCheckGreaterThanParams): this; + multipleOf(value: bigint, params?: string | core.$ZodCheckMultipleOfParams): this; + + minValue: bigint | null; + maxValue: bigint | null; + format: string | null; +} + +export interface ZodBigInt extends _ZodBigInt> {} +export const ZodBigInt: core.$constructor = /*@__PURE__*/ core.$constructor("ZodBigInt", (inst, def) => { + core.$ZodBigInt.init(inst, def); + ZodType.init(inst, def); + + inst.gte = (value, params) => inst.check(checks.gte(value, params)); + inst.min = (value, params) => inst.check(checks.gte(value, params)); + inst.gt = (value, params) => inst.check(checks.gt(value, params)); + inst.gte = (value, params) => inst.check(checks.gte(value, params)); + inst.min = (value, params) => inst.check(checks.gte(value, params)); + inst.lt = (value, params) => inst.check(checks.lt(value, params)); + inst.lte = (value, params) => inst.check(checks.lte(value, params)); + inst.max = (value, params) => inst.check(checks.lte(value, params)); + inst.positive = (params) => inst.check(checks.gt(BigInt(0), params)); + inst.negative = (params) => inst.check(checks.lt(BigInt(0), params)); + inst.nonpositive = (params) => inst.check(checks.lte(BigInt(0), params)); + inst.nonnegative = (params) => inst.check(checks.gte(BigInt(0), params)); + inst.multipleOf = (value, params) => inst.check(checks.multipleOf(value, params)); + + const bag = inst._zod.bag; + inst.minValue = bag.minimum ?? null; + inst.maxValue = bag.maximum ?? null; + inst.format = bag.format ?? null; +}); + +export function bigint(params?: string | core.$ZodBigIntParams): ZodBigInt { + return core._bigint(ZodBigInt, params) as any; +} +// bigint formats + +// ZodBigIntFormat +export interface ZodBigIntFormat extends ZodBigInt { + _zod: core.$ZodBigIntFormatInternals; +} +export const ZodBigIntFormat: core.$constructor = /*@__PURE__*/ core.$constructor( + "ZodBigIntFormat", + (inst, def) => { + core.$ZodBigIntFormat.init(inst, def); + ZodBigInt.init(inst, def); + } +); + +// int64 +export function int64(params?: string | core.$ZodBigIntFormatParams): ZodBigIntFormat { + return core._int64(ZodBigIntFormat, params); +} + +// uint64 +export function uint64(params?: string | core.$ZodBigIntFormatParams): ZodBigIntFormat { + return core._uint64(ZodBigIntFormat, params); +} + +// symbol +export interface ZodSymbol extends _ZodType {} +export const ZodSymbol: core.$constructor = /*@__PURE__*/ core.$constructor("ZodSymbol", (inst, def) => { + core.$ZodSymbol.init(inst, def); + ZodType.init(inst, def); +}); + +export function symbol(params?: string | core.$ZodSymbolParams): ZodSymbol { + return core._symbol(ZodSymbol, params); +} + +// ZodUndefined +export interface ZodUndefined extends _ZodType {} +export const ZodUndefined: core.$constructor = /*@__PURE__*/ core.$constructor( + "ZodUndefined", + (inst, def) => { + core.$ZodUndefined.init(inst, def); + ZodType.init(inst, def); + } +); + +function _undefined(params?: string | core.$ZodUndefinedParams): ZodUndefined { + return core._undefined(ZodUndefined, params); +} +export { _undefined as undefined }; + +// ZodNull +export interface ZodNull extends _ZodType {} +export const ZodNull: core.$constructor = /*@__PURE__*/ core.$constructor("ZodNull", (inst, def) => { + core.$ZodNull.init(inst, def); + ZodType.init(inst, def); +}); + +function _null(params?: string | core.$ZodNullParams): ZodNull { + return core._null(ZodNull, params); +} +export { _null as null }; + +// ZodAny +export interface ZodAny extends _ZodType {} +export const ZodAny: core.$constructor = /*@__PURE__*/ core.$constructor("ZodAny", (inst, def) => { + core.$ZodAny.init(inst, def); + ZodType.init(inst, def); +}); + +export function any(): ZodAny { + return core._any(ZodAny); +} + +// ZodUnknown +export interface ZodUnknown extends _ZodType {} +export const ZodUnknown: core.$constructor = /*@__PURE__*/ core.$constructor("ZodUnknown", (inst, def) => { + core.$ZodUnknown.init(inst, def); + ZodType.init(inst, def); +}); + +export function unknown(): ZodUnknown { + return core._unknown(ZodUnknown); +} + +// ZodNever +export interface ZodNever extends _ZodType {} +export const ZodNever: core.$constructor = /*@__PURE__*/ core.$constructor("ZodNever", (inst, def) => { + core.$ZodNever.init(inst, def); + ZodType.init(inst, def); +}); + +export function never(params?: string | core.$ZodNeverParams): ZodNever { + return core._never(ZodNever, params); +} + +// ZodVoid +export interface ZodVoid extends _ZodType {} +export const ZodVoid: core.$constructor = /*@__PURE__*/ core.$constructor("ZodVoid", (inst, def) => { + core.$ZodVoid.init(inst, def); + ZodType.init(inst, def); +}); + +function _void(params?: string | core.$ZodVoidParams): ZodVoid { + return core._void(ZodVoid, params); +} +export { _void as void }; + +// ZodDate +export interface _ZodDate extends _ZodType { + min(value: number | Date, params?: string | core.$ZodCheckGreaterThanParams): this; + max(value: number | Date, params?: string | core.$ZodCheckLessThanParams): this; + + /** @deprecated Not recommended. */ + minDate: Date | null; + /** @deprecated Not recommended. */ + maxDate: Date | null; +} + +export interface ZodDate extends _ZodDate> {} +export const ZodDate: core.$constructor = /*@__PURE__*/ core.$constructor("ZodDate", (inst, def) => { + core.$ZodDate.init(inst, def); + ZodType.init(inst, def); + + inst.min = (value, params) => inst.check(checks.gte(value, params)); + inst.max = (value, params) => inst.check(checks.lte(value, params)); + + const c = inst._zod.bag; + inst.minDate = c.minimum ? new Date(c.minimum) : null; + inst.maxDate = c.maximum ? new Date(c.maximum) : null; +}); + +export function date(params?: string | core.$ZodDateParams): ZodDate { + return core._date(ZodDate, params); +} + +// ZodArray +export interface ZodArray + extends _ZodType>, + core.$ZodArray { + element: T; + min(minLength: number, params?: string | core.$ZodCheckMinLengthParams): this; + nonempty(params?: string | core.$ZodCheckMinLengthParams): this; + max(maxLength: number, params?: string | core.$ZodCheckMaxLengthParams): this; + length(len: number, params?: string | core.$ZodCheckLengthEqualsParams): this; + + unwrap(): T; +} +export const ZodArray: core.$constructor = /*@__PURE__*/ core.$constructor("ZodArray", (inst, def) => { + core.$ZodArray.init(inst, def); + ZodType.init(inst, def); + + inst.element = def.element as any; + inst.min = (minLength, params) => inst.check(checks.minLength(minLength, params)); + inst.nonempty = (params) => inst.check(checks.minLength(1, params)); + inst.max = (maxLength, params) => inst.check(checks.maxLength(maxLength, params)); + inst.length = (len, params) => inst.check(checks.length(len, params)); + + inst.unwrap = () => inst.element; +}); + +export function array(element: T, params?: string | core.$ZodArrayParams): ZodArray { + return core._array(ZodArray, element as any, params) as any; +} + +// .keyof +export function keyof(schema: T): ZodLiteral> { + const shape = schema._zod.def.shape; + return literal(Object.keys(shape)) as any; +} + +// ZodObject + +export interface ZodObject< + /** @ts-ignore Cast variance */ + out Shape extends core.$ZodShape = core.$ZodLooseShape, + out Config extends core.$ZodObjectConfig = core.$strip, +> extends _ZodType>, + core.$ZodObject { + shape: Shape; + + keyof(): ZodEnum>; + /** Define a schema to validate all unrecognized keys. This overrides the existing strict/loose behavior. */ + catchall(schema: T): ZodObject>; + + /** @deprecated Use `z.looseObject()` or `.loose()` instead. */ + passthrough(): ZodObject; + /** Consider `z.looseObject(A.shape)` instead */ + loose(): ZodObject; + + /** Consider `z.strictObject(A.shape)` instead */ + strict(): ZodObject; + + /** This is the default behavior. This method call is likely unnecessary. */ + strip(): ZodObject; + + extend>>( + shape: U + ): ZodObject, Config>; + + /** + * @deprecated Use spread syntax and the `.shape` property to combine two object schemas: + * + * ```ts + * const A = z.object({ a: z.string() }); + * const B = z.object({ b: z.number() }); + * + * const C = z.object({ + * ...A.shape, + * ...B.shape + * }); + * ``` + */ + merge(other: U): ZodObject, U["_zod"]["config"]>; + + pick>( + mask: M + ): ZodObject>>, Config>; + + omit>( + mask: M + ): ZodObject>>, Config>; + + partial(): ZodObject< + { + [k in keyof Shape]: ZodOptional; + }, + Config + >; + partial>( + mask: M + ): ZodObject< + { + [k in keyof Shape]: k extends keyof M + ? // Shape[k] extends OptionalInSchema + // ? Shape[k] + // : + ZodOptional + : Shape[k]; + }, + Config + >; + + // required + required(): ZodObject< + { + [k in keyof Shape]: ZodNonOptional; + }, + Config + >; + required>( + mask: M + ): ZodObject< + { + [k in keyof Shape]: k extends keyof M ? ZodNonOptional : Shape[k]; + }, + Config + >; +} + +export const ZodObject: core.$constructor = /*@__PURE__*/ core.$constructor("ZodObject", (inst, def) => { + core.$ZodObject.init(inst, def); + ZodType.init(inst, def); + + util.defineLazy(inst, "shape", () => def.shape); + inst.keyof = () => _enum(Object.keys(inst._zod.def.shape)) as any; + inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall: catchall as any as core.$ZodType }) as any; + inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); + // inst.nonstrict = () => inst.clone({ ...inst._zod.def, catchall: api.unknown() }); + inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); + inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() }); + inst.strip = () => inst.clone({ ...inst._zod.def, catchall: undefined }); + + inst.extend = (incoming: any) => { + return util.extend(inst, incoming); + }; + inst.merge = (other) => util.merge(inst, other); + inst.pick = (mask) => util.pick(inst, mask); + inst.omit = (mask) => util.omit(inst, mask); + inst.partial = (...args: any[]) => util.partial(ZodOptional, inst, args[0] as object); + inst.required = (...args: any[]) => util.required(ZodNonOptional, inst, args[0] as object); +}); + +export function object>>( + shape?: T, + params?: string | core.$ZodObjectParams +): ZodObject, core.$strip> { + const def: core.$ZodObjectDef = { + type: "object", + get shape() { + util.assignProp(this, "shape", { ...shape }); + return this.shape; + }, + ...util.normalizeParams(params), + }; + return new ZodObject(def) as any; +} + +// strictObject + +export function strictObject( + shape: T, + params?: string | core.$ZodObjectParams +): ZodObject { + return new ZodObject({ + type: "object", + get shape() { + util.assignProp(this, "shape", { ...shape }); + return this.shape; + }, + catchall: never(), + ...util.normalizeParams(params), + }) as any; +} + +// looseObject + +export function looseObject( + shape: T, + params?: string | core.$ZodObjectParams +): ZodObject { + return new ZodObject({ + type: "object", + get shape() { + util.assignProp(this, "shape", { ...shape }); + return this.shape; + }, + catchall: unknown(), + ...util.normalizeParams(params), + }) as any; +} + +// ZodUnion +export interface ZodUnion + extends _ZodType>, + core.$ZodUnion { + options: T; +} +export const ZodUnion: core.$constructor = /*@__PURE__*/ core.$constructor("ZodUnion", (inst, def) => { + core.$ZodUnion.init(inst, def); + ZodType.init(inst, def); + inst.options = def.options; +}); + +export function union( + options: T, + params?: string | core.$ZodUnionParams +): ZodUnion { + return new ZodUnion({ + type: "union", + options: options as any as core.$ZodType[], + ...util.normalizeParams(params), + }) as any; +} + +// ZodDiscriminatedUnion +export interface ZodDiscriminatedUnion + extends ZodUnion, + core.$ZodDiscriminatedUnion { + _zod: core.$ZodDiscriminatedUnionInternals; +} +export const ZodDiscriminatedUnion: core.$constructor = /*@__PURE__*/ core.$constructor( + "ZodDiscriminatedUnion", + (inst, def) => { + ZodUnion.init(inst, def); + core.$ZodDiscriminatedUnion.init(inst, def); + } +); + +export function discriminatedUnion< + Types extends readonly [core.$ZodTypeDiscriminable, ...core.$ZodTypeDiscriminable[]], +>( + discriminator: string, + options: Types, + params?: string | core.$ZodDiscriminatedUnionParams +): ZodDiscriminatedUnion { + // const [options, params] = args; + return new ZodDiscriminatedUnion({ + type: "union", + options, + discriminator, + ...util.normalizeParams(params), + }) as any; +} + +// ZodIntersection +export interface ZodIntersection + extends _ZodType>, + core.$ZodIntersection {} +export const ZodIntersection: core.$constructor = /*@__PURE__*/ core.$constructor( + "ZodIntersection", + (inst, def) => { + core.$ZodIntersection.init(inst, def); + ZodType.init(inst, def); + } +); + +export function intersection( + left: T, + right: U +): ZodIntersection { + return new ZodIntersection({ + type: "intersection", + left: left as any as core.$ZodType, + right: right as any as core.$ZodType, + }) as any; +} + +// ZodTuple +export interface ZodTuple< + T extends util.TupleItems = readonly core.$ZodType[], + Rest extends core.SomeType | null = core.$ZodType | null, +> extends _ZodType>, + core.$ZodTuple { + rest(rest: Rest): ZodTuple; +} +export const ZodTuple: core.$constructor = /*@__PURE__*/ core.$constructor("ZodTuple", (inst, def) => { + core.$ZodTuple.init(inst, def); + ZodType.init(inst, def); + inst.rest = (rest) => + inst.clone({ + ...inst._zod.def, + rest: rest as any as core.$ZodType, + }) as any; +}); + +export function tuple( + items: T, + params?: string | core.$ZodTupleParams +): ZodTuple; +export function tuple( + items: T, + rest: Rest, + params?: string | core.$ZodTupleParams +): ZodTuple; +export function tuple(items: [], params?: string | core.$ZodTupleParams): ZodTuple<[], null>; +export function tuple( + items: core.SomeType[], + _paramsOrRest?: string | core.$ZodTupleParams | core.SomeType, + _params?: string | core.$ZodTupleParams +) { + const hasRest = _paramsOrRest instanceof core.$ZodType; + const params = hasRest ? _params : _paramsOrRest; + const rest = hasRest ? _paramsOrRest : null; + return new ZodTuple({ + type: "tuple", + items: items as any as core.$ZodType[], + rest, + ...util.normalizeParams(params), + }); +} + +// ZodRecord +export interface ZodRecord< + Key extends core.$ZodRecordKey = core.$ZodRecordKey, + Value extends core.SomeType = core.$ZodType, +> extends _ZodType>, + core.$ZodRecord { + keyType: Key; + valueType: Value; +} +export const ZodRecord: core.$constructor = /*@__PURE__*/ core.$constructor("ZodRecord", (inst, def) => { + core.$ZodRecord.init(inst, def); + ZodType.init(inst, def); + + inst.keyType = def.keyType; + inst.valueType = def.valueType; +}); + +export function record( + keyType: Key, + valueType: Value, + params?: string | core.$ZodRecordParams +): ZodRecord { + return new ZodRecord({ + type: "record", + keyType, + valueType: valueType as any as core.$ZodType, + ...util.normalizeParams(params), + }) as any; +} +// type alksjf = core.output; +export function partialRecord( + keyType: Key, + valueType: Value, + params?: string | core.$ZodRecordParams +): ZodRecord { + return new ZodRecord({ + type: "record", + keyType: union([keyType, never()]), + valueType: valueType as any, + ...util.normalizeParams(params), + }) as any; +} + +// ZodMap +export interface ZodMap + extends _ZodType>, + core.$ZodMap { + keyType: Key; + valueType: Value; +} +export const ZodMap: core.$constructor = /*@__PURE__*/ core.$constructor("ZodMap", (inst, def) => { + core.$ZodMap.init(inst, def); + ZodType.init(inst, def); + inst.keyType = def.keyType; + inst.valueType = def.valueType; +}); + +export function map( + keyType: Key, + valueType: Value, + params?: string | core.$ZodMapParams +): ZodMap { + return new ZodMap({ + type: "map", + keyType: keyType as any as core.$ZodType, + valueType: valueType as any as core.$ZodType, + ...util.normalizeParams(params), + }) as any; +} + +// ZodSet +export interface ZodSet + extends _ZodType>, + core.$ZodSet { + min(minSize: number, params?: string | core.$ZodCheckMinSizeParams): this; + /** */ + nonempty(params?: string | core.$ZodCheckMinSizeParams): this; + max(maxSize: number, params?: string | core.$ZodCheckMaxSizeParams): this; + size(size: number, params?: string | core.$ZodCheckSizeEqualsParams): this; +} +export const ZodSet: core.$constructor = /*@__PURE__*/ core.$constructor("ZodSet", (inst, def) => { + core.$ZodSet.init(inst, def); + ZodType.init(inst, def); + + inst.min = (...args) => inst.check(core._minSize(...args)); + inst.nonempty = (params) => inst.check(core._minSize(1, params)); + inst.max = (...args) => inst.check(core._maxSize(...args)); + inst.size = (...args) => inst.check(core._size(...args)); +}); + +export function set( + valueType: Value, + params?: string | core.$ZodSetParams +): ZodSet { + return new ZodSet({ + type: "set", + valueType: valueType as any as core.$ZodType, + ...util.normalizeParams(params), + }) as any; +} + +// ZodEnum +export interface ZodEnum< + /** @ts-ignore Cast variance */ + out T extends util.EnumLike = util.EnumLike, +> extends _ZodType>, + core.$ZodEnum { + enum: T; + options: Array; + + extract( + values: U, + params?: string | core.$ZodEnumParams + ): ZodEnum>>; + exclude( + values: U, + params?: string | core.$ZodEnumParams + ): ZodEnum>>; +} +export const ZodEnum: core.$constructor = /*@__PURE__*/ core.$constructor("ZodEnum", (inst, def) => { + core.$ZodEnum.init(inst, def); + ZodType.init(inst, def); + + inst.enum = def.entries; + inst.options = Object.values(def.entries); + + const keys = new Set(Object.keys(def.entries)); + + inst.extract = (values, params) => { + const newEntries: Record = {}; + for (const value of values) { + if (keys.has(value)) { + newEntries[value] = def.entries[value]; + } else throw new Error(`Key ${value} not found in enum`); + } + return new ZodEnum({ + ...def, + checks: [], + ...util.normalizeParams(params), + entries: newEntries, + }) as any; + }; + + inst.exclude = (values, params) => { + const newEntries: Record = { ...def.entries }; + for (const value of values) { + if (keys.has(value)) { + delete newEntries[value]; + } else throw new Error(`Key ${value} not found in enum`); + } + return new ZodEnum({ + ...def, + checks: [], + ...util.normalizeParams(params), + entries: newEntries, + }) as any; + }; +}); + +function _enum( + values: T, + params?: string | core.$ZodEnumParams +): ZodEnum>; +function _enum(entries: T, params?: string | core.$ZodEnumParams): ZodEnum; +function _enum(values: any, params?: string | core.$ZodEnumParams) { + const entries: any = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; + + return new ZodEnum({ + type: "enum", + entries, + ...util.normalizeParams(params), + }) as any; +} +export { _enum as enum }; + +/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. + * + * ```ts + * enum Colors { red, green, blue } + * z.enum(Colors); + * ``` + */ +export function nativeEnum(entries: T, params?: string | core.$ZodEnumParams): ZodEnum { + return new ZodEnum({ + type: "enum", + entries, + ...util.normalizeParams(params), + }) as any as ZodEnum; +} + +// ZodLiteral +export interface ZodLiteral + extends _ZodType>, + core.$ZodLiteral { + values: Set; + /** @legacy Use `.values` instead. Accessing this property will throw an error if the literal accepts multiple values. */ + value: T; +} +export const ZodLiteral: core.$constructor = /*@__PURE__*/ core.$constructor("ZodLiteral", (inst, def) => { + core.$ZodLiteral.init(inst, def); + ZodType.init(inst, def); + inst.values = new Set(def.values); + Object.defineProperty(inst, "value", { + get() { + if (def.values.length > 1) { + throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); + } + return def.values[0]; + }, + }); +}); + +export function literal>( + value: T, + params?: string | core.$ZodLiteralParams +): ZodLiteral; +export function literal( + value: T, + params?: string | core.$ZodLiteralParams +): ZodLiteral; +export function literal(value: any, params: any) { + return new ZodLiteral({ + type: "literal", + values: Array.isArray(value) ? value : [value], + ...util.normalizeParams(params), + }); +} + +// ZodFile +export interface ZodFile extends _ZodType, core.$ZodFile { + min(size: number, params?: string | core.$ZodCheckMinSizeParams): this; + max(size: number, params?: string | core.$ZodCheckMaxSizeParams): this; + mime(types: util.MimeTypes | Array, params?: string | core.$ZodCheckMimeTypeParams): this; +} +export const ZodFile: core.$constructor = /*@__PURE__*/ core.$constructor("ZodFile", (inst, def) => { + core.$ZodFile.init(inst, def); + ZodType.init(inst, def); + + inst.min = (size, params) => inst.check(core._minSize(size, params)); + inst.max = (size, params) => inst.check(core._maxSize(size, params)); + inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params)); +}); + +export function file(params?: string | core.$ZodFileParams): ZodFile { + return core._file(ZodFile, params) as any; +} + +// ZodTransform +export interface ZodTransform + extends _ZodType>, + core.$ZodTransform {} +export const ZodTransform: core.$constructor = /*@__PURE__*/ core.$constructor( + "ZodTransform", + (inst, def) => { + core.$ZodTransform.init(inst, def); + ZodType.init(inst, def); + + inst._zod.parse = (payload, _ctx) => { + (payload as RefinementCtx).addIssue = (issue) => { + if (typeof issue === "string") { + payload.issues.push(util.issue(issue, payload.value, def)); + } else { + // for Zod 3 backwards compatibility + const _issue = issue as any; + + if (_issue.fatal) _issue.continue = false; + _issue.code ??= "custom"; + _issue.input ??= payload.value; + _issue.inst ??= inst; + _issue.continue ??= true; + payload.issues.push(util.issue(_issue)); + } + }; + + const output = def.transform(payload.value, payload); + if (output instanceof Promise) { + return output.then((output) => { + payload.value = output; + return payload; + }); + } + payload.value = output; + return payload; + }; + } +); + +export function transform( + fn: (input: I, ctx: core.ParsePayload) => O +): ZodTransform, I> { + return new ZodTransform({ + type: "transform", + transform: fn as any, + }) as any; +} + +// ZodOptional +export interface ZodOptional + extends _ZodType>, + core.$ZodOptional { + unwrap(): T; +} +export const ZodOptional: core.$constructor = /*@__PURE__*/ core.$constructor( + "ZodOptional", + (inst, def) => { + core.$ZodOptional.init(inst, def); + ZodType.init(inst, def); + + inst.unwrap = () => inst._zod.def.innerType; + } +); + +export function optional(innerType: T): ZodOptional { + return new ZodOptional({ + type: "optional", + innerType: innerType as any as core.$ZodType, + }) as any; +} + +// ZodNullable +export interface ZodNullable + extends _ZodType>, + core.$ZodNullable { + unwrap(): T; +} +export const ZodNullable: core.$constructor = /*@__PURE__*/ core.$constructor( + "ZodNullable", + (inst, def) => { + core.$ZodNullable.init(inst, def); + ZodType.init(inst, def); + + inst.unwrap = () => inst._zod.def.innerType; + } +); + +export function nullable(innerType: T): ZodNullable { + return new ZodNullable({ + type: "nullable", + innerType: innerType as any as core.$ZodType, + }) as any; +} + +// nullish +export function nullish(innerType: T): ZodOptional> { + return optional(nullable(innerType)); +} + +// ZodDefault +export interface ZodDefault + extends _ZodType>, + core.$ZodDefault { + unwrap(): T; + /** @deprecated Use `.unwrap()` instead. */ + removeDefault(): T; +} +export const ZodDefault: core.$constructor = /*@__PURE__*/ core.$constructor("ZodDefault", (inst, def) => { + core.$ZodDefault.init(inst, def); + ZodType.init(inst, def); + + inst.unwrap = () => inst._zod.def.innerType; + inst.removeDefault = inst.unwrap; +}); + +export function _default( + innerType: T, + defaultValue: util.NoUndefined> | (() => util.NoUndefined>) +): ZodDefault { + return new ZodDefault({ + type: "default", + innerType: innerType as any as core.$ZodType, + get defaultValue() { + return typeof defaultValue === "function" ? (defaultValue as Function)() : defaultValue; + }, + }) as any; +} + +// ZodPrefault +export interface ZodPrefault + extends _ZodType>, + core.$ZodPrefault { + unwrap(): T; +} +export const ZodPrefault: core.$constructor = /*@__PURE__*/ core.$constructor( + "ZodPrefault", + (inst, def) => { + core.$ZodPrefault.init(inst, def); + ZodType.init(inst, def); + inst.unwrap = () => inst._zod.def.innerType; + } +); + +export function prefault( + innerType: T, + defaultValue: core.input | (() => core.input) +): ZodPrefault { + return new ZodPrefault({ + type: "prefault", + innerType: innerType as any as core.$ZodType, + get defaultValue() { + return typeof defaultValue === "function" ? (defaultValue as Function)() : defaultValue; + }, + }) as any; +} + +// ZodNonOptional +export interface ZodNonOptional + extends _ZodType>, + core.$ZodNonOptional { + unwrap(): T; +} +export const ZodNonOptional: core.$constructor = /*@__PURE__*/ core.$constructor( + "ZodNonOptional", + (inst, def) => { + core.$ZodNonOptional.init(inst, def); + ZodType.init(inst, def); + + inst.unwrap = () => inst._zod.def.innerType; + } +); + +export function nonoptional( + innerType: T, + params?: string | core.$ZodNonOptionalParams +): ZodNonOptional { + return new ZodNonOptional({ + type: "nonoptional", + innerType: innerType as any as core.$ZodType, + ...util.normalizeParams(params), + }) as any; +} + +// ZodSuccess +export interface ZodSuccess + extends _ZodType>, + core.$ZodSuccess { + unwrap(): T; +} +export const ZodSuccess: core.$constructor = /*@__PURE__*/ core.$constructor("ZodSuccess", (inst, def) => { + core.$ZodSuccess.init(inst, def); + ZodType.init(inst, def); + + inst.unwrap = () => inst._zod.def.innerType; +}); + +export function success(innerType: T): ZodSuccess { + return new ZodSuccess({ + type: "success", + innerType: innerType as any as core.$ZodType, + }) as any; +} + +// ZodCatch +export interface ZodCatch + extends _ZodType>, + core.$ZodCatch { + unwrap(): T; + /** @deprecated Use `.unwrap()` instead. */ + removeCatch(): T; +} +export const ZodCatch: core.$constructor = /*@__PURE__*/ core.$constructor("ZodCatch", (inst, def) => { + core.$ZodCatch.init(inst, def); + ZodType.init(inst, def); + + inst.unwrap = () => inst._zod.def.innerType; + inst.removeCatch = inst.unwrap; +}); + +function _catch( + innerType: T, + catchValue: core.output | ((ctx: core.$ZodCatchCtx) => core.output) +): ZodCatch { + return new ZodCatch({ + type: "catch", + innerType: innerType as any as core.$ZodType, + catchValue: (typeof catchValue === "function" ? catchValue : () => catchValue) as ( + ctx: core.$ZodCatchCtx + ) => core.output, + }) as any; +} +export { _catch as catch }; + +// ZodNaN +export interface ZodNaN extends _ZodType, core.$ZodNaN {} +export const ZodNaN: core.$constructor = /*@__PURE__*/ core.$constructor("ZodNaN", (inst, def) => { + core.$ZodNaN.init(inst, def); + ZodType.init(inst, def); +}); + +export function nan(params?: string | core.$ZodNaNParams): ZodNaN { + return core._nan(ZodNaN, params); +} + +// ZodPipe +export interface ZodPipe + extends _ZodType>, + core.$ZodPipe { + in: A; + out: B; +} +export const ZodPipe: core.$constructor = /*@__PURE__*/ core.$constructor("ZodPipe", (inst, def) => { + core.$ZodPipe.init(inst, def); + ZodType.init(inst, def); + + inst.in = def.in; + inst.out = def.out; +}); + +export function pipe< + const A extends core.SomeType, + B extends core.$ZodType> = core.$ZodType>, +>(in_: A, out: B | core.$ZodType>): ZodPipe; +export function pipe(in_: core.SomeType, out: core.SomeType) { + return new ZodPipe({ + type: "pipe", + in: in_ as unknown as core.$ZodType, + out: out as unknown as core.$ZodType, + // ...util.normalizeParams(params), + }); +} + +// ZodReadonly +export interface ZodReadonly + extends _ZodType>, + core.$ZodReadonly {} +export const ZodReadonly: core.$constructor = /*@__PURE__*/ core.$constructor( + "ZodReadonly", + (inst, def) => { + core.$ZodReadonly.init(inst, def); + ZodType.init(inst, def); + } +); + +export function readonly(innerType: T): ZodReadonly { + return new ZodReadonly({ + type: "readonly", + innerType: innerType as any as core.$ZodType, + }) as any; +} + +// ZodTemplateLiteral +export interface ZodTemplateLiteral