diff --git a/worker/node_modules/unenv/dist/index.mjs b/worker/node_modules/unenv/dist/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a36a8e66741e9c317be439e0aee8910b9beacfa1 --- /dev/null +++ b/worker/node_modules/unenv/dist/index.mjs @@ -0,0 +1,338 @@ +import { builtinModules } from "node:module"; +import { createResolver } from "exsolve"; + +//#region node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs +const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//; +function normalizeWindowsPath(input = "") { + if (!input) return input; + return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase()); +} +const _UNC_REGEX = /^[/\\]{2}/; +const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/; +const _DRIVE_LETTER_RE = /^[A-Za-z]:$/; +const normalize = function(path) { + if (path.length === 0) return "."; + path = normalizeWindowsPath(path); + const isUNCPath = path.match(_UNC_REGEX); + const isPathAbsolute = isAbsolute(path); + const trailingSeparator = path[path.length - 1] === "/"; + path = normalizeString(path, !isPathAbsolute); + if (path.length === 0) { + if (isPathAbsolute) return "/"; + return trailingSeparator ? "./" : "."; + } + if (trailingSeparator) path += "/"; + if (_DRIVE_LETTER_RE.test(path)) path += "/"; + if (isUNCPath) { + if (!isPathAbsolute) return `//./${path}`; + return `//${path}`; + } + return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path; +}; +const join = function(...segments) { + let path = ""; + for (const seg of segments) { + if (!seg) continue; + if (path.length > 0) { + const pathTrailing = path[path.length - 1] === "/"; + const segLeading = seg[0] === "/"; + const both = pathTrailing && segLeading; + if (both) path += seg.slice(1); + else path += pathTrailing || segLeading ? seg : `/${seg}`; + } else path += seg; + } + return normalize(path); +}; +function normalizeString(path, allowAboveRoot) { + let res = ""; + let lastSegmentLength = 0; + let lastSlash = -1; + let dots = 0; + let char = null; + for (let index = 0; index <= path.length; ++index) { + if (index < path.length) char = path[index]; + else if (char === "/") break; + else char = "/"; + if (char === "/") { + if (lastSlash === index - 1 || dots === 1); + else if (dots === 2) { + if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") { + if (res.length > 2) { + const lastSlashIndex = res.lastIndexOf("/"); + if (lastSlashIndex === -1) { + res = ""; + lastSegmentLength = 0; + } else { + res = res.slice(0, lastSlashIndex); + lastSegmentLength = res.length - 1 - res.lastIndexOf("/"); + } + lastSlash = index; + dots = 0; + continue; + } else if (res.length > 0) { + res = ""; + lastSegmentLength = 0; + lastSlash = index; + dots = 0; + continue; + } + } + if (allowAboveRoot) { + res += res.length > 0 ? "/.." : ".."; + lastSegmentLength = 2; + } + } else { + if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`; + else res = path.slice(lastSlash + 1, index); + lastSegmentLength = index - lastSlash - 1; + } + lastSlash = index; + dots = 0; + } else if (char === "." && dots !== -1) ++dots; + else dots = -1; + } + return res; +} +const isAbsolute = function(p) { + return _IS_ABSOLUTE_RE.test(p); +}; + +//#endregion +//#region node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/utils.mjs +const pathSeparators = /* @__PURE__ */ new Set([ + "/", + "\\", + void 0 +]); +const normalizedAliasSymbol = Symbol.for("pathe:normalizedAlias"); +function normalizeAliases(_aliases) { + if (_aliases[normalizedAliasSymbol]) return _aliases; + const aliases = Object.fromEntries(Object.entries(_aliases).sort(([a], [b]) => _compareAliases(a, b))); + for (const key in aliases) for (const alias in aliases) { + if (alias === key || key.startsWith(alias)) continue; + if (aliases[key]?.startsWith(alias) && pathSeparators.has(aliases[key][alias.length])) aliases[key] = aliases[alias] + aliases[key].slice(alias.length); + } + Object.defineProperty(aliases, normalizedAliasSymbol, { + value: true, + enumerable: false + }); + return aliases; +} +function resolveAlias(path, aliases) { + const _path = normalizeWindowsPath(path); + aliases = normalizeAliases(aliases); + for (const [alias, to] of Object.entries(aliases)) { + if (!_path.startsWith(alias)) continue; + const _alias = hasTrailingSlash(alias) ? alias.slice(0, -1) : alias; + if (hasTrailingSlash(_path[_alias.length])) return join(to, _path.slice(alias.length)); + } + return _path; +} +function _compareAliases(a, b) { + return b.split("/").length - a.split("/").length; +} +function hasTrailingSlash(path = "/") { + const lastChar = path[path.length - 1]; + return lastChar === "/" || lastChar === "\\"; +} + +//#endregion +//#region package.json +var version = "2.0.0-rc.14"; + +//#endregion +//#region src/preset.ts +const nodeCompatAliases = { + _http_agent: "unenv/mock/proxy-cjs", + _http_client: "unenv/mock/proxy-cjs", + _http_common: "unenv/mock/proxy-cjs", + _http_incoming: "unenv/mock/proxy-cjs", + _http_outgoing: "unenv/mock/proxy-cjs", + _http_server: "unenv/mock/proxy-cjs", + _stream_duplex: "unenv/mock/proxy-cjs", + _stream_passthrough: "unenv/mock/proxy-cjs", + _stream_readable: "unenv/mock/proxy-cjs", + _stream_transform: "unenv/mock/proxy-cjs", + _stream_wrap: "unenv/mock/proxy-cjs", + _stream_writable: "unenv/mock/proxy-cjs", + _tls_common: "unenv/mock/proxy-cjs", + _tls_wrap: "unenv/mock/proxy-cjs", + assert: "unenv/node/assert", + "assert/strict": "unenv/node/assert/strict", + async_hooks: "unenv/node/async_hooks", + buffer: "unenv/node/buffer", + child_process: "unenv/node/child_process", + cluster: "unenv/node/cluster", + console: "unenv/node/console", + constants: "unenv/node/constants", + crypto: "unenv/node/crypto", + dgram: "unenv/node/dgram", + diagnostics_channel: "unenv/node/diagnostics_channel", + dns: "unenv/node/dns", + "dns/promises": "unenv/node/dns/promises", + domain: "unenv/node/domain", + events: "unenv/node/events", + fs: "unenv/node/fs", + "fs/promises": "unenv/node/fs/promises", + http: "unenv/node/http", + http2: "unenv/node/http2", + https: "unenv/node/https", + inspector: "unenv/node/inspector", + "inspector/promises": "unenv/node/inspector/promises", + module: "unenv/node/module", + net: "unenv/node/net", + os: "unenv/node/os", + path: "unenv/node/path", + "path/posix": "unenv/node/path", + "path/win32": "unenv/node/path", + perf_hooks: "unenv/node/perf_hooks", + process: "unenv/node/process", + punycode: "unenv/node/punycode", + querystring: "unenv/node/querystring", + readline: "unenv/node/readline", + "readline/promises": "unenv/node/readline/promises", + repl: "unenv/node/repl", + stream: "unenv/node/stream", + "stream/consumers": "unenv/node/stream/consumers", + "stream/promises": "unenv/node/stream/promises", + "stream/web": "unenv/node/stream/web", + string_decoder: "unenv/node/string_decoder", + sys: "unenv/node/util", + timers: "unenv/node/timers", + "timers/promises": "unenv/node/timers/promises", + tls: "unenv/node/tls", + trace_events: "unenv/node/trace_events", + tty: "unenv/node/tty", + url: "unenv/node/url", + util: "unenv/node/util", + "util/types": "unenv/node/util/types", + v8: "unenv/node/v8", + vm: "unenv/node/vm", + wasi: "unenv/node/wasi", + worker_threads: "unenv/node/worker_threads", + zlib: "unenv/node/zlib" +}; +const nodeCompatInjects = { + process: "unenv/node/process", + global: "unenv/polyfill/globalthis", + Buffer: ["node:buffer", "Buffer"], + clearImmediate: ["node:timers", "clearImmediate"], + setImmediate: ["node:timers", "setImmediate"] +}; +const npmShims = { + "cross-fetch": "unenv/npm/cross-fetch", + debug: "unenv/npm/debug", + fsevents: "unenv/npm/fsevents", + inherits: "unenv/npm/inherits", + "node-fetch": "unenv/npm/node-fetch", + "node-fetch-native": "unenv/npm/node-fetch", + "whatwg-url": "unenv/npm/whatwg-url", + "cross-fetch/polyfill": "unenv/mock/empty", + "node-fetch-native/polyfill": "unenv/mock/empty", + "isomorphic-fetch": "unenv/mock/empty" +}; + +//#endregion +//#region src/env.ts +const defineEnv = (opts = {}) => { + const presets = []; + presets.push(unenvPreset(opts)); + if (opts.presets) presets.push(...opts.presets); + if (opts.overrides) presets.push(opts.overrides); + if (opts.resolve) { + for (const preset of presets) if (preset.meta?.url) resolvePaths(preset, [preset.meta.url], opts); + } + const env = mergePresets(...presets); + if (opts.resolve) resolvePaths(env, presets.map((preset) => preset.meta?.url).filter((v) => v !== undefined), opts); + return { + env, + presets + }; +}; +function unenvPreset(opts) { + const preset = { + meta: { + name: "unenv", + version, + url: import.meta.url + }, + alias: {}, + inject: {}, + external: [], + polyfill: [] + }; + if (opts.nodeCompat !== false) { + Object.assign(preset.inject, nodeCompatInjects); + Object.assign(preset.alias, { ...Object.fromEntries(Object.entries(nodeCompatAliases).flatMap(([from, to]) => { + const aliases = [[from, to], [`node:${from}`, to]]; + return aliases; + })) }); + } + if (opts.npmShims) Object.assign(preset.alias, npmShims); + return preset; +} +function resolvePaths(env, from, opts = {}) { + if (!opts.resolve) return; + const { resolveModulePath } = createResolver({ from: [ + ...opts.resolve === true ? [] : opts.resolve.paths || [], + ...from, + import.meta.url, + process.cwd() + "/" + ] }); + const _resolve = (id) => { + if (!id) return id; + if (env.alias) id = resolveAlias(id, env.alias); + if (id.startsWith("node:")) return id; + if (builtinModules.includes(id)) return `node:${id}`; + let resolved = resolveModulePath(id, { try: true }); + if (!resolved && id.startsWith("unenv/")) resolved = resolveModulePath(id.replace("unenv/", "unenv-nightly/"), { try: true }); + return resolved || id; + }; + for (const alias in env.alias) env.alias[alias] = _resolve(env.alias[alias]); + if (env.polyfill) for (let i = 0; i < env.polyfill.length; i++) env.polyfill[i] = _resolve(env.polyfill[i]); + for (const global in env.inject) { + const inject = env.inject[global]; + if (Array.isArray(inject)) { + const [id, ...path] = inject; + env.inject[global] = [_resolve(id), ...path]; + } else env.inject[global] = _resolve(inject); + } + return env; +} +function mergePresets(...presets) { + const env = { + alias: {}, + inject: {}, + polyfill: [], + external: [] + }; + for (const preset of presets) { + if (preset.alias) { + const aliases = Object.keys(preset.alias).sort((a, b) => b.split("/").length - a.split("/").length || b.length - a.length); + for (const from of aliases) env.alias[from] = preset.alias[from]; + } + if (preset.inject) for (const [global, globalValue] of Object.entries(preset.inject)) if (Array.isArray(globalValue)) env.inject[global] = globalValue; + else if (globalValue === false) delete env.inject[global]; + else env.inject[global] = globalValue; + if (preset.polyfill) env.polyfill.push(...preset.polyfill.filter(Boolean)); + if (preset.external) env.external.push(...preset.external); + } + env.polyfill = resolveArray(env.polyfill); + env.external = resolveArray(env.external); + return env; +} +/** +* - Deduplicates items +* - Removes nagate items with ! prefix +*/ +function resolveArray(arr) { + const set = new Set(arr); + for (const item of arr) if (item.startsWith("!")) { + set.delete(item); + set.delete(item.slice(1)); + } + return [...set]; +} + +//#endregion +export { defineEnv }; \ No newline at end of file diff --git a/worker/node_modules/unenv/dist/runtime/_internal/types.d.mts b/worker/node_modules/unenv/dist/runtime/_internal/types.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..fd46ad532b87af527d2bc1606bff6282deddd2cf --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/_internal/types.d.mts @@ -0,0 +1,5 @@ +export type Callback = (error?: E) => void; +export type HeadersObject = { + [key: string]: string | string[] | undefined +}; +export type BufferEncoding = any; diff --git a/worker/node_modules/unenv/dist/runtime/_internal/types.mjs b/worker/node_modules/unenv/dist/runtime/_internal/types.mjs new file mode 100644 index 0000000000000000000000000000000000000000..cb0ff5c3b541f646105198ee23ac0fc3d805023e --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/_internal/types.mjs @@ -0,0 +1 @@ +export {}; diff --git a/worker/node_modules/unenv/dist/runtime/_internal/utils.d.mts b/worker/node_modules/unenv/dist/runtime/_internal/utils.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..91d61918d2e9729fb826cea675d49e4ed8caf560 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/_internal/utils.d.mts @@ -0,0 +1,14 @@ +import type { HeadersObject } from "./types.mjs"; +/*@__NO_SIDE_EFFECTS__*/ export declare function rawHeaders(headers: HeadersObject); +type Fn = (...args: any[]) => any; +/*@__NO_SIDE_EFFECTS__*/ export declare function mergeFns(...functions: Fn[]): unknown; +/*@__NO_SIDE_EFFECTS__*/ export declare function createNotImplementedError(name: string); +/*@__NO_SIDE_EFFECTS__*/ export declare function notImplemented any>(name: string): Fn; +export interface Promisifiable { + (): any; + native: Promisifiable; + __promisify__: () => Promise; +} +/*@__NO_SIDE_EFFECTS__*/ export declare function notImplementedAsync(name: string): Promisifiable; +/*@__NO_SIDE_EFFECTS__*/ export declare function notImplementedClass(name: string): T; +export {}; diff --git a/worker/node_modules/unenv/dist/runtime/_internal/utils.mjs b/worker/node_modules/unenv/dist/runtime/_internal/utils.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a0fc508bb2c218742a720a700bb61cb922179eb2 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/_internal/utils.mjs @@ -0,0 +1,43 @@ +/*@__NO_SIDE_EFFECTS__*/ export function rawHeaders(headers) { + const rawHeaders = []; + for (const key in headers) { + if (Array.isArray(headers[key])) { + for (const h of headers[key]) { + rawHeaders.push(key, h); + } + } else { + rawHeaders.push(key, headers[key]); + } + } + return rawHeaders; +} +/*@__NO_SIDE_EFFECTS__*/ export function mergeFns(...functions) { + return function(...args) { + for (const fn of functions) { + fn(...args); + } + }; +} +/*@__NO_SIDE_EFFECTS__*/ export function createNotImplementedError(name) { + return new Error(`[unenv] ${name} is not implemented yet!`); +} +/*@__NO_SIDE_EFFECTS__*/ export function notImplemented(name) { + const fn = () => { + throw createNotImplementedError(name); + }; + return Object.assign(fn, { __unenv__: true }); +} +/*@__NO_SIDE_EFFECTS__*/ export function notImplementedAsync(name) { + const fn = notImplemented(name); + fn.__promisify__ = () => notImplemented(name + ".__promisify__"); + fn.native = fn; + return fn; +} +/*@__NO_SIDE_EFFECTS__*/ export function notImplementedClass(name) { + return class { + __unenv__ = true; + constructor() { + throw new Error(`[unenv] ${name} is not implemented yet!`); + } + }; +} diff --git a/worker/node_modules/unenv/dist/runtime/mock/empty.d.mts b/worker/node_modules/unenv/dist/runtime/mock/empty.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..e89f93708579ddfd1194491115ef9005403aa6d9 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/mock/empty.d.mts @@ -0,0 +1,2 @@ +declare const _default; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/mock/empty.mjs b/worker/node_modules/unenv/dist/runtime/mock/empty.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6fbbcc1b02f621faa198010064df032b90da8917 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/mock/empty.mjs @@ -0,0 +1 @@ +export default Object.freeze(Object.create(null, { __unenv__: { get: () => true } })); diff --git a/worker/node_modules/unenv/dist/runtime/mock/noop.d.mts b/worker/node_modules/unenv/dist/runtime/mock/noop.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..e89f93708579ddfd1194491115ef9005403aa6d9 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/mock/noop.d.mts @@ -0,0 +1,2 @@ +declare const _default; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/mock/noop.mjs b/worker/node_modules/unenv/dist/runtime/mock/noop.mjs new file mode 100644 index 0000000000000000000000000000000000000000..95beb569e95b7bf2d5d6bd027d4bc577c6e53daf --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/mock/noop.mjs @@ -0,0 +1 @@ +export default Object.assign(() => {}, { __unenv__: true }); diff --git a/worker/node_modules/unenv/dist/runtime/mock/proxy.d.mts b/worker/node_modules/unenv/dist/runtime/mock/proxy.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..e89f93708579ddfd1194491115ef9005403aa6d9 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/mock/proxy.d.mts @@ -0,0 +1,2 @@ +declare const _default; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/mock/proxy.mjs b/worker/node_modules/unenv/dist/runtime/mock/proxy.mjs new file mode 100644 index 0000000000000000000000000000000000000000..097adf39d8b39a023ca4796e5f1689b95cdc79df --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/mock/proxy.mjs @@ -0,0 +1,42 @@ +function createMock(name, overrides = {}) { + const proxyFn = function() {}; + proxyFn.prototype.name = name; + const props = {}; + const proxy = new Proxy(proxyFn, { + get(_target, prop) { + if (prop === "caller") { + return null; + } + if (prop === "__createMock__") { + return createMock; + } + if (prop === "__unenv__") { + return true; + } + if (prop in overrides) { + return overrides[prop]; + } + if (prop === "then") { + return (fn) => Promise.resolve(fn()); + } + if (prop === "catch") { + return (fn) => Promise.resolve(); + } + if (prop === "finally") { + return (fn) => Promise.resolve(fn()); + } + return props[prop] = props[prop] || createMock(`${name}.${prop.toString()}`); + }, + apply(_target, _this, _args) { + return createMock(`${name}()`); + }, + construct(_target, _args, _newT) { + return createMock(`[${name}]`); + }, + enumerate() { + return []; + } + }); + return proxy; +} +export default createMock("mock"); diff --git a/worker/node_modules/unenv/dist/runtime/node/assert.d.mts b/worker/node_modules/unenv/dist/runtime/node/assert.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..b454b13bb1ada4969302c6e0728b7ab750451402 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/assert.d.mts @@ -0,0 +1,133 @@ +import type nodeAssert from "node:assert"; +export declare class AssertionError extends Error implements nodeAssert.AssertionError { + actual: unknown; + expected: unknown; + operator: string; + generatedMessage: boolean; + code: "ERR_ASSERTION"; + constructor(options: { + message?: string + actual?: unknown + expected?: unknown + operator?: string + stackStartFn?: Function + }); +} +/** +* Pure assertion tests whether a value is truthy, as determined +* by !!value. +* @param {...any} args +* @returns {void} +*/ +export declare function ok(...args: unknown[]); +/** +* The equality assertion tests shallow, coercive equality with ==. +* @param {any} actual +* @param {any} expected +* @param {string | Error} [message] +* @returns {void} +*/ +export declare function equal(actual: unknown, expected: unknown, message?: string | Error): void; +/** +* The non-equality assertion tests for whether two objects are not +* equal with !=. +* @param {any} actual +* @param {any} expected +* @param {string | Error} [message] +* @returns {void} +*/ +export declare function notEqual(actual: unknown, expected: unknown, message?: string | Error); +/** +* The deep equivalence assertion tests a deep equality relation. +* @param {any} actual +* @param {any} expected +* @param {string | Error} [message] +* @returns {void} +*/ +export declare function deepEqual(actual: unknown, expected: unknown, message?: string | Error); +/** +* The deep non-equivalence assertion tests for any deep inequality. +* @param {any} actual +* @param {any} expected +* @param {string | Error} [message] +* @returns {void} +*/ +export declare function notDeepEqual(actual: unknown, expected: unknown, message?: string | Error); +/** +* The deep strict equivalence assertion tests a deep strict equality +* relation. +* @param {any} actual +* @param {any} expected +* @param {string | Error} [message] +* @returns {void} +*/ +export declare function deepStrictEqual(actual: unknown, expected: unknown, message?: string | Error); +/** +* The deep strict non-equivalence assertion tests for any deep strict +* inequality. +* @param {any} actual +* @param {any} expected +* @param {string | Error} [message] +* @returns {void} +*/ +export declare function notDeepStrictEqual(actual: unknown, expected: unknown, message?: string | Error); +/** +* The strict equivalence assertion tests a strict equality relation. +* @param {any} actual +* @param {any} expected +* @param {string | Error} [message] +* @returns {void} +*/ +export declare function strictEqual(actual: unknown, expected: unknown, message?: string | Error); +/** +* The strict non-equivalence assertion tests for any strict inequality. +* @param {any} actual +* @param {any} expected +* @param {string | Error} [message] +* @returns {void} +*/ +export declare function notStrictEqual(actual: unknown, expected: unknown, message?: string | Error); +/** +* Expects the function `promiseFn` to throw an error. +*/ +export declare function throws(promiseFn: () => any, ...args: unknown[]): void; +/** +* Expects `promiseFn` function or its value to reject. +*/ +export declare function rejects(promiseFn: (() => Promise) | Promise, ...args: unknown[]): Promise; +/** +* Asserts that the function `fn` does not throw an error. +*/ +export declare function doesNotThrow(fn: () => any, ...args: unknown[]): void; +/** +* Expects `fn` or its value to not reject. +*/ +export declare function doesNotReject(fn: (() => Promise) | Promise, ...args: unknown[]): Promise; +/** +* Throws `value` if the value is not `null` or `undefined`. +* @param {any} err +* @returns {void} +*/ +export declare function ifError(err: unknown); +/** +* Expects the `string` input to match the regular expression. +* @param {string} string +* @param {RegExp} regexp +* @param {string | Error} [message] +* @returns {void} +*/ +export declare function match(string: string, regexp: RegExp, message?: string | Error); +/** +* Expects the `string` input not to match the regular expression. +* @param {string} string +* @param {RegExp} regexp +* @param {string | Error} [message] +* @returns {void} +*/ +export declare function doesNotMatch(string: string, regexp: RegExp, message?: string | Error); +export declare function fail(actual: unknown, expected?: unknown, message?: string | Error, operator?: string, stackStartFn?: Function): never; +export declare const CallTracker: typeof nodeAssert.CallTracker; +export declare const partialDeepStrictEqual: unknown; +export declare const strict: unknown; +declare const _default; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/assert.mjs b/worker/node_modules/unenv/dist/runtime/node/assert.mjs new file mode 100644 index 0000000000000000000000000000000000000000..226ff58345872ed9e16df3a1b1cfa25535af96d1 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/assert.mjs @@ -0,0 +1,680 @@ +import { isEqual as _ohashIsEqual } from "ohash/utils"; +import { notImplemented, notImplementedClass } from "../_internal/utils.mjs"; +const ERR_AMBIGUOUS_ARGUMENT = Error; +const ERR_INVALID_ARG_TYPE = Error; +const ERR_INVALID_ARG_VALUE = Error; +const ERR_INVALID_RETURN_VALUE = Error; +const ERR_MISSING_ARGS = Error; +export class AssertionError extends Error { + actual; + expected; + operator; + generatedMessage; + code = "ERR_ASSERTION"; + constructor(options) { + super(); + this.actual = options.actual; + this.expected = options.expected; + this.operator = options.operator || ""; + this.generatedMessage = options.message === undefined; + const stackStartFn = options.stackStartFn || fail; + Error.captureStackTrace?.(this, stackStartFn); + } +} +const inspect = (val, opts) => val; +const isDeepEqual = _ohashIsEqual; +const isDeepStrictEqual = _ohashIsEqual; +let warned = false; +const NO_EXCEPTION_SENTINEL = {}; +/** +* Pure assertion tests whether a value is truthy, as determined +* by !!value. +* @param {...any} args +* @returns {void} +*/ +export function ok(...args) { + innerOk(ok, args.length, ...args); +} +/** +* The equality assertion tests shallow, coercive equality with ==. +* @param {any} actual +* @param {any} expected +* @param {string | Error} [message] +* @returns {void} +*/ +export function equal(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS("actual", "expected"); + } + if (actual != expected && (!Number.isNaN(actual) || !Number.isNaN(expected))) { + innerFail({ + actual, + expected, + message, + operator: "==", + stackStartFn: equal + }); + } +} +/** +* The non-equality assertion tests for whether two objects are not +* equal with !=. +* @param {any} actual +* @param {any} expected +* @param {string | Error} [message] +* @returns {void} +*/ +export function notEqual(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS("actual", "expected"); + } + if (actual == expected || Number.isNaN(actual) && Number.isNaN(expected)) { + innerFail({ + actual, + expected, + message, + operator: "!=", + stackStartFn: notEqual + }); + } +} +/** +* The deep equivalence assertion tests a deep equality relation. +* @param {any} actual +* @param {any} expected +* @param {string | Error} [message] +* @returns {void} +*/ +export function deepEqual(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS("actual", "expected"); + } + if (!isDeepEqual(actual, expected)) { + innerFail({ + actual, + expected, + message, + operator: "deepEqual", + stackStartFn: deepEqual + }); + } +} +/** +* The deep non-equivalence assertion tests for any deep inequality. +* @param {any} actual +* @param {any} expected +* @param {string | Error} [message] +* @returns {void} +*/ +export function notDeepEqual(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS("actual", "expected"); + } + if (isDeepEqual(actual, expected)) { + innerFail({ + actual, + expected, + message, + operator: "notDeepEqual", + stackStartFn: notDeepEqual + }); + } +} +/** +* The deep strict equivalence assertion tests a deep strict equality +* relation. +* @param {any} actual +* @param {any} expected +* @param {string | Error} [message] +* @returns {void} +*/ +export function deepStrictEqual(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS("actual", "expected"); + } + if (!isDeepStrictEqual(actual, expected)) { + innerFail({ + actual, + expected, + message, + operator: "deepStrictEqual", + stackStartFn: deepStrictEqual + }); + } +} +/** +* The deep strict non-equivalence assertion tests for any deep strict +* inequality. +* @param {any} actual +* @param {any} expected +* @param {string | Error} [message] +* @returns {void} +*/ +export function notDeepStrictEqual(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS("actual", "expected"); + } + if (isDeepStrictEqual(actual, expected)) { + innerFail({ + actual, + expected, + message, + operator: "notDeepStrictEqual", + stackStartFn: notDeepStrictEqual + }); + } +} +/** +* The strict equivalence assertion tests a strict equality relation. +* @param {any} actual +* @param {any} expected +* @param {string | Error} [message] +* @returns {void} +*/ +export function strictEqual(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS("actual", "expected"); + } + if (!Object.is(actual, expected)) { + innerFail({ + actual, + expected, + message, + operator: "strictEqual", + stackStartFn: strictEqual + }); + } +} +/** +* The strict non-equivalence assertion tests for any strict inequality. +* @param {any} actual +* @param {any} expected +* @param {string | Error} [message] +* @returns {void} +*/ +export function notStrictEqual(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS("actual", "expected"); + } + if (Object.is(actual, expected)) { + innerFail({ + actual, + expected, + message, + operator: "notStrictEqual", + stackStartFn: notStrictEqual + }); + } +} +/** +* Expects the function `promiseFn` to throw an error. +*/ +export function throws(promiseFn, ...args) { + expectsError(throws, getActual(promiseFn), ...args); +} +/** +* Expects `promiseFn` function or its value to reject. +*/ +export async function rejects(promiseFn, ...args) { + expectsError(rejects, await waitForActual(promiseFn), ...args); +} +/** +* Asserts that the function `fn` does not throw an error. +*/ +export function doesNotThrow(fn, ...args) { + expectsNoError(doesNotThrow, getActual(fn), ...args); +} +/** +* Expects `fn` or its value to not reject. +*/ +export async function doesNotReject(fn, ...args) { + expectsNoError(doesNotReject, await waitForActual(fn), ...args); +} +/** +* Throws `value` if the value is not `null` or `undefined`. +* @param {any} err +* @returns {void} +*/ +export function ifError(err) { + if (err !== null && err !== undefined) { + let message = "ifError got unwanted exception: "; + if (typeof err === "object" && typeof err.message === "string") { + if (err.message.length === 0 && err.constructor) { + message += err.constructor.name; + } else { + message += err.message; + } + } else { + message += inspect(err); + } + const newErr = new AssertionError({ + actual: err, + expected: null, + operator: "ifError", + message, + stackStartFn: ifError + }); + const origStack = err?.stack; + if (typeof origStack === "string") { + const origStackStart = origStack.indexOf("\n at"); + if (origStackStart !== -1) { + const originalFrames = origStack.slice(origStackStart + 1).split("\n"); + let newFrames = (newErr.stack || "").split("\n"); + for (const errFrame of originalFrames) { + const pos = newFrames.indexOf(errFrame); + if (pos !== -1) { + newFrames = newFrames.slice(0, pos); + break; + } + } + const stackStart = newFrames.join("\n"); + const stackEnd = originalFrames.join("\n"); + newErr.stack = `${stackStart}\n${stackEnd}`; + } + } + throw newErr; + } +} +/** +* Expects the `string` input to match the regular expression. +* @param {string} string +* @param {RegExp} regexp +* @param {string | Error} [message] +* @returns {void} +*/ +export function match(string, regexp, message) { + internalMatch(string, regexp, message, match); +} +/** +* Expects the `string` input not to match the regular expression. +* @param {string} string +* @param {RegExp} regexp +* @param {string | Error} [message] +* @returns {void} +*/ +export function doesNotMatch(string, regexp, message) { + internalMatch(string, regexp, message, doesNotMatch); +} +export function fail(actual, expected, message, operator, stackStartFn) { + const argsLen = arguments.length; + let internalMessage = false; + if (actual == null && argsLen <= 1) { + internalMessage = true; + message = "Failed"; + } else if (argsLen === 1) { + message = actual; + actual = undefined; + } else { + if (warned === false) { + warned = true; + process.emitWarning("assert.fail() with more than one argument is deprecated. " + "Please use assert.strictEqual() instead or only pass a message.", "DeprecationWarning", "DEP0094"); + } + if (argsLen === 2) operator = "!="; + } + if (message instanceof Error) throw message; + const errArgs = { + actual, + expected, + operator: operator === undefined ? "fail" : operator, + stackStartFn: stackStartFn || fail, + message + }; + const err = new AssertionError(errArgs); + if (internalMessage) { + err.generatedMessage = true; + } + throw err; +} +function innerFail(obj) { + if (obj.message instanceof Error) throw obj.message; + throw new AssertionError(obj); +} +function innerOk(fn, argLen, value, message) { + if (!value) { + let generatedMessage = false; + if (argLen === 0) { + generatedMessage = true; + message = "No value argument passed to `assert.ok()`"; + } else if (message == null) { + generatedMessage = true; + message = ""; + } else if (message instanceof Error) { + throw message; + } + const err = new AssertionError({ + actual: value, + expected: true, + message, + operator: "==", + stackStartFn: fn + }); + err.generatedMessage = generatedMessage; + throw err; + } +} +class Comparison { + constructor(obj, keys, actual) { + for (const key of keys) { + if (key in obj) { + if (actual !== undefined && typeof actual[key] === "string" && obj[key] instanceof RegExp && obj[key].exec(actual[key]) !== null) { + this[key] = actual[key]; + } else { + this[key] = obj[key]; + } + } + } + } +} +function compareExceptionKey(actual, expected, key, message, keys, fn) { + if (!(key in actual) || !isDeepStrictEqual(actual[key], expected[key])) { + if (!message) { + const a = new Comparison(actual, keys); + const b = new Comparison(expected, keys, actual); + const err = new AssertionError({ + actual: a, + expected: b, + operator: "deepStrictEqual", + stackStartFn: fn + }); + err.actual = actual; + err.expected = expected; + err.operator = fn.name; + throw err; + } + innerFail({ + actual, + expected, + message, + operator: fn.name, + stackStartFn: fn + }); + } +} +function expectedException(actual, expected, message, fn) { + let generatedMessage = false; + let throwError = false; + if (typeof expected !== "function") { + if (expected instanceof RegExp) { + const str = String(actual); + if (RegExp.prototype.exec.call(expected, str) !== null) return; + if (!message) { + generatedMessage = true; + message = "The input did not match the regular expression " + `${inspect(expected)}. Input:\n\n${inspect(str)}\n`; + } + throwError = true; + } else if (typeof actual !== "object" || actual === null) { + const err = new AssertionError({ + actual, + expected, + message, + operator: "deepStrictEqual", + stackStartFn: fn + }); + err.operator = fn.name; + throw err; + } else { + const keys = Object.keys(expected); + if (expected instanceof Error) { + keys.push("name", "message"); + } else if (keys.length === 0) { + throw new ERR_INVALID_ARG_VALUE( + "error", + expected, + // @ts-expect-error + "may not be an empty object" +); + } + for (const key of keys) { + if (typeof actual[key] === "string" && expected[key] instanceof RegExp && expected[key].exec(actual[key]) !== null) { + continue; + } + compareExceptionKey(actual, expected, key, message, keys, fn); + } + return; + } + } else if (expected.prototype !== undefined && actual instanceof expected) { + return; + } else if (expected instanceof Error) { + if (!message) { + generatedMessage = true; + message = "The error is expected to be an instance of " + `"${expected.name}". Received `; + if (actual instanceof Error) { + const name = actual.constructor && actual.constructor.name || actual.name; + if (expected.name === name) { + message += "an error with identical name but a different prototype."; + } else { + message += `"${name}"`; + } + if (actual.message) { + message += `\n\nError message:\n\n${actual.message}`; + } + } else { + message += `"${inspect(actual, { depth: -1 })}"`; + } + } + throwError = true; + } else { + const res = Reflect.apply(expected, {}, [actual]); + if (res !== true) { + if (!message) { + generatedMessage = true; + const name = expected.name ? `"${expected.name}" ` : ""; + message = `The ${name}validation function is expected to return` + ` "true". Received ${inspect(res)}`; + if (actual instanceof Error) { + message += `\n\nCaught error:\n\n${actual}`; + } + } + throwError = true; + } + } + if (throwError) { + const err = new AssertionError({ + actual, + expected, + message, + operator: fn.name, + stackStartFn: fn + }); + err.generatedMessage = generatedMessage; + throw err; + } +} +function getActual(fn) { + try { + fn(); + } catch (error_) { + return error_; + } + return NO_EXCEPTION_SENTINEL; +} +function checkIsPromise(obj) { + return obj instanceof Promise || obj !== null && typeof obj === "object" && typeof obj.then === "function" && typeof obj.catch === "function"; +} +function internalMatch(string, regexp, message, fn) { + if (!(regexp instanceof RegExp)) { + throw new ERR_INVALID_ARG_TYPE("regexp", "RegExp", regexp); + } + const match = fn === assert.match; + if (typeof string !== "string" || regexp.exec(string) !== null !== match) { + if (message instanceof Error) { + throw message; + } + const generatedMessage = !message; + message = message || (typeof string === "string" ? (match ? "The input did not match the regular expression " : "The input was expected to not match the regular expression ") + `${inspect(regexp)}. Input:\n\n${inspect(string)}\n` : "The \"string\" argument must be of type string. Received type " + `${typeof string} (${inspect(string)})`); + const err = new AssertionError({ + actual: string, + expected: regexp, + message, + operator: fn?.name, + stackStartFn: fn + }); + err.generatedMessage = generatedMessage; + throw err; + } +} +async function waitForActual(promiseFn) { + let resultPromise; + if (typeof promiseFn === "function") { + resultPromise = promiseFn(); + if (!checkIsPromise(resultPromise)) { + throw new ERR_INVALID_RETURN_VALUE( + "instance of Promise", + "promiseFn", + // @ts-expect-error + resultPromise +); + } + } else if (checkIsPromise(promiseFn)) { + resultPromise = promiseFn; + } else { + throw new ERR_INVALID_ARG_TYPE( + "promiseFn", + ["Function", "Promise"], + // @ts-expect-error + promiseFn +); + } + try { + await resultPromise; + } catch (error_) { + return error_; + } + return NO_EXCEPTION_SENTINEL; +} +function expectsError(stackStartFn, actual, error, message) { + if (typeof error === "string") { + if (arguments.length === 4) { + throw new ERR_INVALID_ARG_TYPE( + "error", + [ + "Object", + "Error", + "Function", + "RegExp" + ], + // @ts-expect-error + error +); + } + if (typeof actual === "object" && actual !== null) { + if (actual?.message === error) { + throw new ERR_AMBIGUOUS_ARGUMENT( + "error/message", + // @ts-expect-error + `The error message "${actual.message}" is identical to the message.` +); + } + } else if (actual === error) { + throw new ERR_AMBIGUOUS_ARGUMENT( + "error/message", + // @ts-expect-error + `The error "${actual}" is identical to the message.` +); + } + message = error; + error = undefined; + } else if (error != null && typeof error !== "object" && typeof error !== "function") { + throw new ERR_INVALID_ARG_TYPE( + "error", + [ + "Object", + "Error", + "Function", + "RegExp" + ], + // @ts-expect-error + error +); + } + if (actual === NO_EXCEPTION_SENTINEL) { + let details = ""; + if (error && error.name) { + details += ` (${error.name})`; + } + details += message ? `: ${message}` : "."; + const fnType = stackStartFn === assert.rejects ? "rejection" : "exception"; + innerFail({ + actual: undefined, + expected: error, + operator: stackStartFn.name, + message: `Missing expected ${fnType}${details}`, + stackStartFn + }); + } + if (!error) return; + expectedException(actual, error, message, stackStartFn); +} +function hasMatchingError(actual, expected) { + if (typeof expected !== "function") { + if (expected instanceof RegExp) { + const str = String(actual); + return RegExp.prototype.exec.call(expected, str) !== null; + } + throw new ERR_INVALID_ARG_TYPE( + "expected", + ["Function", "RegExp"], + // @ts-expect-error + expected +); + } + if (expected.prototype !== undefined && actual instanceof expected) { + return true; + } + if (expected instanceof Error) { + return false; + } + return Reflect.apply(expected, {}, [actual]) === true; +} +function expectsNoError(stackStartFn, actual, error, message) { + if (actual === NO_EXCEPTION_SENTINEL) return; + if (typeof error === "string") { + message = error; + error = undefined; + } + if (!error || hasMatchingError(actual, error)) { + const details = message ? `: ${message}` : "."; + const fnType = stackStartFn === assert.doesNotReject ? "rejection" : "exception"; + innerFail({ + actual, + expected: error, + operator: stackStartFn?.name, + message: `Got unwanted ${fnType}${details}\n` + `Actual message: "${actual && actual.message}"`, + stackStartFn + }); + } + throw actual; +} +const assert = Object.assign(ok, {}); +export const CallTracker = /*@__PURE__*/ notImplementedClass("asset.CallTracker"); +export const partialDeepStrictEqual = /* @__PURE__ */ notImplemented("assert.partialDeepStrictEqual"); +assert.fail = fail; +assert.ok = ok; +assert.equal = equal; +assert.notEqual = notEqual; +assert.deepEqual = deepEqual; +assert.notDeepEqual = notDeepEqual; +assert.deepStrictEqual = deepStrictEqual; +assert.notDeepStrictEqual = notDeepStrictEqual; +assert.strictEqual = strictEqual; +assert.notStrictEqual = notStrictEqual; +assert.throws = throws; +assert.rejects = rejects; +assert.doesNotThrow = doesNotThrow; +assert.doesNotReject = doesNotReject; +assert.ifError = ifError; +assert.match = match; +assert.doesNotMatch = doesNotMatch; +assert.partialDeepStrictEqual = partialDeepStrictEqual; +assert.AssertionError = AssertionError; +assert.CallTracker = CallTracker; +export const strict = Object.assign(function _strict(...args) { + innerOk(strict, args.length, ...args); +}, assert, { + equal: assert.strictEqual, + deepEqual: assert.deepStrictEqual, + notEqual: assert.notStrictEqual, + notDeepEqual: assert.notDeepStrictEqual +}); +assert.strict = strict; +assert.strict.strict = assert.strict; +export default assert; diff --git a/worker/node_modules/unenv/dist/runtime/node/assert/strict.d.mts b/worker/node_modules/unenv/dist/runtime/node/assert/strict.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..40e690d46c36dc855c87e88e22ca10135b284e77 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/assert/strict.d.mts @@ -0,0 +1,4 @@ +import type nodeAssert from "node:assert"; +export { AssertionError, CallTracker, strict, fail, ok, throws, rejects, doesNotThrow, doesNotReject, ifError, match, doesNotMatch, notDeepStrictEqual, notDeepStrictEqual as notDeepEqual, strictEqual, strictEqual as equal, notStrictEqual, notStrictEqual as notEqual, deepStrictEqual, deepStrictEqual as deepEqual, partialDeepStrictEqual } from "../assert.mjs"; +declare const _default: typeof nodeAssert.strict; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/assert/strict.mjs b/worker/node_modules/unenv/dist/runtime/node/assert/strict.mjs new file mode 100644 index 0000000000000000000000000000000000000000..21d331d86db9b21538c760e858d6016fbaaeef0c --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/assert/strict.mjs @@ -0,0 +1,25 @@ +import { AssertionError, CallTracker, strict, fail, ok, throws, rejects, doesNotThrow, doesNotReject, ifError, match, doesNotMatch, notDeepStrictEqual, notDeepStrictEqual as notDeepEqual, strictEqual, strictEqual as equal, notStrictEqual, notStrictEqual as notEqual, deepStrictEqual, deepStrictEqual as deepEqual, partialDeepStrictEqual } from "../assert.mjs"; +export { AssertionError, CallTracker, strict, fail, ok, throws, rejects, doesNotThrow, doesNotReject, ifError, match, doesNotMatch, notDeepStrictEqual, notDeepStrictEqual as notDeepEqual, strictEqual, strictEqual as equal, notStrictEqual, notStrictEqual as notEqual, deepStrictEqual, deepStrictEqual as deepEqual, partialDeepStrictEqual } from "../assert.mjs"; +export default Object.assign(ok, { + AssertionError, + CallTracker, + strict, + fail, + ok, + throws, + rejects, + doesNotThrow, + doesNotReject, + ifError, + match, + doesNotMatch, + notDeepStrictEqual, + notDeepEqual, + strictEqual, + equal, + notStrictEqual, + notEqual, + deepStrictEqual, + deepEqual, + partialDeepStrictEqual +}); diff --git a/worker/node_modules/unenv/dist/runtime/node/async_hooks.d.mts b/worker/node_modules/unenv/dist/runtime/node/async_hooks.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..5d87b9465e9ebef411bbb840729157a591cba2d8 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/async_hooks.d.mts @@ -0,0 +1,5 @@ +export { AsyncLocalStorage } from "./internal/async_hooks/async-local-storage.mjs"; +export { AsyncResource } from "./internal/async_hooks/async-resource.mjs"; +export * from "./internal/async_hooks/async-hook.mjs"; +declare const _default: {}; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/async_hooks.mjs b/worker/node_modules/unenv/dist/runtime/node/async_hooks.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1db8f696f6c83f613b864511e730659b12437113 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/async_hooks.mjs @@ -0,0 +1,15 @@ +import { AsyncLocalStorage } from "./internal/async_hooks/async-local-storage.mjs"; +import { AsyncResource } from "./internal/async_hooks/async-resource.mjs"; +import { asyncWrapProviders, createHook, executionAsyncId, executionAsyncResource, triggerAsyncId } from "./internal/async_hooks/async-hook.mjs"; +export { AsyncLocalStorage } from "./internal/async_hooks/async-local-storage.mjs"; +export { AsyncResource } from "./internal/async_hooks/async-resource.mjs"; +export * from "./internal/async_hooks/async-hook.mjs"; +export default { + asyncWrapProviders, + AsyncLocalStorage, + AsyncResource, + createHook, + executionAsyncId, + executionAsyncResource, + triggerAsyncId +}; diff --git a/worker/node_modules/unenv/dist/runtime/node/buffer.d.mts b/worker/node_modules/unenv/dist/runtime/node/buffer.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..3a82b22f410851f9f3131b207805e62cc7c672d2 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/buffer.d.mts @@ -0,0 +1,17 @@ +import type nodeBuffer from "node:buffer"; +export { kMaxLength, INSPECT_MAX_BYTES, SlowBuffer } from "./internal/buffer/buffer.mjs"; +export declare const Buffer: unknown; +export { File } from "./internal/buffer/file.mjs"; +export declare const Blob: typeof nodeBuffer.Blob; +export declare const resolveObjectURL: unknown; +export declare const transcode: unknown; +export declare const isUtf8: unknown; +export declare const isAscii: unknown; +export declare const btoa: unknown; +export declare const atob: unknown; +export declare const kStringMaxLength = 0; +export declare const constants: {}; +declare const _default: { + SlowBuffer: typeof nodeBuffer.SlowBuffer +}; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/buffer.mjs b/worker/node_modules/unenv/dist/runtime/node/buffer.mjs new file mode 100644 index 0000000000000000000000000000000000000000..bc7c5706328d030c01d7747eef65fddcccd76141 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/buffer.mjs @@ -0,0 +1,34 @@ +import { notImplemented } from "../_internal/utils.mjs"; +import { Buffer as _Buffer, kMaxLength, INSPECT_MAX_BYTES, SlowBuffer } from "./internal/buffer/buffer.mjs"; +import { File } from "./internal/buffer/file.mjs"; +export { kMaxLength, INSPECT_MAX_BYTES, SlowBuffer } from "./internal/buffer/buffer.mjs"; +export const Buffer = globalThis.Buffer || _Buffer; +export { File } from "./internal/buffer/file.mjs"; +export const Blob = globalThis.Blob; +export const resolveObjectURL = /*@__PURE__*/ notImplemented("buffer.resolveObjectURL"); +export const transcode = /*@__PURE__*/ notImplemented("buffer.transcode"); +export const isUtf8 = /*@__PURE__*/ notImplemented("buffer.isUtf8"); +export const isAscii = /*@__PURE__*/ notImplemented("buffer.isAscii"); +export const btoa = globalThis.btoa.bind(globalThis); +export const atob = globalThis.atob.bind(globalThis); +export const kStringMaxLength = 0; +export const constants = { + MAX_LENGTH: kMaxLength, + MAX_STRING_LENGTH: kStringMaxLength +}; +export default { + Buffer, + SlowBuffer, + kMaxLength, + INSPECT_MAX_BYTES, + Blob, + resolveObjectURL, + transcode, + btoa, + atob, + kStringMaxLength, + constants, + isUtf8, + isAscii, + File +}; diff --git a/worker/node_modules/unenv/dist/runtime/node/child_process.d.mts b/worker/node_modules/unenv/dist/runtime/node/child_process.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..6668ff976e7ad45fdb16e9a4d7213801fd181aa0 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/child_process.d.mts @@ -0,0 +1,12 @@ +import type nodeChildProcess from "node:child_process"; +export declare const ChildProcess: typeof nodeChildProcess.ChildProcess; +export declare const _forkChild: unknown; +export declare const exec: typeof nodeChildProcess.exec; +export declare const execFile: typeof nodeChildProcess.execFile; +export declare const execFileSync: typeof nodeChildProcess.execFileSync; +export declare const execSync: typeof nodeChildProcess.execSync; +export declare const fork: typeof nodeChildProcess.fork; +export declare const spawn: typeof nodeChildProcess.spawn; +export declare const spawnSync: typeof nodeChildProcess.spawnSync; +declare const _default: typeof nodeChildProcess; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/child_process.mjs b/worker/node_modules/unenv/dist/runtime/node/child_process.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8de3a0bf9d60ca944c7a17ace1e8d2d18c0396c9 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/child_process.mjs @@ -0,0 +1,21 @@ +import { notImplemented, notImplementedClass } from "../_internal/utils.mjs"; +export const ChildProcess = /*@__PURE__*/ notImplementedClass("child_process.ChildProcess"); +export const _forkChild = /*@__PURE__*/ notImplemented("child_process.ChildProcess"); +export const exec = /*@__PURE__*/ notImplemented("child_process.exec"); +export const execFile = /*@__PURE__*/ notImplemented("child_process.execFile"); +export const execFileSync = /*@__PURE__*/ notImplemented("child_process.execFileSync"); +export const execSync = /*@__PURE__*/ notImplemented("child_process.execSyn"); +export const fork = /*@__PURE__*/ notImplemented("child_process.fork"); +export const spawn = /*@__PURE__*/ notImplemented("child_process.spawn"); +export const spawnSync = /*@__PURE__*/ notImplemented("child_process.spawnSync"); +export default { + ChildProcess, + _forkChild, + exec, + execFile, + execFileSync, + execSync, + fork, + spawn, + spawnSync +}; diff --git a/worker/node_modules/unenv/dist/runtime/node/cluster.d.mts b/worker/node_modules/unenv/dist/runtime/node/cluster.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..bbe54f6ca9fe0f4a1fe71c9bb3a227b4a80fabc5 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/cluster.d.mts @@ -0,0 +1,32 @@ +import type nodeCluster from "node:cluster"; +import type { Worker as NodeClusterWorker } from "node:cluster"; +import { EventEmitter } from "node:events"; +export declare const SCHED_NONE: typeof nodeCluster.SCHED_NONE; +export declare const SCHED_RR: typeof nodeCluster.SCHED_RR; +export declare const isMaster: typeof nodeCluster.isMaster; +export declare const isPrimary: typeof nodeCluster.isPrimary; +export declare const isWorker: typeof nodeCluster.isWorker; +export declare const schedulingPolicy: typeof nodeCluster.schedulingPolicy; +export declare const settings: typeof nodeCluster.settings; +export declare const workers: typeof nodeCluster.workers; +export declare const fork: typeof nodeCluster.fork; +export declare const disconnect: typeof nodeCluster.disconnect; +export declare const setupPrimary: typeof nodeCluster.setupPrimary; +export declare const setupMaster: typeof nodeCluster.setupMaster; +export declare const _events: unknown; +export declare const _eventsCount = 0; +export declare const _maxListeners = 0; +export declare class Worker extends EventEmitter implements NodeClusterWorker { + _connected: boolean; + id: number; + get process(): any; + get exitedAfterDisconnect(); + isConnected(): boolean; + isDead(): boolean; + send(message: any, sendHandle?: any, options?: any, callback?: any): boolean; + kill(signal?: string): void; + destroy(signal?: string): void; + disconnect(): void; +} +declare const _default; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/cluster.mjs b/worker/node_modules/unenv/dist/runtime/node/cluster.mjs new file mode 100644 index 0000000000000000000000000000000000000000..51091dcd806d4a0b2ec045c2b2d643f6a7a82f25 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/cluster.mjs @@ -0,0 +1,69 @@ +import { EventEmitter } from "node:events"; +import { notImplemented } from "../_internal/utils.mjs"; +export const SCHED_NONE = 1; +export const SCHED_RR = 2; +export const isMaster = true; +export const isPrimary = true; +export const isWorker = false; +export const schedulingPolicy = SCHED_RR; +export const settings = {}; +export const workers = {}; +export const fork = /*@__PURE__*/ notImplemented("cluster.fork"); +export const disconnect = /*@__PURE__*/ notImplemented("cluster.disconnect"); +export const setupPrimary = /*@__PURE__*/ notImplemented("cluster.setupPrimary"); +export const setupMaster = /*@__PURE__*/ notImplemented("cluster.setupMaster"); +export const _events = []; +export const _eventsCount = 0; +export const _maxListeners = 0; +export class Worker extends EventEmitter { + _connected = false; + id = 0; + get process() { + return globalThis.process; + } + get exitedAfterDisconnect() { + return this._connected; + } + isConnected() { + return this._connected; + } + isDead() { + return true; + } + send(message, sendHandle, options, callback) { + return false; + } + kill(signal) { + this._connected = false; + } + destroy(signal) { + this._connected = false; + } + disconnect() { + this._connected = false; + } +} +class _Cluster extends EventEmitter { + Worker = Worker; + isMaster = isMaster; + isPrimary = isPrimary; + isWorker = isWorker; + SCHED_NONE = SCHED_NONE; + SCHED_RR = SCHED_RR; + schedulingPolicy = SCHED_RR; + settings = settings; + workers = workers; + setupPrimary() { + return setupPrimary(); + } + setupMaster() { + return setupPrimary(); + } + disconnect() { + return disconnect(); + } + fork() { + return fork(); + } +} +export default new _Cluster(); diff --git a/worker/node_modules/unenv/dist/runtime/node/console.d.mts b/worker/node_modules/unenv/dist/runtime/node/console.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..62e8a2e13fa2dfd985ecf0d0a5a20146214addcd --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/console.d.mts @@ -0,0 +1,35 @@ +import type nodeConsole from "node:console"; +import { Writable } from "node:stream"; +export declare const _ignoreErrors: boolean; +export declare const _stderr: Writable; +export declare const _stdout: Writable; +export declare const log: typeof nodeConsole.log; +export declare const info: typeof nodeConsole.info; +export declare const trace: typeof nodeConsole.trace; +export declare const debug: typeof nodeConsole.debug; +export declare const table: typeof nodeConsole.table; +export declare const error: typeof nodeConsole.error; +export declare const warn: typeof nodeConsole.warn; +export declare const createTask: unknown; +export declare const assert: typeof nodeConsole.assert; +export declare const clear: typeof nodeConsole.clear; +export declare const count: typeof nodeConsole.count; +export declare const countReset: typeof nodeConsole.countReset; +export declare const dir: typeof nodeConsole.dir; +export declare const dirxml: typeof nodeConsole.dirxml; +export declare const group: typeof nodeConsole.group; +export declare const groupEnd: typeof nodeConsole.groupEnd; +export declare const groupCollapsed: typeof nodeConsole.groupCollapsed; +export declare const profile: typeof nodeConsole.profile; +export declare const profileEnd: typeof nodeConsole.profileEnd; +export declare const time: typeof nodeConsole.time; +export declare const timeEnd: typeof nodeConsole.timeEnd; +export declare const timeLog: typeof nodeConsole.timeLog; +export declare const timeStamp: typeof nodeConsole.timeStamp; +export declare const Console: typeof nodeConsole.Console; +export declare const _times: unknown; +export declare function context(); +export declare const _stdoutErrorHandler: unknown; +export declare const _stderrErrorHandler: unknown; +declare const _default: {}; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/console.mjs b/worker/node_modules/unenv/dist/runtime/node/console.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6375852f90480a2a34ab3b9fedd8dbe3453676ff --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/console.mjs @@ -0,0 +1,70 @@ +import { Writable } from "node:stream"; +import noop from "../mock/noop.mjs"; +import { notImplemented, notImplementedClass } from "../_internal/utils.mjs"; +const _console = globalThis.console; +export const _ignoreErrors = true; +export const _stderr = new Writable(); +export const _stdout = new Writable(); +export const log = _console?.log ?? noop; +export const info = _console?.info ?? log; +export const trace = _console?.trace ?? info; +export const debug = _console?.debug ?? log; +export const table = _console?.table ?? log; +export const error = _console?.error ?? log; +export const warn = _console?.warn ?? error; +export const createTask = _console?.createTask ?? /*@__PURE__*/ notImplemented("console.createTask"); +export const assert = /*@__PURE__*/ notImplemented("console.assert"); +export const clear = _console?.clear ?? noop; +export const count = _console?.count ?? noop; +export const countReset = _console?.countReset ?? noop; +export const dir = _console?.dir ?? noop; +export const dirxml = _console?.dirxml ?? noop; +export const group = _console?.group ?? noop; +export const groupEnd = _console?.groupEnd ?? noop; +export const groupCollapsed = _console?.groupCollapsed ?? noop; +export const profile = _console?.profile ?? noop; +export const profileEnd = _console?.profileEnd ?? noop; +export const time = _console?.time ?? noop; +export const timeEnd = _console?.timeEnd ?? noop; +export const timeLog = _console?.timeLog ?? noop; +export const timeStamp = _console?.timeStamp ?? noop; +export const Console = _console?.Console ?? /*@__PURE__*/ notImplementedClass("console.Console"); +export const _times = /*@__PURE__*/ new Map(); +export function context() { + return _console; +} +export const _stdoutErrorHandler = noop; +export const _stderrErrorHandler = noop; +export default { + _times, + _ignoreErrors, + _stdoutErrorHandler, + _stderrErrorHandler, + _stdout, + _stderr, + assert, + clear, + Console, + count, + countReset, + debug, + dir, + dirxml, + error, + context, + createTask, + group, + groupEnd, + groupCollapsed, + info, + log, + profile, + profileEnd, + table, + time, + timeEnd, + timeLog, + timeStamp, + trace, + warn +}; diff --git a/worker/node_modules/unenv/dist/runtime/node/constants.d.mts b/worker/node_modules/unenv/dist/runtime/node/constants.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..65a3b5ff16b4192e934d7e8c012b833b032da9ad --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/constants.d.mts @@ -0,0 +1,8 @@ +export * from "./internal/fs/constants.mjs"; +export { OPENSSL_VERSION_NUMBER, SSL_OP_ALL, SSL_OP_ALLOW_NO_DHE_KEX, SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION, SSL_OP_CIPHER_SERVER_PREFERENCE, SSL_OP_CISCO_ANYCONNECT, SSL_OP_COOKIE_EXCHANGE, SSL_OP_CRYPTOPRO_TLSEXT_BUG, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS, SSL_OP_LEGACY_SERVER_CONNECT, SSL_OP_NO_COMPRESSION, SSL_OP_NO_ENCRYPT_THEN_MAC, SSL_OP_NO_QUERY_MTU, SSL_OP_NO_RENEGOTIATION, SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION, SSL_OP_NO_SSLv2, SSL_OP_NO_SSLv3, SSL_OP_NO_TICKET, SSL_OP_NO_TLSv1, SSL_OP_NO_TLSv1_1, SSL_OP_NO_TLSv1_2, SSL_OP_NO_TLSv1_3, SSL_OP_PRIORITIZE_CHACHA, SSL_OP_TLS_ROLLBACK_BUG, ENGINE_METHOD_RSA, ENGINE_METHOD_DSA, ENGINE_METHOD_DH, ENGINE_METHOD_RAND, ENGINE_METHOD_EC, ENGINE_METHOD_CIPHERS, ENGINE_METHOD_DIGESTS, ENGINE_METHOD_PKEY_METHS, ENGINE_METHOD_PKEY_ASN1_METHS, ENGINE_METHOD_ALL, ENGINE_METHOD_NONE, DH_CHECK_P_NOT_SAFE_PRIME, DH_CHECK_P_NOT_PRIME, DH_UNABLE_TO_CHECK_GENERATOR, DH_NOT_SUITABLE_GENERATOR, RSA_PKCS1_PADDING, RSA_NO_PADDING, RSA_PKCS1_OAEP_PADDING, RSA_X931_PADDING, RSA_PKCS1_PSS_PADDING, RSA_PSS_SALTLEN_DIGEST, RSA_PSS_SALTLEN_MAX_SIGN, RSA_PSS_SALTLEN_AUTO, defaultCoreCipherList, TLS1_VERSION, TLS1_1_VERSION, TLS1_2_VERSION, TLS1_3_VERSION, POINT_CONVERSION_COMPRESSED, POINT_CONVERSION_UNCOMPRESSED, POINT_CONVERSION_HYBRID } from "./internal/crypto/constants.mjs"; +export declare const; +export declare const; +export declare const; +export declare const; +declare const _default: {}; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/constants.mjs b/worker/node_modules/unenv/dist/runtime/node/constants.mjs new file mode 100644 index 0000000000000000000000000000000000000000..23de29a573ce73b4d1642e86618e37847130c459 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/constants.mjs @@ -0,0 +1,247 @@ +import { errno, priority, signals, dlopen } from "./internal/os/constants.mjs"; +import { UV_FS_SYMLINK_DIR, UV_FS_SYMLINK_JUNCTION, O_RDONLY, O_WRONLY, O_RDWR, UV_DIRENT_UNKNOWN, UV_DIRENT_FILE, UV_DIRENT_DIR, UV_DIRENT_LINK, UV_DIRENT_FIFO, UV_DIRENT_SOCKET, UV_DIRENT_CHAR, UV_DIRENT_BLOCK, EXTENSIONLESS_FORMAT_JAVASCRIPT, EXTENSIONLESS_FORMAT_WASM, S_IFMT, S_IFREG, S_IFDIR, S_IFCHR, S_IFBLK, S_IFIFO, S_IFLNK, S_IFSOCK, O_CREAT, O_EXCL, UV_FS_O_FILEMAP, O_NOCTTY, O_TRUNC, O_APPEND, O_DIRECTORY, O_NOATIME, O_NOFOLLOW, O_SYNC, O_DSYNC, O_DIRECT, O_NONBLOCK, S_IRWXU, S_IRUSR, S_IWUSR, S_IXUSR, S_IRWXG, S_IRGRP, S_IWGRP, S_IXGRP, S_IRWXO, S_IROTH, S_IWOTH, S_IXOTH, F_OK, R_OK, W_OK, X_OK, UV_FS_COPYFILE_EXCL, COPYFILE_EXCL, UV_FS_COPYFILE_FICLONE, COPYFILE_FICLONE, UV_FS_COPYFILE_FICLONE_FORCE, COPYFILE_FICLONE_FORCE } from "./internal/fs/constants.mjs"; +import { OPENSSL_VERSION_NUMBER, SSL_OP_ALL, SSL_OP_ALLOW_NO_DHE_KEX, SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION, SSL_OP_CIPHER_SERVER_PREFERENCE, SSL_OP_CISCO_ANYCONNECT, SSL_OP_COOKIE_EXCHANGE, SSL_OP_CRYPTOPRO_TLSEXT_BUG, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS, SSL_OP_LEGACY_SERVER_CONNECT, SSL_OP_NO_COMPRESSION, SSL_OP_NO_ENCRYPT_THEN_MAC, SSL_OP_NO_QUERY_MTU, SSL_OP_NO_RENEGOTIATION, SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION, SSL_OP_NO_SSLv2, SSL_OP_NO_SSLv3, SSL_OP_NO_TICKET, SSL_OP_NO_TLSv1, SSL_OP_NO_TLSv1_1, SSL_OP_NO_TLSv1_2, SSL_OP_NO_TLSv1_3, SSL_OP_PRIORITIZE_CHACHA, SSL_OP_TLS_ROLLBACK_BUG, ENGINE_METHOD_RSA, ENGINE_METHOD_DSA, ENGINE_METHOD_DH, ENGINE_METHOD_RAND, ENGINE_METHOD_EC, ENGINE_METHOD_CIPHERS, ENGINE_METHOD_DIGESTS, ENGINE_METHOD_PKEY_METHS, ENGINE_METHOD_PKEY_ASN1_METHS, ENGINE_METHOD_ALL, ENGINE_METHOD_NONE, DH_CHECK_P_NOT_SAFE_PRIME, DH_CHECK_P_NOT_PRIME, DH_UNABLE_TO_CHECK_GENERATOR, DH_NOT_SUITABLE_GENERATOR, RSA_PKCS1_PADDING, RSA_NO_PADDING, RSA_PKCS1_OAEP_PADDING, RSA_X931_PADDING, RSA_PKCS1_PSS_PADDING, RSA_PSS_SALTLEN_DIGEST, RSA_PSS_SALTLEN_MAX_SIGN, RSA_PSS_SALTLEN_AUTO, defaultCoreCipherList, TLS1_VERSION, TLS1_1_VERSION, TLS1_2_VERSION, TLS1_3_VERSION, POINT_CONVERSION_COMPRESSED, POINT_CONVERSION_UNCOMPRESSED, POINT_CONVERSION_HYBRID } from "./internal/crypto/constants.mjs"; +export * from "./internal/fs/constants.mjs"; +export { OPENSSL_VERSION_NUMBER, SSL_OP_ALL, SSL_OP_ALLOW_NO_DHE_KEX, SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION, SSL_OP_CIPHER_SERVER_PREFERENCE, SSL_OP_CISCO_ANYCONNECT, SSL_OP_COOKIE_EXCHANGE, SSL_OP_CRYPTOPRO_TLSEXT_BUG, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS, SSL_OP_LEGACY_SERVER_CONNECT, SSL_OP_NO_COMPRESSION, SSL_OP_NO_ENCRYPT_THEN_MAC, SSL_OP_NO_QUERY_MTU, SSL_OP_NO_RENEGOTIATION, SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION, SSL_OP_NO_SSLv2, SSL_OP_NO_SSLv3, SSL_OP_NO_TICKET, SSL_OP_NO_TLSv1, SSL_OP_NO_TLSv1_1, SSL_OP_NO_TLSv1_2, SSL_OP_NO_TLSv1_3, SSL_OP_PRIORITIZE_CHACHA, SSL_OP_TLS_ROLLBACK_BUG, ENGINE_METHOD_RSA, ENGINE_METHOD_DSA, ENGINE_METHOD_DH, ENGINE_METHOD_RAND, ENGINE_METHOD_EC, ENGINE_METHOD_CIPHERS, ENGINE_METHOD_DIGESTS, ENGINE_METHOD_PKEY_METHS, ENGINE_METHOD_PKEY_ASN1_METHS, ENGINE_METHOD_ALL, ENGINE_METHOD_NONE, DH_CHECK_P_NOT_SAFE_PRIME, DH_CHECK_P_NOT_PRIME, DH_UNABLE_TO_CHECK_GENERATOR, DH_NOT_SUITABLE_GENERATOR, RSA_PKCS1_PADDING, RSA_NO_PADDING, RSA_PKCS1_OAEP_PADDING, RSA_X931_PADDING, RSA_PKCS1_PSS_PADDING, RSA_PSS_SALTLEN_DIGEST, RSA_PSS_SALTLEN_MAX_SIGN, RSA_PSS_SALTLEN_AUTO, defaultCoreCipherList, TLS1_VERSION, TLS1_1_VERSION, TLS1_2_VERSION, TLS1_3_VERSION, POINT_CONVERSION_COMPRESSED, POINT_CONVERSION_UNCOMPRESSED, POINT_CONVERSION_HYBRID } from "./internal/crypto/constants.mjs"; +export const { RTLD_LAZY, RTLD_NOW, RTLD_GLOBAL, RTLD_LOCAL, RTLD_DEEPBIND } = dlopen; +export const { E2BIG, EACCES, EADDRINUSE, EADDRNOTAVAIL, EAFNOSUPPORT, EAGAIN, EALREADY, EBADF, EBADMSG, EBUSY, ECANCELED, ECHILD, ECONNABORTED, ECONNREFUSED, ECONNRESET, EDEADLK, EDESTADDRREQ, EDOM, EDQUOT, EEXIST, EFAULT, EFBIG, EHOSTUNREACH, EIDRM, EILSEQ, EINPROGRESS, EINTR, EINVAL, EIO, EISCONN, EISDIR, ELOOP, EMFILE, EMLINK, EMSGSIZE, EMULTIHOP, ENAMETOOLONG, ENETDOWN, ENETRESET, ENETUNREACH, ENFILE, ENOBUFS, ENODATA, ENODEV, ENOENT, ENOEXEC, ENOLCK, ENOLINK, ENOMEM, ENOMSG, ENOPROTOOPT, ENOSPC, ENOSR, ENOSTR, ENOSYS, ENOTCONN, ENOTDIR, ENOTEMPTY, ENOTSOCK, ENOTSUP, ENOTTY, ENXIO, EOPNOTSUPP, EOVERFLOW, EPERM, EPIPE, EPROTO, EPROTONOSUPPORT, EPROTOTYPE, ERANGE, EROFS, ESPIPE, ESRCH, ESTALE, ETIME, ETIMEDOUT, ETXTBSY, EWOULDBLOCK, EXDEV } = errno; +export const { PRIORITY_LOW, PRIORITY_BELOW_NORMAL, PRIORITY_NORMAL, PRIORITY_ABOVE_NORMAL, PRIORITY_HIGH, PRIORITY_HIGHEST } = priority; +export const { SIGHUP, SIGINT, SIGQUIT, SIGILL, SIGTRAP, SIGABRT, SIGIOT, SIGBUS, SIGFPE, SIGKILL, SIGUSR1, SIGSEGV, SIGUSR2, SIGPIPE, SIGALRM, SIGTERM, SIGCHLD, SIGSTKFLT, SIGCONT, SIGSTOP, SIGTSTP, SIGTTIN, SIGTTOU, SIGURG, SIGXCPU, SIGXFSZ, SIGVTALRM, SIGPROF, SIGWINCH, SIGIO, SIGPOLL, SIGPWR, SIGSYS } = signals; +export default { + OPENSSL_VERSION_NUMBER, + SSL_OP_ALL, + SSL_OP_ALLOW_NO_DHE_KEX, + SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION, + SSL_OP_CIPHER_SERVER_PREFERENCE, + SSL_OP_CISCO_ANYCONNECT, + SSL_OP_COOKIE_EXCHANGE, + SSL_OP_CRYPTOPRO_TLSEXT_BUG, + SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS, + SSL_OP_LEGACY_SERVER_CONNECT, + SSL_OP_NO_COMPRESSION, + SSL_OP_NO_ENCRYPT_THEN_MAC, + SSL_OP_NO_QUERY_MTU, + SSL_OP_NO_RENEGOTIATION, + SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION, + SSL_OP_NO_SSLv2, + SSL_OP_NO_SSLv3, + SSL_OP_NO_TICKET, + SSL_OP_NO_TLSv1, + SSL_OP_NO_TLSv1_1, + SSL_OP_NO_TLSv1_2, + SSL_OP_NO_TLSv1_3, + SSL_OP_PRIORITIZE_CHACHA, + SSL_OP_TLS_ROLLBACK_BUG, + ENGINE_METHOD_RSA, + ENGINE_METHOD_DSA, + ENGINE_METHOD_DH, + ENGINE_METHOD_RAND, + ENGINE_METHOD_EC, + ENGINE_METHOD_CIPHERS, + ENGINE_METHOD_DIGESTS, + ENGINE_METHOD_PKEY_METHS, + ENGINE_METHOD_PKEY_ASN1_METHS, + ENGINE_METHOD_ALL, + ENGINE_METHOD_NONE, + DH_CHECK_P_NOT_SAFE_PRIME, + DH_CHECK_P_NOT_PRIME, + DH_UNABLE_TO_CHECK_GENERATOR, + DH_NOT_SUITABLE_GENERATOR, + RSA_PKCS1_PADDING, + RSA_NO_PADDING, + RSA_PKCS1_OAEP_PADDING, + RSA_X931_PADDING, + RSA_PKCS1_PSS_PADDING, + RSA_PSS_SALTLEN_DIGEST, + RSA_PSS_SALTLEN_MAX_SIGN, + RSA_PSS_SALTLEN_AUTO, + defaultCoreCipherList, + TLS1_VERSION, + TLS1_1_VERSION, + TLS1_2_VERSION, + TLS1_3_VERSION, + POINT_CONVERSION_COMPRESSED, + POINT_CONVERSION_UNCOMPRESSED, + POINT_CONVERSION_HYBRID, + UV_FS_SYMLINK_DIR, + UV_FS_SYMLINK_JUNCTION, + O_RDONLY, + O_WRONLY, + O_RDWR, + UV_DIRENT_UNKNOWN, + UV_DIRENT_FILE, + UV_DIRENT_DIR, + UV_DIRENT_LINK, + UV_DIRENT_FIFO, + UV_DIRENT_SOCKET, + UV_DIRENT_CHAR, + UV_DIRENT_BLOCK, + EXTENSIONLESS_FORMAT_JAVASCRIPT, + EXTENSIONLESS_FORMAT_WASM, + S_IFMT, + S_IFREG, + S_IFDIR, + S_IFCHR, + S_IFBLK, + S_IFIFO, + S_IFLNK, + S_IFSOCK, + O_CREAT, + O_EXCL, + UV_FS_O_FILEMAP, + O_NOCTTY, + O_TRUNC, + O_APPEND, + O_DIRECTORY, + O_NOATIME, + O_NOFOLLOW, + O_SYNC, + O_DSYNC, + O_DIRECT, + O_NONBLOCK, + S_IRWXU, + S_IRUSR, + S_IWUSR, + S_IXUSR, + S_IRWXG, + S_IRGRP, + S_IWGRP, + S_IXGRP, + S_IRWXO, + S_IROTH, + S_IWOTH, + S_IXOTH, + F_OK, + R_OK, + W_OK, + X_OK, + UV_FS_COPYFILE_EXCL, + COPYFILE_EXCL, + UV_FS_COPYFILE_FICLONE, + COPYFILE_FICLONE, + UV_FS_COPYFILE_FICLONE_FORCE, + COPYFILE_FICLONE_FORCE, + E2BIG, + EACCES, + EADDRINUSE, + EADDRNOTAVAIL, + EAFNOSUPPORT, + EAGAIN, + EALREADY, + EBADF, + EBADMSG, + EBUSY, + ECANCELED, + ECHILD, + ECONNABORTED, + ECONNREFUSED, + ECONNRESET, + EDEADLK, + EDESTADDRREQ, + EDOM, + EDQUOT, + EEXIST, + EFAULT, + EFBIG, + EHOSTUNREACH, + EIDRM, + EILSEQ, + EINPROGRESS, + EINTR, + EINVAL, + EIO, + EISCONN, + EISDIR, + ELOOP, + EMFILE, + EMLINK, + EMSGSIZE, + EMULTIHOP, + ENAMETOOLONG, + ENETDOWN, + ENETRESET, + ENETUNREACH, + ENFILE, + ENOBUFS, + ENODATA, + ENODEV, + ENOENT, + ENOEXEC, + ENOLCK, + ENOLINK, + ENOMEM, + ENOMSG, + ENOPROTOOPT, + ENOSPC, + ENOSR, + ENOSTR, + ENOSYS, + ENOTCONN, + ENOTDIR, + ENOTEMPTY, + ENOTSOCK, + ENOTSUP, + ENOTTY, + ENXIO, + EOPNOTSUPP, + EOVERFLOW, + EPERM, + EPIPE, + EPROTO, + EPROTONOSUPPORT, + EPROTOTYPE, + ERANGE, + EROFS, + ESPIPE, + ESRCH, + ESTALE, + ETIME, + ETIMEDOUT, + ETXTBSY, + EWOULDBLOCK, + EXDEV, + RTLD_LAZY, + RTLD_NOW, + RTLD_GLOBAL, + RTLD_LOCAL, + RTLD_DEEPBIND, + PRIORITY_LOW, + PRIORITY_BELOW_NORMAL, + PRIORITY_NORMAL, + PRIORITY_ABOVE_NORMAL, + PRIORITY_HIGH, + PRIORITY_HIGHEST, + SIGHUP, + SIGINT, + SIGQUIT, + SIGILL, + SIGTRAP, + SIGABRT, + SIGIOT, + SIGBUS, + SIGFPE, + SIGKILL, + SIGUSR1, + SIGSEGV, + SIGUSR2, + SIGPIPE, + SIGALRM, + SIGTERM, + SIGCHLD, + SIGSTKFLT, + SIGCONT, + SIGSTOP, + SIGTSTP, + SIGTTIN, + SIGTTOU, + SIGURG, + SIGXCPU, + SIGXFSZ, + SIGVTALRM, + SIGPROF, + SIGWINCH, + SIGIO, + SIGPOLL, + SIGPWR, + SIGSYS +}; diff --git a/worker/node_modules/unenv/dist/runtime/node/crypto.d.mts b/worker/node_modules/unenv/dist/runtime/node/crypto.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..863f198679ea1d4786658ecb6cee7d5dc19c315c --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/crypto.d.mts @@ -0,0 +1,5 @@ +export * from "./internal/crypto/web.mjs"; +export * from "./internal/crypto/node.mjs"; +export declare const constants: {}; +declare const _default: {}; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/crypto.mjs b/worker/node_modules/unenv/dist/runtime/node/crypto.mjs new file mode 100644 index 0000000000000000000000000000000000000000..0f71db94acb759328edf3340a2c6a4f851688ab5 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/crypto.mjs @@ -0,0 +1,136 @@ +import { getRandomValues, randomUUID, subtle } from "./internal/crypto/web.mjs"; +import { Certificate, Cipher, Cipheriv, Decipher, Decipheriv, DiffieHellman, DiffieHellmanGroup, ECDH, Hash, Hmac, KeyObject, Sign, Verify, X509Certificate, checkPrime, checkPrimeSync, createCipheriv, createDecipheriv, createDiffieHellman, createDiffieHellmanGroup, createECDH, createHash, createHmac, createPrivateKey, createPublicKey, createSecretKey, createSign, createVerify, diffieHellman, fips, generateKey, generateKeyPair, generateKeyPairSync, generateKeySync, generatePrime, generatePrimeSync, getCipherInfo, getCiphers, getCurves, getDiffieHellman, getFips, getHashes, hash, hkdf, hkdfSync, pbkdf2, pbkdf2Sync, privateDecrypt, privateEncrypt, pseudoRandomBytes, publicDecrypt, prng, publicEncrypt, randomBytes, randomFill, randomFillSync, randomInt, rng, scrypt, scryptSync, secureHeapUsed, setEngine, setFips, sign, timingSafeEqual, verify, webcrypto } from "./internal/crypto/node.mjs"; +import { OPENSSL_VERSION_NUMBER, SSL_OP_ALL, SSL_OP_ALLOW_NO_DHE_KEX, SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION, SSL_OP_CIPHER_SERVER_PREFERENCE, SSL_OP_CISCO_ANYCONNECT, SSL_OP_COOKIE_EXCHANGE, SSL_OP_CRYPTOPRO_TLSEXT_BUG, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS, SSL_OP_LEGACY_SERVER_CONNECT, SSL_OP_NO_COMPRESSION, SSL_OP_NO_ENCRYPT_THEN_MAC, SSL_OP_NO_QUERY_MTU, SSL_OP_NO_RENEGOTIATION, SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION, SSL_OP_NO_SSLv2, SSL_OP_NO_SSLv3, SSL_OP_NO_TICKET, SSL_OP_NO_TLSv1, SSL_OP_NO_TLSv1_1, SSL_OP_NO_TLSv1_2, SSL_OP_NO_TLSv1_3, SSL_OP_PRIORITIZE_CHACHA, SSL_OP_TLS_ROLLBACK_BUG, ENGINE_METHOD_RSA, ENGINE_METHOD_DSA, ENGINE_METHOD_DH, ENGINE_METHOD_RAND, ENGINE_METHOD_EC, ENGINE_METHOD_CIPHERS, ENGINE_METHOD_DIGESTS, ENGINE_METHOD_PKEY_METHS, ENGINE_METHOD_PKEY_ASN1_METHS, ENGINE_METHOD_ALL, ENGINE_METHOD_NONE, DH_CHECK_P_NOT_SAFE_PRIME, DH_CHECK_P_NOT_PRIME, DH_UNABLE_TO_CHECK_GENERATOR, DH_NOT_SUITABLE_GENERATOR, RSA_PKCS1_PADDING, RSA_NO_PADDING, RSA_PKCS1_OAEP_PADDING, RSA_X931_PADDING, RSA_PKCS1_PSS_PADDING, RSA_PSS_SALTLEN_DIGEST, RSA_PSS_SALTLEN_MAX_SIGN, RSA_PSS_SALTLEN_AUTO, defaultCoreCipherList, TLS1_VERSION, TLS1_1_VERSION, TLS1_2_VERSION, TLS1_3_VERSION, POINT_CONVERSION_COMPRESSED, POINT_CONVERSION_UNCOMPRESSED, POINT_CONVERSION_HYBRID, defaultCipherList } from "./internal/crypto/constants.mjs"; +export * from "./internal/crypto/web.mjs"; +export * from "./internal/crypto/node.mjs"; +export const constants = { + OPENSSL_VERSION_NUMBER, + SSL_OP_ALL, + SSL_OP_ALLOW_NO_DHE_KEX, + SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION, + SSL_OP_CIPHER_SERVER_PREFERENCE, + SSL_OP_CISCO_ANYCONNECT, + SSL_OP_COOKIE_EXCHANGE, + SSL_OP_CRYPTOPRO_TLSEXT_BUG, + SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS, + SSL_OP_LEGACY_SERVER_CONNECT, + SSL_OP_NO_COMPRESSION, + SSL_OP_NO_ENCRYPT_THEN_MAC, + SSL_OP_NO_QUERY_MTU, + SSL_OP_NO_RENEGOTIATION, + SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION, + SSL_OP_NO_SSLv2, + SSL_OP_NO_SSLv3, + SSL_OP_NO_TICKET, + SSL_OP_NO_TLSv1, + SSL_OP_NO_TLSv1_1, + SSL_OP_NO_TLSv1_2, + SSL_OP_NO_TLSv1_3, + SSL_OP_PRIORITIZE_CHACHA, + SSL_OP_TLS_ROLLBACK_BUG, + ENGINE_METHOD_RSA, + ENGINE_METHOD_DSA, + ENGINE_METHOD_DH, + ENGINE_METHOD_RAND, + ENGINE_METHOD_EC, + ENGINE_METHOD_CIPHERS, + ENGINE_METHOD_DIGESTS, + ENGINE_METHOD_PKEY_METHS, + ENGINE_METHOD_PKEY_ASN1_METHS, + ENGINE_METHOD_ALL, + ENGINE_METHOD_NONE, + DH_CHECK_P_NOT_SAFE_PRIME, + DH_CHECK_P_NOT_PRIME, + DH_UNABLE_TO_CHECK_GENERATOR, + DH_NOT_SUITABLE_GENERATOR, + RSA_PKCS1_PADDING, + RSA_NO_PADDING, + RSA_PKCS1_OAEP_PADDING, + RSA_X931_PADDING, + RSA_PKCS1_PSS_PADDING, + RSA_PSS_SALTLEN_DIGEST, + RSA_PSS_SALTLEN_MAX_SIGN, + RSA_PSS_SALTLEN_AUTO, + defaultCoreCipherList, + TLS1_VERSION, + TLS1_1_VERSION, + TLS1_2_VERSION, + TLS1_3_VERSION, + POINT_CONVERSION_COMPRESSED, + POINT_CONVERSION_UNCOMPRESSED, + POINT_CONVERSION_HYBRID, + defaultCipherList +}; +export default { + constants, + getRandomValues, + randomUUID, + subtle, + Certificate, + Cipher, + Cipheriv, + Decipher, + Decipheriv, + DiffieHellman, + DiffieHellmanGroup, + ECDH, + Hash, + Hmac, + KeyObject, + Sign, + Verify, + X509Certificate, + checkPrime, + checkPrimeSync, + createCipheriv, + createDecipheriv, + createDiffieHellman, + createDiffieHellmanGroup, + createECDH, + createHash, + createHmac, + createPrivateKey, + createPublicKey, + createSecretKey, + createSign, + createVerify, + diffieHellman, + fips, + generateKey, + generateKeyPair, + generateKeyPairSync, + generateKeySync, + generatePrime, + generatePrimeSync, + getCipherInfo, + getCiphers, + getCurves, + getDiffieHellman, + getFips, + getHashes, + hash, + hkdf, + hkdfSync, + pbkdf2, + pbkdf2Sync, + privateDecrypt, + privateEncrypt, + pseudoRandomBytes, + publicDecrypt, + prng, + publicEncrypt, + randomBytes, + randomFill, + randomFillSync, + randomInt, + rng, + scrypt, + scryptSync, + secureHeapUsed, + setEngine, + setFips, + sign, + timingSafeEqual, + verify, + webcrypto +}; diff --git a/worker/node_modules/unenv/dist/runtime/node/dgram.d.mts b/worker/node_modules/unenv/dist/runtime/node/dgram.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..01bb2a2884ed489a2f0faa316487da2ac75827b8 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/dgram.d.mts @@ -0,0 +1,6 @@ +import type nodeDgram from "node:dgram"; +export { Socket } from "./internal/dgram/socket.mjs"; +export declare const _createSocketHandle: unknown; +export declare const createSocket: typeof nodeDgram.createSocket; +declare const _default: typeof nodeDgram; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/dgram.mjs b/worker/node_modules/unenv/dist/runtime/node/dgram.mjs new file mode 100644 index 0000000000000000000000000000000000000000..9f64e777ad0b5a3990e166b0df8cc5fa406a064b --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/dgram.mjs @@ -0,0 +1,12 @@ +import noop from "../mock/noop.mjs"; +import { Socket } from "./internal/dgram/socket.mjs"; +export { Socket } from "./internal/dgram/socket.mjs"; +export const _createSocketHandle = noop; +export const createSocket = function() { + return new Socket(); +}; +export default { + Socket, + _createSocketHandle, + createSocket +}; diff --git a/worker/node_modules/unenv/dist/runtime/node/diagnostics_channel.d.mts b/worker/node_modules/unenv/dist/runtime/node/diagnostics_channel.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..e2a814198f45880c528d34e20864363b46d11ec4 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/diagnostics_channel.d.mts @@ -0,0 +1,9 @@ +import type nodeDiagnosticsChannel from "node:diagnostics_channel"; +export { Channel } from "./internal/diagnostics_channel/channel.mjs"; +export declare const channel: typeof nodeDiagnosticsChannel.channel; +export declare const hasSubscribers: typeof nodeDiagnosticsChannel.hasSubscribers; +export declare const subscribe: typeof nodeDiagnosticsChannel.subscribe; +export declare const unsubscribe: typeof nodeDiagnosticsChannel.unsubscribe; +export declare const tracingChannel: typeof nodeDiagnosticsChannel.tracingChannel; +declare const _default: {}; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/diagnostics_channel.mjs b/worker/node_modules/unenv/dist/runtime/node/diagnostics_channel.mjs new file mode 100644 index 0000000000000000000000000000000000000000..104d3107f0805432e088ae16f5c8388e2dfd92de --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/diagnostics_channel.mjs @@ -0,0 +1,32 @@ +import { Channel, getChannels } from "./internal/diagnostics_channel/channel.mjs"; +import { TracingChannel } from "./internal/diagnostics_channel/tracing-channel.mjs"; +export { Channel } from "./internal/diagnostics_channel/channel.mjs"; +export const channel = function(name) { + const channels = getChannels(); + if (name in channels) { + return channels[name]; + } + return new Channel(name); +}; +export const hasSubscribers = function(name) { + const channels = getChannels(); + const channel = channels[name]; + return channel && channel.hasSubscribers; +}; +export const subscribe = function(name, onMessage) { + channel(name).subscribe(onMessage); +}; +export const unsubscribe = function(name, onMessage) { + return channel(name).unsubscribe(onMessage); +}; +export const tracingChannel = function(name) { + return new TracingChannel(name); +}; +export default { + Channel, + channel, + hasSubscribers, + subscribe, + tracingChannel, + unsubscribe +}; diff --git a/worker/node_modules/unenv/dist/runtime/node/dns.d.mts b/worker/node_modules/unenv/dist/runtime/node/dns.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..169e09eddebd4f3c6dff9f89d3685727af2102f8 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/dns.d.mts @@ -0,0 +1,27 @@ +import type nodeDns from "node:dns"; +import promises from "node:dns/promises"; +export { promises }; +export declare const Resolver: typeof nodeDns.Resolver; +export declare const getDefaultResultOrder: typeof nodeDns.getDefaultResultOrder; +export declare const getServers: typeof nodeDns.getServers; +export declare const lookup: typeof nodeDns.lookup; +export declare const lookupService: typeof nodeDns.lookupService; +export declare const resolve: typeof nodeDns.resolve; +export declare const resolve4: typeof nodeDns.resolve4; +export declare const resolve6: typeof nodeDns.resolve6; +export declare const resolveAny: typeof nodeDns.resolveAny; +export declare const resolveCaa: typeof nodeDns.resolveCaa; +export declare const resolveCname: typeof nodeDns.resolveCname; +export declare const resolveMx: typeof nodeDns.resolveMx; +export declare const resolveNaptr: typeof nodeDns.resolveNaptr; +export declare const resolveNs: typeof nodeDns.resolveNs; +export declare const resolvePtr: typeof nodeDns.resolvePtr; +export declare const resolveSoa: typeof nodeDns.resolveSoa; +export declare const resolveSrv: typeof nodeDns.resolveSrv; +export declare const resolveTxt: typeof nodeDns.resolveTxt; +export declare const reverse: typeof nodeDns.reverse; +export declare const setDefaultResultOrder: typeof nodeDns.setDefaultResultOrder; +export declare const setServers: typeof nodeDns.setServers; +export { NODATA, FORMERR, SERVFAIL, NOTFOUND, NOTIMP, REFUSED, BADQUERY, BADNAME, BADFAMILY, BADRESP, CONNREFUSED, TIMEOUT, EOF, FILE, NOMEM, DESTRUCTION, BADSTR, BADFLAGS, NONAME, BADHINTS, NOTINITIALIZED, LOADIPHLPAPI, ADDRGETNETWORKPARAMS, CANCELLED, ADDRCONFIG, ALL, V4MAPPED } from "./internal/dns/constants.mjs"; +declare const _default: {}; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/dns.mjs b/worker/node_modules/unenv/dist/runtime/node/dns.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c6a8eb6273a5bd3395f097ed28e2731a1ad63125 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/dns.mjs @@ -0,0 +1,78 @@ +import noop from "../mock/noop.mjs"; +import { notImplemented, notImplementedAsync, notImplementedClass } from "../_internal/utils.mjs"; +import promises from "node:dns/promises"; +export { promises }; +export const Resolver = /*@__PURE__*/ notImplementedClass("dns.Resolver"); +export const getDefaultResultOrder = () => "verbatim"; +export const getServers = () => []; +export const lookup = /*@__PURE__*/ notImplementedAsync("dns.lookup"); +export const lookupService = /*@__PURE__*/ notImplementedAsync("dns.lookupService"); +export const resolve = /*@__PURE__*/ notImplementedAsync("dns.resolve"); +export const resolve4 = /*@__PURE__*/ notImplementedAsync("dns.resolve4"); +export const resolve6 = /*@__PURE__*/ notImplementedAsync("dns.resolve6"); +export const resolveAny = /*@__PURE__*/ notImplementedAsync("dns.resolveAny"); +export const resolveCaa = /*@__PURE__*/ notImplementedAsync("dns.resolveCaa"); +export const resolveCname = /*@__PURE__*/ notImplementedAsync("dns.resolveCname"); +export const resolveMx = /*@__PURE__*/ notImplementedAsync("dns.resolveMx"); +export const resolveNaptr = /*@__PURE__*/ notImplementedAsync("dns.resolveNaptr"); +export const resolveNs = /*@__PURE__*/ notImplementedAsync("dns.resolveNs"); +export const resolvePtr = /*@__PURE__*/ notImplementedAsync("dns.resolvePtr"); +export const resolveSoa = /*@__PURE__*/ notImplementedAsync("dns.resolveSoa"); +export const resolveSrv = /*@__PURE__*/ notImplementedAsync("dns.resolveSrv"); +export const resolveTxt = /*@__PURE__*/ notImplementedAsync("dns.resolveTxt"); +export const reverse = /*@__PURE__*/ notImplemented("dns.reverse"); +export const setDefaultResultOrder = noop; +export const setServers = noop; +import { NODATA, FORMERR, SERVFAIL, NOTFOUND, NOTIMP, REFUSED, BADQUERY, BADNAME, BADFAMILY, BADRESP, CONNREFUSED, TIMEOUT, EOF, FILE, NOMEM, DESTRUCTION, BADSTR, BADFLAGS, NONAME, BADHINTS, NOTINITIALIZED, LOADIPHLPAPI, ADDRGETNETWORKPARAMS, CANCELLED, ADDRCONFIG, ALL, V4MAPPED } from "./internal/dns/constants.mjs"; +export { NODATA, FORMERR, SERVFAIL, NOTFOUND, NOTIMP, REFUSED, BADQUERY, BADNAME, BADFAMILY, BADRESP, CONNREFUSED, TIMEOUT, EOF, FILE, NOMEM, DESTRUCTION, BADSTR, BADFLAGS, NONAME, BADHINTS, NOTINITIALIZED, LOADIPHLPAPI, ADDRGETNETWORKPARAMS, CANCELLED, ADDRCONFIG, ALL, V4MAPPED } from "./internal/dns/constants.mjs"; +export default { + NODATA, + FORMERR, + SERVFAIL, + NOTFOUND, + NOTIMP, + REFUSED, + BADQUERY, + BADNAME, + BADFAMILY, + BADRESP, + CONNREFUSED, + TIMEOUT, + EOF, + FILE, + NOMEM, + DESTRUCTION, + BADSTR, + BADFLAGS, + NONAME, + BADHINTS, + NOTINITIALIZED, + LOADIPHLPAPI, + ADDRGETNETWORKPARAMS, + CANCELLED, + ADDRCONFIG, + ALL, + V4MAPPED, + Resolver, + getDefaultResultOrder, + getServers, + lookup, + lookupService, + promises, + resolve, + resolve4, + resolve6, + resolveAny, + resolveCaa, + resolveCname, + resolveMx, + resolveNaptr, + resolveNs, + resolvePtr, + resolveSoa, + resolveSrv, + resolveTxt, + reverse, + setDefaultResultOrder, + setServers +}; diff --git a/worker/node_modules/unenv/dist/runtime/node/dns/promises.d.mts b/worker/node_modules/unenv/dist/runtime/node/dns/promises.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..c213dcc6333fbf8057c2dc850607c4310bb88820 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/dns/promises.d.mts @@ -0,0 +1,25 @@ +import type nodeDnsPromises from "node:dns/promises"; +export { NODATA, FORMERR, SERVFAIL, NOTFOUND, NOTIMP, REFUSED, BADQUERY, BADNAME, BADFAMILY, BADRESP, CONNREFUSED, TIMEOUT, EOF, FILE, NOMEM, DESTRUCTION, BADSTR, BADFLAGS, NONAME, BADHINTS, NOTINITIALIZED, LOADIPHLPAPI, ADDRGETNETWORKPARAMS, CANCELLED } from "../internal/dns/constants.mjs"; +export declare const Resolver: typeof nodeDnsPromises.Resolver; +export declare const getDefaultResultOrder: typeof nodeDnsPromises.getDefaultResultOrder; +export declare const getServers: typeof nodeDnsPromises.getServers; +export declare const lookup: typeof nodeDnsPromises.lookup; +export declare const lookupService: typeof nodeDnsPromises.lookupService; +export declare const resolve: typeof nodeDnsPromises.resolve; +export declare const resolve4: typeof nodeDnsPromises.resolve4; +export declare const resolve6: typeof nodeDnsPromises.resolve6; +export declare const resolveAny: typeof nodeDnsPromises.resolveAny; +export declare const resolveCaa: typeof nodeDnsPromises.resolveCaa; +export declare const resolveCname: typeof nodeDnsPromises.resolveCname; +export declare const resolveMx: typeof nodeDnsPromises.resolveMx; +export declare const resolveNaptr: typeof nodeDnsPromises.resolveNaptr; +export declare const resolveNs: typeof nodeDnsPromises.resolveNs; +export declare const resolvePtr: typeof nodeDnsPromises.resolvePtr; +export declare const resolveSoa: typeof nodeDnsPromises.resolveSoa; +export declare const resolveSrv: typeof nodeDnsPromises.resolveSrv; +export declare const resolveTxt: typeof nodeDnsPromises.resolveTxt; +export declare const reverse: typeof nodeDnsPromises.reverse; +export declare const setDefaultResultOrder: typeof nodeDnsPromises.setDefaultResultOrder; +export declare const setServers: typeof nodeDnsPromises.setServers; +declare const _default: {}; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/dns/promises.mjs b/worker/node_modules/unenv/dist/runtime/node/dns/promises.mjs new file mode 100644 index 0000000000000000000000000000000000000000..0f3e7932a80a69a5e8e896532e6d1138affb9a2c --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/dns/promises.mjs @@ -0,0 +1,72 @@ +import noop from "../../mock/noop.mjs"; +import { notImplemented, notImplementedAsync, notImplementedClass } from "../../_internal/utils.mjs"; +import { NODATA, FORMERR, SERVFAIL, NOTFOUND, NOTIMP, REFUSED, BADQUERY, BADNAME, BADFAMILY, BADRESP, CONNREFUSED, TIMEOUT, EOF, FILE, NOMEM, DESTRUCTION, BADSTR, BADFLAGS, NONAME, BADHINTS, NOTINITIALIZED, LOADIPHLPAPI, ADDRGETNETWORKPARAMS, CANCELLED } from "../internal/dns/constants.mjs"; +export { NODATA, FORMERR, SERVFAIL, NOTFOUND, NOTIMP, REFUSED, BADQUERY, BADNAME, BADFAMILY, BADRESP, CONNREFUSED, TIMEOUT, EOF, FILE, NOMEM, DESTRUCTION, BADSTR, BADFLAGS, NONAME, BADHINTS, NOTINITIALIZED, LOADIPHLPAPI, ADDRGETNETWORKPARAMS, CANCELLED } from "../internal/dns/constants.mjs"; +export const Resolver = /*@__PURE__*/ notImplementedClass("dns.Resolver"); +export const getDefaultResultOrder = () => "verbatim"; +export const getServers = () => []; +export const lookup = /*@__PURE__*/ notImplementedAsync("dns.lookup"); +export const lookupService = /*@__PURE__*/ notImplementedAsync("dns.lookupService"); +export const resolve = /*@__PURE__*/ notImplementedAsync("dns.resolve"); +export const resolve4 = /*@__PURE__*/ notImplementedAsync("dns.resolve4"); +export const resolve6 = /*@__PURE__*/ notImplementedAsync("dns.resolve6"); +export const resolveAny = /*@__PURE__*/ notImplementedAsync("dns.resolveAny"); +export const resolveCaa = /*@__PURE__*/ notImplementedAsync("dns.resolveCaa"); +export const resolveCname = /*@__PURE__*/ notImplementedAsync("dns.resolveCname"); +export const resolveMx = /*@__PURE__*/ notImplementedAsync("dns.resolveMx"); +export const resolveNaptr = /*@__PURE__*/ notImplementedAsync("dns.resolveNaptr"); +export const resolveNs = /*@__PURE__*/ notImplementedAsync("dns.resolveNs"); +export const resolvePtr = /*@__PURE__*/ notImplementedAsync("dns.resolvePtr"); +export const resolveSoa = /*@__PURE__*/ notImplementedAsync("dns.resolveSoa"); +export const resolveSrv = /*@__PURE__*/ notImplementedAsync("dns.resolveSrv"); +export const resolveTxt = /*@__PURE__*/ notImplementedAsync("dns.resolveTxt"); +export const reverse = /*@__PURE__*/ notImplemented("dns.reverse"); +export const setDefaultResultOrder = noop; +export const setServers = noop; +export default { + NODATA, + FORMERR, + SERVFAIL, + NOTFOUND, + NOTIMP, + REFUSED, + BADQUERY, + BADNAME, + BADFAMILY, + BADRESP, + CONNREFUSED, + TIMEOUT, + EOF, + FILE, + NOMEM, + DESTRUCTION, + BADSTR, + BADFLAGS, + NONAME, + BADHINTS, + NOTINITIALIZED, + LOADIPHLPAPI, + ADDRGETNETWORKPARAMS, + CANCELLED, + Resolver, + getDefaultResultOrder, + getServers, + lookup, + lookupService, + resolve, + resolve4, + resolve6, + resolveAny, + resolveCaa, + resolveCname, + resolveMx, + resolveNaptr, + resolveNs, + resolvePtr, + resolveSoa, + resolveSrv, + resolveTxt, + reverse, + setDefaultResultOrder, + setServers +}; diff --git a/worker/node_modules/unenv/dist/runtime/node/domain.d.mts b/worker/node_modules/unenv/dist/runtime/node/domain.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..7bcc541240fe63446b844dcc45480a921509f820 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/domain.d.mts @@ -0,0 +1,8 @@ +import type nodeDomain from "node:domain"; +export { Domain } from "./internal/domain/domain.mjs"; +export declare const create: typeof nodeDomain.create; +export declare const createDomain: typeof nodeDomain.create; +export declare const active: unknown; +export declare const _stack: unknown; +declare const _default: typeof nodeDomain; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/domain.mjs b/worker/node_modules/unenv/dist/runtime/node/domain.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c129b5487dcb4807988b889b3deebadd5262edbf --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/domain.mjs @@ -0,0 +1,16 @@ +import { Domain } from "./internal/domain/domain.mjs"; +export { Domain } from "./internal/domain/domain.mjs"; +export const create = function() { + return new Domain(); +}; +export const createDomain = create; +const _domain = create(); +export const active = () => _domain; +export const _stack = []; +export default { + Domain, + _stack, + active, + create, + createDomain +}; diff --git a/worker/node_modules/unenv/dist/runtime/node/events.d.mts b/worker/node_modules/unenv/dist/runtime/node/events.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..7bf5f897d2903884f7148bbe5d0ed4657ee9ce25 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/events.d.mts @@ -0,0 +1,12 @@ +import type nodeEvents from "node:events"; +export { _EventEmitter as EventEmitter, EventEmitterAsyncResource, addAbortListener, getEventListeners, getMaxListeners, on, once } from "./internal/events/events.mjs"; +export declare const usingDomains: boolean; +export declare const captureRejectionSymbol: unknown; +export declare const captureRejections: boolean; +export declare const errorMonitor: unknown; +export declare const defaultMaxListeners = 10; +export declare const setMaxListeners: unknown; +export declare const listenerCount: unknown; +export declare const init: unknown; +declare const _default: typeof nodeEvents; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/events.mjs b/worker/node_modules/unenv/dist/runtime/node/events.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c5b0d8b55c9f1496334faf4bbf377f9f3ac716d7 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/events.mjs @@ -0,0 +1,12 @@ +import { _EventEmitter } from "./internal/events/events.mjs"; +import { notImplemented } from "../_internal/utils.mjs"; +export { _EventEmitter as EventEmitter, EventEmitterAsyncResource, addAbortListener, getEventListeners, getMaxListeners, on, once } from "./internal/events/events.mjs"; +export const usingDomains = false; +export const captureRejectionSymbol = /*@__PURE__*/ Symbol.for("nodejs.rejection"); +export const captureRejections = false; +export const errorMonitor = /*@__PURE__*/ Symbol.for("events.errorMonitor"); +export const defaultMaxListeners = 10; +export const setMaxListeners = /*@__PURE__*/ notImplemented("node:events.setMaxListeners"); +export const listenerCount = /*@__PURE__*/ notImplemented("node:events.listenerCount"); +export const init = /*@__PURE__*/ notImplemented("node:events.init"); +export default _EventEmitter; diff --git a/worker/node_modules/unenv/dist/runtime/node/fs.d.mts b/worker/node_modules/unenv/dist/runtime/node/fs.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..4f23a20fca290da78247df21cb51b0b49ab8c72c --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/fs.d.mts @@ -0,0 +1,10 @@ +import promises from "node:fs/promises"; +import * as constants from "./internal/fs/constants.mjs"; +export { F_OK, R_OK, W_OK, X_OK } from "./internal/fs/constants.mjs"; +export { promises, constants }; +export * from "./internal/fs/fs.mjs"; +export * from "./internal/fs/classes.mjs"; +declare const _default: { + constants: any +}; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/fs.mjs b/worker/node_modules/unenv/dist/runtime/node/fs.mjs new file mode 100644 index 0000000000000000000000000000000000000000..298a6a1850b7bef897e0f86b5dba50d4900bf1b4 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/fs.mjs @@ -0,0 +1,117 @@ +import promises from "node:fs/promises"; +import { Dir, Dirent, FileReadStream, FileWriteStream, ReadStream, Stats, WriteStream } from "./internal/fs/classes.mjs"; +import { _toUnixTimestamp, access, accessSync, appendFile, appendFileSync, chmod, chmodSync, chown, chownSync, close, closeSync, copyFile, copyFileSync, cp, cpSync, createReadStream, createWriteStream, exists, existsSync, fchmod, fchmodSync, fchown, fchownSync, fdatasync, fdatasyncSync, fstat, fstatSync, fsync, fsyncSync, ftruncate, ftruncateSync, futimes, futimesSync, glob, lchmod, globSync, lchmodSync, lchown, lchownSync, link, linkSync, lstat, lstatSync, lutimes, lutimesSync, mkdir, mkdirSync, mkdtemp, mkdtempSync, open, openAsBlob, openSync, opendir, opendirSync, read, readFile, readFileSync, readSync, readdir, readdirSync, readlink, readlinkSync, readv, readvSync, realpath, realpathSync, rename, renameSync, rm, rmSync, rmdir, rmdirSync, stat, statSync, statfs, statfsSync, symlink, symlinkSync, truncate, truncateSync, unlink, unlinkSync, unwatchFile, utimes, utimesSync, watch, watchFile, write, writeFile, writeFileSync, writeSync, writev, writevSync } from "./internal/fs/fs.mjs"; +import * as constants from "./internal/fs/constants.mjs"; +import { F_OK, R_OK, W_OK, X_OK } from "./internal/fs/constants.mjs"; +export { F_OK, R_OK, W_OK, X_OK } from "./internal/fs/constants.mjs"; +export { promises, constants }; +export * from "./internal/fs/fs.mjs"; +export * from "./internal/fs/classes.mjs"; +export default { + F_OK, + R_OK, + W_OK, + X_OK, + constants, + promises, + Dir, + Dirent, + FileReadStream, + FileWriteStream, + ReadStream, + Stats, + WriteStream, + _toUnixTimestamp, + access, + accessSync, + appendFile, + appendFileSync, + chmod, + chmodSync, + chown, + chownSync, + close, + closeSync, + copyFile, + copyFileSync, + cp, + cpSync, + createReadStream, + createWriteStream, + exists, + existsSync, + fchmod, + fchmodSync, + fchown, + fchownSync, + fdatasync, + fdatasyncSync, + fstat, + fstatSync, + fsync, + fsyncSync, + ftruncate, + ftruncateSync, + futimes, + futimesSync, + glob, + lchmod, + globSync, + lchmodSync, + lchown, + lchownSync, + link, + linkSync, + lstat, + lstatSync, + lutimes, + lutimesSync, + mkdir, + mkdirSync, + mkdtemp, + mkdtempSync, + open, + openAsBlob, + openSync, + opendir, + opendirSync, + read, + readFile, + readFileSync, + readSync, + readdir, + readdirSync, + readlink, + readlinkSync, + readv, + readvSync, + realpath, + realpathSync, + rename, + renameSync, + rm, + rmSync, + rmdir, + rmdirSync, + stat, + statSync, + statfs, + statfsSync, + symlink, + symlinkSync, + truncate, + truncateSync, + unlink, + unlinkSync, + unwatchFile, + utimes, + utimesSync, + watch, + watchFile, + write, + writeFile, + writeFileSync, + writeSync, + writev, + writevSync +}; diff --git a/worker/node_modules/unenv/dist/runtime/node/fs/promises.d.mts b/worker/node_modules/unenv/dist/runtime/node/fs/promises.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..856d111960840fa4af818b7aa3ccd85cb032cdd2 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/fs/promises.d.mts @@ -0,0 +1,7 @@ +import * as constants from "../internal/fs/constants.mjs"; +export { constants }; +export * from "../internal/fs/promises.mjs"; +declare const _default: { + constants: any +}; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/fs/promises.mjs b/worker/node_modules/unenv/dist/runtime/node/fs/promises.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3ea8d64395a70414f5588d2c7269f4f8a2945ab3 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/fs/promises.mjs @@ -0,0 +1,38 @@ +import { access, appendFile, chmod, chown, copyFile, cp, glob, lchmod, lchown, link, lstat, lutimes, mkdir, mkdtemp, open, opendir, readFile, readdir, readlink, realpath, rename, rm, rmdir, stat, statfs, symlink, truncate, unlink, utimes, watch, writeFile } from "../internal/fs/promises.mjs"; +import * as constants from "../internal/fs/constants.mjs"; +export { constants }; +export * from "../internal/fs/promises.mjs"; +export default { + constants, + access, + appendFile, + chmod, + chown, + copyFile, + cp, + glob, + lchmod, + lchown, + link, + lstat, + lutimes, + mkdir, + mkdtemp, + open, + opendir, + readFile, + readdir, + readlink, + realpath, + rename, + rm, + rmdir, + stat, + statfs, + symlink, + truncate, + unlink, + utimes, + watch, + writeFile +}; diff --git a/worker/node_modules/unenv/dist/runtime/node/http.d.mts b/worker/node_modules/unenv/dist/runtime/node/http.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..4c6ccbba0284f835fdd1e24f03776ee271f22d6d --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/http.d.mts @@ -0,0 +1,22 @@ +import type nodeHttp from "node:http"; +import { METHODS, STATUS_CODES, maxHeaderSize } from "./internal/http/constants.mjs"; +export { METHODS, STATUS_CODES, maxHeaderSize }; +export * from "./internal/http/request.mjs"; +export * from "./internal/http/response.mjs"; +export { Agent } from "./internal/http/agent.mjs"; +export declare const createServer: unknown; +export declare const request: unknown; +export declare const get: unknown; +export declare const Server: typeof nodeHttp.Server; +export declare const OutgoingMessage: typeof nodeHttp.OutgoingMessage; +export declare const ClientRequest: typeof nodeHttp.ClientRequest; +export declare const globalAgent: typeof nodeHttp.globalAgent; +export declare const validateHeaderName: unknown; +export declare const validateHeaderValue: unknown; +export declare const setMaxIdleHTTPParsers: unknown; +export declare const _connectionListener: unknown; +export declare const WebSocket: unknown; +export declare const CloseEvent: unknown; +export declare const MessageEvent: unknown; +declare const _default: typeof nodeHttp; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/http.mjs b/worker/node_modules/unenv/dist/runtime/node/http.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a01bedd34d3a6273d187b9343e01f5635c420637 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/http.mjs @@ -0,0 +1,45 @@ +import { notImplemented, notImplementedClass } from "../_internal/utils.mjs"; +import { IncomingMessage } from "./internal/http/request.mjs"; +import { ServerResponse } from "./internal/http/response.mjs"; +import { Agent } from "./internal/http/agent.mjs"; +import { METHODS, STATUS_CODES, maxHeaderSize } from "./internal/http/constants.mjs"; +export { METHODS, STATUS_CODES, maxHeaderSize }; +export * from "./internal/http/request.mjs"; +export * from "./internal/http/response.mjs"; +export { Agent } from "./internal/http/agent.mjs"; +export const createServer = /*@__PURE__*/ notImplemented("http.createServer"); +export const request = /*@__PURE__*/ notImplemented("http.request"); +export const get = /*@__PURE__*/ notImplemented("http.get"); +export const Server = /*@__PURE__*/ notImplementedClass("http.Server"); +export const OutgoingMessage = /*@__PURE__*/ notImplementedClass("http.OutgoingMessage"); +export const ClientRequest = /*@__PURE__*/ notImplementedClass("http.ClientRequest"); +export const globalAgent = new Agent(); +export const validateHeaderName = /*@__PURE__*/ notImplemented("http.validateHeaderName"); +export const validateHeaderValue = /*@__PURE__*/ notImplemented("http.validateHeaderValue"); +export const setMaxIdleHTTPParsers = /*@__PURE__*/ notImplemented("http.setMaxIdleHTTPParsers"); +export const _connectionListener = /*@__PURE__*/ notImplemented("http._connectionListener"); +export const WebSocket = globalThis.WebSocket || /*@__PURE__*/ notImplementedClass("WebSocket"); +export const CloseEvent = globalThis.CloseEvent || /*@__PURE__*/ notImplementedClass("CloseEvent"); +export const MessageEvent = globalThis.MessageEvent || /*@__PURE__*/ notImplementedClass("MessageEvent"); +export default { + METHODS, + STATUS_CODES, + maxHeaderSize, + IncomingMessage, + ServerResponse, + WebSocket, + CloseEvent, + MessageEvent, + createServer, + request, + get, + Server, + OutgoingMessage, + ClientRequest, + Agent, + globalAgent, + validateHeaderName, + validateHeaderValue, + setMaxIdleHTTPParsers, + _connectionListener +}; diff --git a/worker/node_modules/unenv/dist/runtime/node/http2.d.mts b/worker/node_modules/unenv/dist/runtime/node/http2.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..50ee9d4434fbb16d472f10e4513623815308affd --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/http2.d.mts @@ -0,0 +1,14 @@ +import type nodeHttp2 from "node:http2"; +export declare const constants: typeof nodeHttp2.constants; +export declare const createSecureServer: unknown; +export declare const createServer: unknown; +export declare const connect: typeof nodeHttp2.connect; +export declare const performServerHandshake: typeof nodeHttp2.performServerHandshake; +export declare const Http2ServerRequest: typeof nodeHttp2.Http2ServerRequest; +export declare const Http2ServerResponse: typeof nodeHttp2.Http2ServerResponse; +export declare const getDefaultSettings: typeof nodeHttp2.getDefaultSettings; +export declare const getPackedSettings: typeof nodeHttp2.getPackedSettings; +export declare const getUnpackedSettings: typeof nodeHttp2.getUnpackedSettings; +export declare const sensitiveHeaders: typeof nodeHttp2.sensitiveHeaders; +declare const _default: {}; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/http2.mjs b/worker/node_modules/unenv/dist/runtime/node/http2.mjs new file mode 100644 index 0000000000000000000000000000000000000000..260c36f8f19a840c2bf48bdc9048bfb653d2a696 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/http2.mjs @@ -0,0 +1,282 @@ +import { notImplemented, notImplementedClass } from "../_internal/utils.mjs"; +import { NGHTTP2_ERR_FRAME_SIZE_ERROR, NGHTTP2_SESSION_SERVER, NGHTTP2_SESSION_CLIENT, NGHTTP2_STREAM_STATE_IDLE, NGHTTP2_STREAM_STATE_OPEN, NGHTTP2_STREAM_STATE_RESERVED_LOCAL, NGHTTP2_STREAM_STATE_RESERVED_REMOTE, NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL, NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE, NGHTTP2_STREAM_STATE_CLOSED, NGHTTP2_FLAG_NONE, NGHTTP2_FLAG_END_STREAM, NGHTTP2_FLAG_END_HEADERS, NGHTTP2_FLAG_ACK, NGHTTP2_FLAG_PADDED, NGHTTP2_FLAG_PRIORITY, DEFAULT_SETTINGS_HEADER_TABLE_SIZE, DEFAULT_SETTINGS_ENABLE_PUSH, DEFAULT_SETTINGS_MAX_CONCURRENT_STREAMS, DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE, DEFAULT_SETTINGS_MAX_FRAME_SIZE, DEFAULT_SETTINGS_MAX_HEADER_LIST_SIZE, DEFAULT_SETTINGS_ENABLE_CONNECT_PROTOCOL, MAX_MAX_FRAME_SIZE, MIN_MAX_FRAME_SIZE, MAX_INITIAL_WINDOW_SIZE, NGHTTP2_SETTINGS_HEADER_TABLE_SIZE, NGHTTP2_SETTINGS_ENABLE_PUSH, NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS, NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE, NGHTTP2_SETTINGS_MAX_FRAME_SIZE, NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE, NGHTTP2_SETTINGS_ENABLE_CONNECT_PROTOCOL, PADDING_STRATEGY_NONE, PADDING_STRATEGY_ALIGNED, PADDING_STRATEGY_MAX, PADDING_STRATEGY_CALLBACK, NGHTTP2_NO_ERROR, NGHTTP2_PROTOCOL_ERROR, NGHTTP2_INTERNAL_ERROR, NGHTTP2_FLOW_CONTROL_ERROR, NGHTTP2_SETTINGS_TIMEOUT, NGHTTP2_STREAM_CLOSED, NGHTTP2_FRAME_SIZE_ERROR, NGHTTP2_REFUSED_STREAM, NGHTTP2_CANCEL, NGHTTP2_COMPRESSION_ERROR, NGHTTP2_CONNECT_ERROR, NGHTTP2_ENHANCE_YOUR_CALM, NGHTTP2_INADEQUATE_SECURITY, NGHTTP2_HTTP_1_1_REQUIRED, NGHTTP2_DEFAULT_WEIGHT, HTTP2_HEADER_STATUS, HTTP2_HEADER_METHOD, HTTP2_HEADER_AUTHORITY, HTTP2_HEADER_SCHEME, HTTP2_HEADER_PATH, HTTP2_HEADER_PROTOCOL, HTTP2_HEADER_ACCEPT_ENCODING, HTTP2_HEADER_ACCEPT_LANGUAGE, HTTP2_HEADER_ACCEPT_RANGES, HTTP2_HEADER_ACCEPT, HTTP2_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS, HTTP2_HEADER_ACCESS_CONTROL_ALLOW_HEADERS, HTTP2_HEADER_ACCESS_CONTROL_ALLOW_METHODS, HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN, HTTP2_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS, HTTP2_HEADER_ACCESS_CONTROL_REQUEST_HEADERS, HTTP2_HEADER_ACCESS_CONTROL_REQUEST_METHOD, HTTP2_HEADER_AGE, HTTP2_HEADER_AUTHORIZATION, HTTP2_HEADER_CACHE_CONTROL, HTTP2_HEADER_CONNECTION, HTTP2_HEADER_CONTENT_DISPOSITION, HTTP2_HEADER_CONTENT_ENCODING, HTTP2_HEADER_CONTENT_LENGTH, HTTP2_HEADER_CONTENT_TYPE, HTTP2_HEADER_COOKIE, HTTP2_HEADER_DATE, HTTP2_HEADER_ETAG, HTTP2_HEADER_FORWARDED, HTTP2_HEADER_HOST, HTTP2_HEADER_IF_MODIFIED_SINCE, HTTP2_HEADER_IF_NONE_MATCH, HTTP2_HEADER_IF_RANGE, HTTP2_HEADER_LAST_MODIFIED, HTTP2_HEADER_LINK, HTTP2_HEADER_LOCATION, HTTP2_HEADER_RANGE, HTTP2_HEADER_REFERER, HTTP2_HEADER_SERVER, HTTP2_HEADER_SET_COOKIE, HTTP2_HEADER_STRICT_TRANSPORT_SECURITY, HTTP2_HEADER_TRANSFER_ENCODING, HTTP2_HEADER_TE, HTTP2_HEADER_UPGRADE_INSECURE_REQUESTS, HTTP2_HEADER_UPGRADE, HTTP2_HEADER_USER_AGENT, HTTP2_HEADER_VARY, HTTP2_HEADER_X_CONTENT_TYPE_OPTIONS, HTTP2_HEADER_X_FRAME_OPTIONS, HTTP2_HEADER_KEEP_ALIVE, HTTP2_HEADER_PROXY_CONNECTION, HTTP2_HEADER_X_XSS_PROTECTION, HTTP2_HEADER_ALT_SVC, HTTP2_HEADER_CONTENT_SECURITY_POLICY, HTTP2_HEADER_EARLY_DATA, HTTP2_HEADER_EXPECT_CT, HTTP2_HEADER_ORIGIN, HTTP2_HEADER_PURPOSE, HTTP2_HEADER_TIMING_ALLOW_ORIGIN, HTTP2_HEADER_X_FORWARDED_FOR, HTTP2_HEADER_PRIORITY, HTTP2_HEADER_ACCEPT_CHARSET, HTTP2_HEADER_ACCESS_CONTROL_MAX_AGE, HTTP2_HEADER_ALLOW, HTTP2_HEADER_CONTENT_LANGUAGE, HTTP2_HEADER_CONTENT_LOCATION, HTTP2_HEADER_CONTENT_MD5, HTTP2_HEADER_CONTENT_RANGE, HTTP2_HEADER_DNT, HTTP2_HEADER_EXPECT, HTTP2_HEADER_EXPIRES, HTTP2_HEADER_FROM, HTTP2_HEADER_IF_MATCH, HTTP2_HEADER_IF_UNMODIFIED_SINCE, HTTP2_HEADER_MAX_FORWARDS, HTTP2_HEADER_PREFER, HTTP2_HEADER_PROXY_AUTHENTICATE, HTTP2_HEADER_PROXY_AUTHORIZATION, HTTP2_HEADER_REFRESH, HTTP2_HEADER_RETRY_AFTER, HTTP2_HEADER_TRAILER, HTTP2_HEADER_TK, HTTP2_HEADER_VIA, HTTP2_HEADER_WARNING, HTTP2_HEADER_WWW_AUTHENTICATE, HTTP2_HEADER_HTTP2_SETTINGS, HTTP2_METHOD_ACL, HTTP2_METHOD_BASELINE_CONTROL, HTTP2_METHOD_BIND, HTTP2_METHOD_CHECKIN, HTTP2_METHOD_CHECKOUT, HTTP2_METHOD_CONNECT, HTTP2_METHOD_COPY, HTTP2_METHOD_DELETE, HTTP2_METHOD_GET, HTTP2_METHOD_HEAD, HTTP2_METHOD_LABEL, HTTP2_METHOD_LINK, HTTP2_METHOD_LOCK, HTTP2_METHOD_MERGE, HTTP2_METHOD_MKACTIVITY, HTTP2_METHOD_MKCALENDAR, HTTP2_METHOD_MKCOL, HTTP2_METHOD_MKREDIRECTREF, HTTP2_METHOD_MKWORKSPACE, HTTP2_METHOD_MOVE, HTTP2_METHOD_OPTIONS, HTTP2_METHOD_ORDERPATCH, HTTP2_METHOD_PATCH, HTTP2_METHOD_POST, HTTP2_METHOD_PRI, HTTP2_METHOD_PROPFIND, HTTP2_METHOD_PROPPATCH, HTTP2_METHOD_PUT, HTTP2_METHOD_REBIND, HTTP2_METHOD_REPORT, HTTP2_METHOD_SEARCH, HTTP2_METHOD_TRACE, HTTP2_METHOD_UNBIND, HTTP2_METHOD_UNCHECKOUT, HTTP2_METHOD_UNLINK, HTTP2_METHOD_UNLOCK, HTTP2_METHOD_UPDATE, HTTP2_METHOD_UPDATEREDIRECTREF, HTTP2_METHOD_VERSION_CONTROL, HTTP_STATUS_CONTINUE, HTTP_STATUS_SWITCHING_PROTOCOLS, HTTP_STATUS_PROCESSING, HTTP_STATUS_EARLY_HINTS, HTTP_STATUS_OK, HTTP_STATUS_CREATED, HTTP_STATUS_ACCEPTED, HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION, HTTP_STATUS_NO_CONTENT, HTTP_STATUS_RESET_CONTENT, HTTP_STATUS_PARTIAL_CONTENT, HTTP_STATUS_MULTI_STATUS, HTTP_STATUS_ALREADY_REPORTED, HTTP_STATUS_IM_USED, HTTP_STATUS_MULTIPLE_CHOICES, HTTP_STATUS_MOVED_PERMANENTLY, HTTP_STATUS_FOUND, HTTP_STATUS_SEE_OTHER, HTTP_STATUS_NOT_MODIFIED, HTTP_STATUS_USE_PROXY, HTTP_STATUS_TEMPORARY_REDIRECT, HTTP_STATUS_PERMANENT_REDIRECT, HTTP_STATUS_BAD_REQUEST, HTTP_STATUS_UNAUTHORIZED, HTTP_STATUS_PAYMENT_REQUIRED, HTTP_STATUS_FORBIDDEN, HTTP_STATUS_NOT_FOUND, HTTP_STATUS_METHOD_NOT_ALLOWED, HTTP_STATUS_NOT_ACCEPTABLE, HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED, HTTP_STATUS_REQUEST_TIMEOUT, HTTP_STATUS_CONFLICT, HTTP_STATUS_GONE, HTTP_STATUS_LENGTH_REQUIRED, HTTP_STATUS_PRECONDITION_FAILED, HTTP_STATUS_PAYLOAD_TOO_LARGE, HTTP_STATUS_URI_TOO_LONG, HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, HTTP_STATUS_RANGE_NOT_SATISFIABLE, HTTP_STATUS_EXPECTATION_FAILED, HTTP_STATUS_TEAPOT, HTTP_STATUS_MISDIRECTED_REQUEST, HTTP_STATUS_UNPROCESSABLE_ENTITY, HTTP_STATUS_LOCKED, HTTP_STATUS_FAILED_DEPENDENCY, HTTP_STATUS_TOO_EARLY, HTTP_STATUS_UPGRADE_REQUIRED, HTTP_STATUS_PRECONDITION_REQUIRED, HTTP_STATUS_TOO_MANY_REQUESTS, HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE, HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS, HTTP_STATUS_INTERNAL_SERVER_ERROR, HTTP_STATUS_NOT_IMPLEMENTED, HTTP_STATUS_BAD_GATEWAY, HTTP_STATUS_SERVICE_UNAVAILABLE, HTTP_STATUS_GATEWAY_TIMEOUT, HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED, HTTP_STATUS_VARIANT_ALSO_NEGOTIATES, HTTP_STATUS_INSUFFICIENT_STORAGE, HTTP_STATUS_LOOP_DETECTED, HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED, HTTP_STATUS_NOT_EXTENDED, HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED } from "./internal/http2/constants.mjs"; +export const constants = { + NGHTTP2_ERR_FRAME_SIZE_ERROR, + NGHTTP2_SESSION_SERVER, + NGHTTP2_SESSION_CLIENT, + NGHTTP2_STREAM_STATE_IDLE, + NGHTTP2_STREAM_STATE_OPEN, + NGHTTP2_STREAM_STATE_RESERVED_LOCAL, + NGHTTP2_STREAM_STATE_RESERVED_REMOTE, + NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL, + NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE, + NGHTTP2_STREAM_STATE_CLOSED, + NGHTTP2_FLAG_NONE, + NGHTTP2_FLAG_END_STREAM, + NGHTTP2_FLAG_END_HEADERS, + NGHTTP2_FLAG_ACK, + NGHTTP2_FLAG_PADDED, + NGHTTP2_FLAG_PRIORITY, + DEFAULT_SETTINGS_HEADER_TABLE_SIZE, + DEFAULT_SETTINGS_ENABLE_PUSH, + DEFAULT_SETTINGS_MAX_CONCURRENT_STREAMS, + DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE, + DEFAULT_SETTINGS_MAX_FRAME_SIZE, + DEFAULT_SETTINGS_MAX_HEADER_LIST_SIZE, + DEFAULT_SETTINGS_ENABLE_CONNECT_PROTOCOL, + MAX_MAX_FRAME_SIZE, + MIN_MAX_FRAME_SIZE, + MAX_INITIAL_WINDOW_SIZE, + NGHTTP2_SETTINGS_HEADER_TABLE_SIZE, + NGHTTP2_SETTINGS_ENABLE_PUSH, + NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS, + NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE, + NGHTTP2_SETTINGS_MAX_FRAME_SIZE, + NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE, + NGHTTP2_SETTINGS_ENABLE_CONNECT_PROTOCOL, + PADDING_STRATEGY_NONE, + PADDING_STRATEGY_ALIGNED, + PADDING_STRATEGY_MAX, + PADDING_STRATEGY_CALLBACK, + NGHTTP2_NO_ERROR, + NGHTTP2_PROTOCOL_ERROR, + NGHTTP2_INTERNAL_ERROR, + NGHTTP2_FLOW_CONTROL_ERROR, + NGHTTP2_SETTINGS_TIMEOUT, + NGHTTP2_STREAM_CLOSED, + NGHTTP2_FRAME_SIZE_ERROR, + NGHTTP2_REFUSED_STREAM, + NGHTTP2_CANCEL, + NGHTTP2_COMPRESSION_ERROR, + NGHTTP2_CONNECT_ERROR, + NGHTTP2_ENHANCE_YOUR_CALM, + NGHTTP2_INADEQUATE_SECURITY, + NGHTTP2_HTTP_1_1_REQUIRED, + NGHTTP2_DEFAULT_WEIGHT, + HTTP2_HEADER_STATUS, + HTTP2_HEADER_METHOD, + HTTP2_HEADER_AUTHORITY, + HTTP2_HEADER_SCHEME, + HTTP2_HEADER_PATH, + HTTP2_HEADER_PROTOCOL, + HTTP2_HEADER_ACCEPT_ENCODING, + HTTP2_HEADER_ACCEPT_LANGUAGE, + HTTP2_HEADER_ACCEPT_RANGES, + HTTP2_HEADER_ACCEPT, + HTTP2_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS, + HTTP2_HEADER_ACCESS_CONTROL_ALLOW_HEADERS, + HTTP2_HEADER_ACCESS_CONTROL_ALLOW_METHODS, + HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN, + HTTP2_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS, + HTTP2_HEADER_ACCESS_CONTROL_REQUEST_HEADERS, + HTTP2_HEADER_ACCESS_CONTROL_REQUEST_METHOD, + HTTP2_HEADER_AGE, + HTTP2_HEADER_AUTHORIZATION, + HTTP2_HEADER_CACHE_CONTROL, + HTTP2_HEADER_CONNECTION, + HTTP2_HEADER_CONTENT_DISPOSITION, + HTTP2_HEADER_CONTENT_ENCODING, + HTTP2_HEADER_CONTENT_LENGTH, + HTTP2_HEADER_CONTENT_TYPE, + HTTP2_HEADER_COOKIE, + HTTP2_HEADER_DATE, + HTTP2_HEADER_ETAG, + HTTP2_HEADER_FORWARDED, + HTTP2_HEADER_HOST, + HTTP2_HEADER_IF_MODIFIED_SINCE, + HTTP2_HEADER_IF_NONE_MATCH, + HTTP2_HEADER_IF_RANGE, + HTTP2_HEADER_LAST_MODIFIED, + HTTP2_HEADER_LINK, + HTTP2_HEADER_LOCATION, + HTTP2_HEADER_RANGE, + HTTP2_HEADER_REFERER, + HTTP2_HEADER_SERVER, + HTTP2_HEADER_SET_COOKIE, + HTTP2_HEADER_STRICT_TRANSPORT_SECURITY, + HTTP2_HEADER_TRANSFER_ENCODING, + HTTP2_HEADER_TE, + HTTP2_HEADER_UPGRADE_INSECURE_REQUESTS, + HTTP2_HEADER_UPGRADE, + HTTP2_HEADER_USER_AGENT, + HTTP2_HEADER_VARY, + HTTP2_HEADER_X_CONTENT_TYPE_OPTIONS, + HTTP2_HEADER_X_FRAME_OPTIONS, + HTTP2_HEADER_KEEP_ALIVE, + HTTP2_HEADER_PROXY_CONNECTION, + HTTP2_HEADER_X_XSS_PROTECTION, + HTTP2_HEADER_ALT_SVC, + HTTP2_HEADER_CONTENT_SECURITY_POLICY, + HTTP2_HEADER_EARLY_DATA, + HTTP2_HEADER_EXPECT_CT, + HTTP2_HEADER_ORIGIN, + HTTP2_HEADER_PURPOSE, + HTTP2_HEADER_TIMING_ALLOW_ORIGIN, + HTTP2_HEADER_X_FORWARDED_FOR, + HTTP2_HEADER_PRIORITY, + HTTP2_HEADER_ACCEPT_CHARSET, + HTTP2_HEADER_ACCESS_CONTROL_MAX_AGE, + HTTP2_HEADER_ALLOW, + HTTP2_HEADER_CONTENT_LANGUAGE, + HTTP2_HEADER_CONTENT_LOCATION, + HTTP2_HEADER_CONTENT_MD5, + HTTP2_HEADER_CONTENT_RANGE, + HTTP2_HEADER_DNT, + HTTP2_HEADER_EXPECT, + HTTP2_HEADER_EXPIRES, + HTTP2_HEADER_FROM, + HTTP2_HEADER_IF_MATCH, + HTTP2_HEADER_IF_UNMODIFIED_SINCE, + HTTP2_HEADER_MAX_FORWARDS, + HTTP2_HEADER_PREFER, + HTTP2_HEADER_PROXY_AUTHENTICATE, + HTTP2_HEADER_PROXY_AUTHORIZATION, + HTTP2_HEADER_REFRESH, + HTTP2_HEADER_RETRY_AFTER, + HTTP2_HEADER_TRAILER, + HTTP2_HEADER_TK, + HTTP2_HEADER_VIA, + HTTP2_HEADER_WARNING, + HTTP2_HEADER_WWW_AUTHENTICATE, + HTTP2_HEADER_HTTP2_SETTINGS, + HTTP2_METHOD_ACL, + HTTP2_METHOD_BASELINE_CONTROL, + HTTP2_METHOD_BIND, + HTTP2_METHOD_CHECKIN, + HTTP2_METHOD_CHECKOUT, + HTTP2_METHOD_CONNECT, + HTTP2_METHOD_COPY, + HTTP2_METHOD_DELETE, + HTTP2_METHOD_GET, + HTTP2_METHOD_HEAD, + HTTP2_METHOD_LABEL, + HTTP2_METHOD_LINK, + HTTP2_METHOD_LOCK, + HTTP2_METHOD_MERGE, + HTTP2_METHOD_MKACTIVITY, + HTTP2_METHOD_MKCALENDAR, + HTTP2_METHOD_MKCOL, + HTTP2_METHOD_MKREDIRECTREF, + HTTP2_METHOD_MKWORKSPACE, + HTTP2_METHOD_MOVE, + HTTP2_METHOD_OPTIONS, + HTTP2_METHOD_ORDERPATCH, + HTTP2_METHOD_PATCH, + HTTP2_METHOD_POST, + HTTP2_METHOD_PRI, + HTTP2_METHOD_PROPFIND, + HTTP2_METHOD_PROPPATCH, + HTTP2_METHOD_PUT, + HTTP2_METHOD_REBIND, + HTTP2_METHOD_REPORT, + HTTP2_METHOD_SEARCH, + HTTP2_METHOD_TRACE, + HTTP2_METHOD_UNBIND, + HTTP2_METHOD_UNCHECKOUT, + HTTP2_METHOD_UNLINK, + HTTP2_METHOD_UNLOCK, + HTTP2_METHOD_UPDATE, + HTTP2_METHOD_UPDATEREDIRECTREF, + HTTP2_METHOD_VERSION_CONTROL, + HTTP_STATUS_CONTINUE, + HTTP_STATUS_SWITCHING_PROTOCOLS, + HTTP_STATUS_PROCESSING, + HTTP_STATUS_EARLY_HINTS, + HTTP_STATUS_OK, + HTTP_STATUS_CREATED, + HTTP_STATUS_ACCEPTED, + HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION, + HTTP_STATUS_NO_CONTENT, + HTTP_STATUS_RESET_CONTENT, + HTTP_STATUS_PARTIAL_CONTENT, + HTTP_STATUS_MULTI_STATUS, + HTTP_STATUS_ALREADY_REPORTED, + HTTP_STATUS_IM_USED, + HTTP_STATUS_MULTIPLE_CHOICES, + HTTP_STATUS_MOVED_PERMANENTLY, + HTTP_STATUS_FOUND, + HTTP_STATUS_SEE_OTHER, + HTTP_STATUS_NOT_MODIFIED, + HTTP_STATUS_USE_PROXY, + HTTP_STATUS_TEMPORARY_REDIRECT, + HTTP_STATUS_PERMANENT_REDIRECT, + HTTP_STATUS_BAD_REQUEST, + HTTP_STATUS_UNAUTHORIZED, + HTTP_STATUS_PAYMENT_REQUIRED, + HTTP_STATUS_FORBIDDEN, + HTTP_STATUS_NOT_FOUND, + HTTP_STATUS_METHOD_NOT_ALLOWED, + HTTP_STATUS_NOT_ACCEPTABLE, + HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED, + HTTP_STATUS_REQUEST_TIMEOUT, + HTTP_STATUS_CONFLICT, + HTTP_STATUS_GONE, + HTTP_STATUS_LENGTH_REQUIRED, + HTTP_STATUS_PRECONDITION_FAILED, + HTTP_STATUS_PAYLOAD_TOO_LARGE, + HTTP_STATUS_URI_TOO_LONG, + HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, + HTTP_STATUS_RANGE_NOT_SATISFIABLE, + HTTP_STATUS_EXPECTATION_FAILED, + HTTP_STATUS_TEAPOT, + HTTP_STATUS_MISDIRECTED_REQUEST, + HTTP_STATUS_UNPROCESSABLE_ENTITY, + HTTP_STATUS_LOCKED, + HTTP_STATUS_FAILED_DEPENDENCY, + HTTP_STATUS_TOO_EARLY, + HTTP_STATUS_UPGRADE_REQUIRED, + HTTP_STATUS_PRECONDITION_REQUIRED, + HTTP_STATUS_TOO_MANY_REQUESTS, + HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE, + HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS, + HTTP_STATUS_INTERNAL_SERVER_ERROR, + HTTP_STATUS_NOT_IMPLEMENTED, + HTTP_STATUS_BAD_GATEWAY, + HTTP_STATUS_SERVICE_UNAVAILABLE, + HTTP_STATUS_GATEWAY_TIMEOUT, + HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED, + HTTP_STATUS_VARIANT_ALSO_NEGOTIATES, + HTTP_STATUS_INSUFFICIENT_STORAGE, + HTTP_STATUS_LOOP_DETECTED, + HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED, + HTTP_STATUS_NOT_EXTENDED, + HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED +}; +export const createSecureServer = /*@__PURE__*/ notImplemented("http2.createSecureServer"); +export const createServer = /*@__PURE__*/ notImplemented("http2.createServer"); +export const connect = /*@__PURE__*/ notImplemented("http2.connect"); +export const performServerHandshake = /*@__PURE__*/ notImplemented("http2.performServerHandshake "); +export const Http2ServerRequest = /*@__PURE__*/ notImplementedClass("http2.Http2ServerRequest"); +export const Http2ServerResponse = /*@__PURE__*/ notImplementedClass("http2.Http2ServerResponse"); +export const getDefaultSettings = function() { + return Object.create({ + headerTableSize: 4096, + enablePush: true, + initialWindowSize: 65535, + maxFrameSize: 16384, + maxConcurrentStreams: 4294967295, + maxHeaderSize: 65535, + maxHeaderListSize: 65535, + enableConnectProtocol: false + }); +}; +export const getPackedSettings = function() { + return Buffer.from(""); +}; +export const getUnpackedSettings = function() { + return Object.create({}); +}; +export const sensitiveHeaders = /*@__PURE__*/ Symbol("nodejs.http2.sensitiveHeaders"); +export default { + constants, + createSecureServer, + createServer, + Http2ServerRequest, + Http2ServerResponse, + connect, + getDefaultSettings, + getPackedSettings, + getUnpackedSettings, + performServerHandshake, + sensitiveHeaders +}; diff --git a/worker/node_modules/unenv/dist/runtime/node/https.d.mts b/worker/node_modules/unenv/dist/runtime/node/https.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..ac8a2ab1078949605ee14cdce22c48ae809b80b2 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/https.d.mts @@ -0,0 +1,9 @@ +import type nodeHttps from "node:https"; +export declare const Server: typeof nodeHttps.Server; +export declare const Agent: typeof nodeHttps.Agent; +export declare const globalAgent: typeof nodeHttps.globalAgent; +export declare const get: unknown; +export declare const createServer: unknown; +export declare const request: unknown; +declare const _default: {}; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/https.mjs b/worker/node_modules/unenv/dist/runtime/node/https.mjs new file mode 100644 index 0000000000000000000000000000000000000000..2d41b2ae8c38d3e69f8804a37b6cc597755d8c60 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/https.mjs @@ -0,0 +1,16 @@ +import { notImplemented, notImplementedClass } from "../_internal/utils.mjs"; +import { Agent as HttpAgent } from "./internal/http/agent.mjs"; +export const Server = /*@__PURE__*/ notImplementedClass("https.Server"); +export const Agent = HttpAgent; +export const globalAgent = /*@__PURE__*/ new Agent(); +export const get = /*@__PURE__*/ notImplemented("https.get"); +export const createServer = /*@__PURE__*/ notImplemented("https.createServer"); +export const request = /*@__PURE__*/ notImplemented("https.request"); +export default { + Server, + Agent, + globalAgent, + get, + createServer, + request +}; diff --git a/worker/node_modules/unenv/dist/runtime/node/inspector.d.mts b/worker/node_modules/unenv/dist/runtime/node/inspector.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..cab05e793fc1db7427d723d4b281497cacc6dfbc --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/inspector.d.mts @@ -0,0 +1,10 @@ +import type nodeInspector from "node:inspector"; +export declare const close: typeof nodeInspector.close; +export declare const console: nodeInspector.InspectorConsole; +export declare const open: typeof nodeInspector.open; +export declare const url: typeof nodeInspector.url; +export declare const waitForDebugger: typeof nodeInspector.waitForDebugger; +export declare const Session: typeof nodeInspector.Session; +export declare const Network: typeof nodeInspector.Network; +declare const _default: {}; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/inspector.mjs b/worker/node_modules/unenv/dist/runtime/node/inspector.mjs new file mode 100644 index 0000000000000000000000000000000000000000..16480eb62ff1fc726fb6d74c90dc486f58c305d2 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/inspector.mjs @@ -0,0 +1,50 @@ +import { notImplementedClass, notImplemented } from "../_internal/utils.mjs"; +import noop from "../mock/noop.mjs"; +export const close = noop; +export const console = { + debug: noop, + error: noop, + info: noop, + log: noop, + warn: noop, + dir: noop, + dirxml: noop, + table: noop, + trace: noop, + group: noop, + groupCollapsed: noop, + groupEnd: noop, + clear: noop, + count: noop, + countReset: noop, + assert: noop, + profile: noop, + profileEnd: noop, + time: noop, + timeLog: noop, + timeStamp: noop +}; +export const open = () => ({ + __unenv__: true, + [Symbol.dispose]() { + return Promise.resolve(); + } +}); +export const url = () => undefined; +export const waitForDebugger = noop; +export const Session = /*@__PURE__*/ notImplementedClass("inspector.Session"); +export const Network = { + loadingFailed: /*@__PURE__*/ notImplemented("inspector.Network.loadingFailed"), + loadingFinished: /*@__PURE__*/ notImplemented("inspector.Network.loadingFinished"), + requestWillBeSent: /*@__PURE__*/ notImplemented("inspector.Network.requestWillBeSent"), + responseReceived: /*@__PURE__*/ notImplemented("inspector.Network.responseReceived") +}; +export default { + Session, + close, + console, + open, + url, + waitForDebugger, + Network +}; diff --git a/worker/node_modules/unenv/dist/runtime/node/inspector/promises.d.mts b/worker/node_modules/unenv/dist/runtime/node/inspector/promises.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..a6bd5c1e5245c5d16646aa80d8bddb5b03d29295 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/inspector/promises.d.mts @@ -0,0 +1,10 @@ +import type nodeInspectorPromises from "node:inspector/promises"; +export declare const console: typeof nodeInspectorPromises.console; +export declare const Network: unknown; +export declare const Session: unknown; +export declare const url: unknown; +export declare const waitForDebugger: unknown; +export declare const open: unknown; +export declare const close: unknown; +declare const _default: {}; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/inspector/promises.mjs b/worker/node_modules/unenv/dist/runtime/node/inspector/promises.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6a8b4181d12aa82f657226962b6cf6a3344ad161 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/inspector/promises.mjs @@ -0,0 +1,40 @@ +import { notImplemented, notImplementedClass } from "../../_internal/utils.mjs"; +import noop from "../../mock/noop.mjs"; +export const console = { + debug: noop, + error: noop, + info: noop, + log: noop, + warn: noop, + dir: noop, + dirxml: noop, + table: noop, + trace: noop, + group: noop, + groupCollapsed: noop, + groupEnd: noop, + clear: noop, + count: noop, + countReset: noop, + assert: noop, + profile: noop, + profileEnd: noop, + time: noop, + timeLog: noop, + timeStamp: noop +}; +export const Network = /*@__PURE__*/ notImplementedClass("inspectorPromises.Network"); +export const Session = /*@__PURE__*/ notImplementedClass("inspectorPromises.Session"); +export const url = /*@__PURE__*/ notImplemented("inspectorPromises.url"); +export const waitForDebugger = /*@__PURE__*/ notImplemented("inspectorPromises.waitForDebugger"); +export const open = /*@__PURE__*/ notImplemented("inspectorPromises.open"); +export const close = /*@__PURE__*/ notImplemented("inspectorPromises.close"); +export default { + close, + console, + Network, + open, + Session, + url, + waitForDebugger +}; diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/async_hooks/async-hook.d.mts b/worker/node_modules/unenv/dist/runtime/node/internal/async_hooks/async-hook.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..6922f47208812fa4dd7dd4946f3d5db4fada219b --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/async_hooks/async-hook.d.mts @@ -0,0 +1,6 @@ +import type nodeAsyncHooks from "node:async_hooks"; +export declare const createHook: typeof nodeAsyncHooks.createHook; +export declare const executionAsyncId: typeof nodeAsyncHooks.executionAsyncId; +export declare const executionAsyncResource: typeof nodeAsyncHooks.executionAsyncResource; +export declare const triggerAsyncId: typeof nodeAsyncHooks.triggerAsyncId; +export declare const asyncWrapProviders: typeof nodeAsyncHooks.asyncWrapProviders; diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/async_hooks/async-hook.mjs b/worker/node_modules/unenv/dist/runtime/node/internal/async_hooks/async-hook.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b8e147484a36f6c61328f0594bbb5321e8600800 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/async_hooks/async-hook.mjs @@ -0,0 +1,114 @@ +const kInit = /*@__PURE__*/ Symbol("init"); +const kBefore = /*@__PURE__*/ Symbol("before"); +const kAfter = /*@__PURE__*/ Symbol("after"); +const kDestroy = /*@__PURE__*/ Symbol("destroy"); +const kPromiseResolve = /*@__PURE__*/ Symbol("promiseResolve"); +class _AsyncHook { + __unenv__ = true; + _enabled = false; + _callbacks = {}; + constructor(callbacks = {}) { + this._callbacks = callbacks; + } + enable() { + this._enabled = true; + return this; + } + disable() { + this._enabled = false; + return this; + } + get [kInit]() { + return this._callbacks.init; + } + get [kBefore]() { + return this._callbacks.before; + } + get [kAfter]() { + return this._callbacks.after; + } + get [kDestroy]() { + return this._callbacks.destroy; + } + get [kPromiseResolve]() { + return this._callbacks.promiseResolve; + } +} +export const createHook = function createHook(callbacks) { + const asyncHook = new _AsyncHook(callbacks); + return asyncHook; +}; +export const executionAsyncId = function executionAsyncId() { + return 0; +}; +export const executionAsyncResource = function() { + return Object.create(null); +}; +export const triggerAsyncId = function() { + return 0; +}; +export const asyncWrapProviders = Object.assign(Object.create(null), { + NONE: 0, + DIRHANDLE: 1, + DNSCHANNEL: 2, + ELDHISTOGRAM: 3, + FILEHANDLE: 4, + FILEHANDLECLOSEREQ: 5, + BLOBREADER: 6, + FSEVENTWRAP: 7, + FSREQCALLBACK: 8, + FSREQPROMISE: 9, + GETADDRINFOREQWRAP: 10, + GETNAMEINFOREQWRAP: 11, + HEAPSNAPSHOT: 12, + HTTP2SESSION: 13, + HTTP2STREAM: 14, + HTTP2PING: 15, + HTTP2SETTINGS: 16, + HTTPINCOMINGMESSAGE: 17, + HTTPCLIENTREQUEST: 18, + JSSTREAM: 19, + JSUDPWRAP: 20, + MESSAGEPORT: 21, + PIPECONNECTWRAP: 22, + PIPESERVERWRAP: 23, + PIPEWRAP: 24, + PROCESSWRAP: 25, + PROMISE: 26, + QUERYWRAP: 27, + QUIC_ENDPOINT: 28, + QUIC_LOGSTREAM: 29, + QUIC_PACKET: 30, + QUIC_SESSION: 31, + QUIC_STREAM: 32, + QUIC_UDP: 33, + SHUTDOWNWRAP: 34, + SIGNALWRAP: 35, + STATWATCHER: 36, + STREAMPIPE: 37, + TCPCONNECTWRAP: 38, + TCPSERVERWRAP: 39, + TCPWRAP: 40, + TTYWRAP: 41, + UDPSENDWRAP: 42, + UDPWRAP: 43, + SIGINTWATCHDOG: 44, + WORKER: 45, + WORKERHEAPSNAPSHOT: 46, + WRITEWRAP: 47, + ZLIB: 48, + CHECKPRIMEREQUEST: 49, + PBKDF2REQUEST: 50, + KEYPAIRGENREQUEST: 51, + KEYGENREQUEST: 52, + KEYEXPORTREQUEST: 53, + CIPHERREQUEST: 54, + DERIVEBITSREQUEST: 55, + HASHREQUEST: 56, + RANDOMBYTESREQUEST: 57, + RANDOMPRIMEREQUEST: 58, + SCRYPTREQUEST: 59, + SIGNREQUEST: 60, + TLSWRAP: 61, + VERIFYREQUEST: 62 +}); diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/async_hooks/async-local-storage.d.mts b/worker/node_modules/unenv/dist/runtime/node/internal/async_hooks/async-local-storage.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..060b8273a5f5a1aad8daeea5a2415f3713991a92 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/async_hooks/async-local-storage.d.mts @@ -0,0 +1,2 @@ +import type nodeAsyncHooks from "node:async_hooks"; +export declare const AsyncLocalStorage: typeof nodeAsyncHooks.AsyncLocalStorage; diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/async_hooks/async-local-storage.mjs b/worker/node_modules/unenv/dist/runtime/node/internal/async_hooks/async-local-storage.mjs new file mode 100644 index 0000000000000000000000000000000000000000..73cb5aab4df2ebd1ded9813915ac39de9acb0a88 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/async_hooks/async-local-storage.mjs @@ -0,0 +1,35 @@ +class _AsyncLocalStorage { + __unenv__ = true; + _currentStore; + _enterStore; + _enabled = true; + getStore() { + return this._currentStore ?? this._enterStore; + } + disable() { + this._enabled = false; + } + enable() { + this._enabled = true; + } + enterWith(store) { + this._enterStore = store; + } + run(store, callback, ...args) { + this._currentStore = store; + const res = callback(...args); + this._currentStore = undefined; + return res; + } + exit(callback, ...args) { + const _previousStore = this._currentStore; + this._currentStore = undefined; + const res = callback(...args); + this._currentStore = _previousStore; + return res; + } + static snapshot() { + throw new Error("[unenv] `AsyncLocalStorage.snapshot` is not implemented!"); + } +} +export const AsyncLocalStorage = globalThis.AsyncLocalStorage || _AsyncLocalStorage; diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/async_hooks/async-resource.d.mts b/worker/node_modules/unenv/dist/runtime/node/internal/async_hooks/async-resource.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..4b6cc5420d6b4a8f550a2ef7a73be4d318f943e0 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/async_hooks/async-resource.d.mts @@ -0,0 +1,2 @@ +import type nodeAsyncHooks from "node:async_hooks"; +export declare const AsyncResource: typeof nodeAsyncHooks.AsyncResource; diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/async_hooks/async-resource.mjs b/worker/node_modules/unenv/dist/runtime/node/internal/async_hooks/async-resource.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ac870a34fdef67504314abdab820f6edfdd8145b --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/async_hooks/async-resource.mjs @@ -0,0 +1,36 @@ +import { executionAsyncId } from "./async-hook.mjs"; +let _asyncIdCounter = 100; +class _AsyncResource { + __unenv__ = true; + type; + _asyncId; + _triggerAsyncId; + constructor(type, triggerAsyncId = executionAsyncId()) { + this.type = type; + this._asyncId = -1 * _asyncIdCounter++; + this._triggerAsyncId = typeof triggerAsyncId === "number" ? triggerAsyncId : triggerAsyncId?.triggerAsyncId; + } + static bind(fn, type, thisArg) { + const resource = new AsyncResource(type ?? "anonymous"); + return resource.bind(fn); + } + bind(fn, thisArg) { + const binded = (...args) => this.runInAsyncScope(fn, thisArg, ...args); + binded.asyncResource = this; + return binded; + } + runInAsyncScope(fn, thisArg, ...args) { + const result = fn.apply(thisArg, args); + return result; + } + emitDestroy() { + return this; + } + asyncId() { + return this._asyncId; + } + triggerAsyncId() { + return this._triggerAsyncId; + } +} +export const AsyncResource = globalThis.AsyncResource || _AsyncResource; diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/buffer/base64.d.mts b/worker/node_modules/unenv/dist/runtime/node/internal/buffer/base64.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..d1c46b4a0975f5ae8e213e479e3803cde49acfd7 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/buffer/base64.d.mts @@ -0,0 +1,3 @@ +export declare function byteLength(b64); +export declare function toByteArray(b64); +export declare function fromByteArray(uint8); diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/buffer/base64.mjs b/worker/node_modules/unenv/dist/runtime/node/internal/buffer/base64.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f307fe5097949e76e616287fcb4311c8b4ec9b76 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/buffer/base64.mjs @@ -0,0 +1,87 @@ +const lookup = []; +const revLookup = []; +const Arr = typeof Uint8Array === "undefined" ? Array : Uint8Array; +const code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +for (let i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; +} +revLookup["-".charCodeAt(0)] = 62; +revLookup["_".charCodeAt(0)] = 63; +function getLens(b64) { + const len = b64.length; + if (len % 4 > 0) { + throw new Error("Invalid string. Length must be a multiple of 4"); + } + let validLen = b64.indexOf("="); + if (validLen === -1) { + validLen = len; + } + const placeHoldersLen = validLen === len ? 0 : 4 - validLen % 4; + return [validLen, placeHoldersLen]; +} +export function byteLength(b64) { + const lens = getLens(b64); + const validLen = lens[0]; + const placeHoldersLen = lens[1]; + return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; +} +function _byteLength(b64, validLen, placeHoldersLen) { + return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; +} +export function toByteArray(b64) { + let tmp; + const lens = getLens(b64); + const validLen = lens[0]; + const placeHoldersLen = lens[1]; + const arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)); + let curByte = 0; + const len = placeHoldersLen > 0 ? validLen - 4 : validLen; + let i; + for (i = 0; i < len; i += 4) { + tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)]; + arr[curByte++] = tmp >> 16 & 255; + arr[curByte++] = tmp >> 8 & 255; + arr[curByte++] = tmp & 255; + } + if (placeHoldersLen === 2) { + tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4; + arr[curByte++] = tmp & 255; + } + if (placeHoldersLen === 1) { + tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2; + arr[curByte++] = tmp >> 8 & 255; + arr[curByte++] = tmp & 255; + } + return arr; +} +function tripletToBase64(num) { + return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63]; +} +function encodeChunk(uint8, start, end) { + let tmp; + const output = []; + for (let i = start; i < end; i += 3) { + tmp = (uint8[i] << 16 & 16711680) + (uint8[i + 1] << 8 & 65280) + (uint8[i + 2] & 255); + output.push(tripletToBase64(tmp)); + } + return output.join(""); +} +export function fromByteArray(uint8) { + let tmp; + const len = uint8.length; + const extraBytes = len % 3; + const parts = []; + const maxChunkLength = 16383; + for (let i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength)); + } + if (extraBytes === 1) { + tmp = uint8[len - 1]; + parts.push(lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "=="); + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1]; + parts.push(lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "="); + } + return parts.join(""); +} diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/buffer/buffer.d.mts b/worker/node_modules/unenv/dist/runtime/node/internal/buffer/buffer.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..eed28c0a8e327bcb8d69209e2b18dfa943773ae9 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/buffer/buffer.d.mts @@ -0,0 +1,13 @@ +export declare const INSPECT_MAX_BYTES = 50; +export declare const kMaxLength: unknown; +/** +* The Buffer constructor returns instances of `Uint8Array` that have their +* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of +* `Uint8Array`, so the returned instances will have all the node `Buffer` methods +* and the `Uint8Array` methods. Square bracket notation works as expected -- it +* returns a single octet. +* +* The `Uint8Array` prototype remains unmodified. +*/ +export declare function Buffer(arg, encodingOrOffset, length); +export declare function SlowBuffer(length); diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/buffer/buffer.mjs b/worker/node_modules/unenv/dist/runtime/node/internal/buffer/buffer.mjs new file mode 100644 index 0000000000000000000000000000000000000000..895525acee53ac8428168f698615e44fd2b4f8e0 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/buffer/buffer.mjs @@ -0,0 +1,1739 @@ +/*! +* The buffer module from node.js, for the browser. +* +* @author Feross Aboukhadijeh +* @license MIT +*/ +import * as base64 from "./base64.mjs"; +import * as ieee754 from "./ieee754.mjs"; +const customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null; +export const INSPECT_MAX_BYTES = 50; +const K_MAX_LENGTH = 2147483647; +export const kMaxLength = K_MAX_LENGTH; +/** +* If `Buffer.TYPED_ARRAY_SUPPORT`: +* === true Use Uint8Array implementation (fastest) +* === false Print warning and recommend using `buffer` v4.x which has an Object +* implementation (most compatible, even IE6) +* +* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, +* Opera 11.6+, iOS 4.2+. +* +* We report that the browser does not support typed arrays if the are not subclassable +* using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` +* (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support +* for __proto__ and has a buggy typed array implementation. +*/ +Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport(); +if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && typeof console.error === "function") { + console.error("This environment lacks typed array (Uint8Array) support which is required by " + "`buffer` v5.x. Use `buffer` v4.x if you require old browser support."); +} +function typedArraySupport() { + try { + const arr = new Uint8Array(1); + const proto = { foo: function() { + return 42; + } }; + Object.setPrototypeOf(proto, Uint8Array.prototype); + Object.setPrototypeOf(arr, proto); + return arr.foo() === 42; + } catch { + return false; + } +} +Object.defineProperty(Buffer.prototype, "parent", { + enumerable: true, + get: function() { + if (!Buffer.isBuffer(this)) { + return; + } + return this.buffer; + } +}); +Object.defineProperty(Buffer.prototype, "offset", { + enumerable: true, + get: function() { + if (!Buffer.isBuffer(this)) { + return; + } + return this.byteOffset; + } +}); +function createBuffer(length) { + if (length > K_MAX_LENGTH) { + throw new RangeError("The value \"" + length + "\" is invalid for option \"size\""); + } + const buf = new Uint8Array(length); + Object.setPrototypeOf(buf, Buffer.prototype); + return buf; +} +/** +* The Buffer constructor returns instances of `Uint8Array` that have their +* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of +* `Uint8Array`, so the returned instances will have all the node `Buffer` methods +* and the `Uint8Array` methods. Square bracket notation works as expected -- it +* returns a single octet. +* +* The `Uint8Array` prototype remains unmodified. +*/ +export function Buffer(arg, encodingOrOffset, length) { + if (typeof arg === "number") { + if (typeof encodingOrOffset === "string") { + throw new TypeError("The \"string\" argument must be of type string. Received type number"); + } + return allocUnsafe(arg); + } + return from(arg, encodingOrOffset, length); +} +Buffer.poolSize = 8192; +function from(value, encodingOrOffset, length) { + if (typeof value === "string") { + return fromString(value, encodingOrOffset); + } + if (ArrayBuffer.isView(value)) { + return fromArrayView(value); + } + if (value == null) { + throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, " + "or Array-like Object. Received type " + typeof value); + } + if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) { + return fromArrayBuffer(value, encodingOrOffset, length); + } + if (typeof SharedArrayBuffer !== "undefined" && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length); + } + if (typeof value === "number") { + throw new TypeError("The \"value\" argument must not be of type number. Received type number"); + } + const valueOf = value.valueOf && value.valueOf(); + if (valueOf != null && valueOf !== value) { + return Buffer.from(valueOf, encodingOrOffset, length); + } + const b = fromObject(value); + if (b) { + return b; + } + if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === "function") { + return Buffer.from(value[Symbol.toPrimitive]("string"), encodingOrOffset, length); + } + throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, " + "or Array-like Object. Received type " + typeof value); +} +/** +* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError +* if value is a number. +* Buffer.from(str[, encoding]) +* Buffer.from(array) +* Buffer.from(buffer) +* Buffer.from(arrayBuffer[, byteOffset[, length]]) +**/ +Buffer.from = function(value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length); +}; +Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype); +Object.setPrototypeOf(Buffer, Uint8Array); +function assertSize(size) { + if (typeof size !== "number") { + throw new TypeError("\"size\" argument must be of type number"); + } else if (size < 0) { + throw new RangeError("The value \"" + size + "\" is invalid for option \"size\""); + } +} +function alloc(size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(size); + } + if (fill !== undefined) { + return typeof encoding === "string" ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill); + } + return createBuffer(size); +} +/** +* Creates a new filled Buffer instance. +* alloc(size[, fill[, encoding]]) +**/ +Buffer.alloc = function(size, fill, encoding) { + return alloc(size, fill, encoding); +}; +function allocUnsafe(size) { + assertSize(size); + return createBuffer(size < 0 ? 0 : checked(size) | 0); +} +/** +* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. +* */ +Buffer.allocUnsafe = function(size) { + return allocUnsafe(size); +}; +/** +* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. +*/ +Buffer.allocUnsafeSlow = function(size) { + return allocUnsafe(size); +}; +function fromString(string, encoding) { + if (typeof encoding !== "string" || encoding === "") { + encoding = "utf8"; + } + if (!Buffer.isEncoding(encoding)) { + throw new TypeError("Unknown encoding: " + encoding); + } + const length = byteLength(string, encoding) | 0; + let buf = createBuffer(length); + const actual = buf.write(string, encoding); + if (actual !== length) { + buf = buf.slice(0, actual); + } + return buf; +} +function fromArrayLike(array) { + const length = array.length < 0 ? 0 : checked(array.length) | 0; + const buf = createBuffer(length); + for (let i = 0; i < length; i += 1) { + buf[i] = array[i] & 255; + } + return buf; +} +function fromArrayView(arrayView) { + if (isInstance(arrayView, Uint8Array)) { + const copy = new Uint8Array(arrayView); + return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength); + } + return fromArrayLike(arrayView); +} +function fromArrayBuffer(array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError("\"offset\" is outside of buffer bounds"); + } + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError("\"length\" is outside of buffer bounds"); + } + let buf; + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array); + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset); + } else { + buf = new Uint8Array(array, byteOffset, length); + } + Object.setPrototypeOf(buf, Buffer.prototype); + return buf; +} +function fromObject(obj) { + if (Buffer.isBuffer(obj)) { + const len = checked(obj.length) | 0; + const buf = createBuffer(len); + if (buf.length === 0) { + return buf; + } + obj.copy(buf, 0, 0, len); + return buf; + } + if (obj.length !== undefined) { + if (typeof obj.length !== "number" || numberIsNaN(obj.length)) { + return createBuffer(0); + } + return fromArrayLike(obj); + } + if (obj.type === "Buffer" && Array.isArray(obj.data)) { + return fromArrayLike(obj.data); + } +} +function checked(length) { + if (length >= K_MAX_LENGTH) { + throw new RangeError("Attempt to allocate Buffer larger than maximum " + "size: 0x" + K_MAX_LENGTH.toString(16) + " bytes"); + } + return length | 0; +} +export function SlowBuffer(length) { + if (+length != length) { + length = 0; + } + return Buffer.alloc(+length); +} +Buffer.isBuffer = function isBuffer(b) { + return b != null && b._isBuffer === true && b !== Buffer.prototype; +}; +Buffer.compare = function compare(a, b) { + if (isInstance(a, Uint8Array)) { + a = Buffer.from(a, a.offset, a.byteLength); + } + if (isInstance(b, Uint8Array)) { + b = Buffer.from(b, b.offset, b.byteLength); + } + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError("The \"buf1\", \"buf2\" arguments must be one of type Buffer or Uint8Array"); + } + if (a === b) { + return 0; + } + let x = a.length; + let y = b.length; + for (let i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break; + } + } + if (x < y) { + return -1; + } + if (y < x) { + return 1; + } + return 0; +}; +Buffer.isEncoding = function isEncoding(encoding) { + switch (String(encoding).toLowerCase()) { + case "hex": + case "utf8": + case "utf-8": + case "ascii": + case "latin1": + case "binary": + case "base64": + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": return true; + default: return false; + } +}; +Buffer.concat = function concat(list, length) { + if (!Array.isArray(list)) { + throw new TypeError("\"list\" argument must be an Array of Buffers"); + } + if (list.length === 0) { + return Buffer.alloc(0); + } + let i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + const buffer = Buffer.allocUnsafe(length); + let pos = 0; + for (i = 0; i < list.length; ++i) { + let buf = list[i]; + if (isInstance(buf, Uint8Array)) { + if (pos + buf.length > buffer.length) { + if (!Buffer.isBuffer(buf)) { + buf = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); + } + buf.copy(buffer, pos); + } else { + Uint8Array.prototype.set.call(buffer, buf, pos); + } + } else if (Buffer.isBuffer(buf)) { + buf.copy(buffer, pos); + } else { + throw new TypeError("\"list\" argument must be an Array of Buffers"); + } + pos += buf.length; + } + return buffer; +}; +function byteLength(string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length; + } + if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { + return string.byteLength; + } + if (typeof string !== "string") { + throw new TypeError("The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. " + "Received type " + typeof string); + } + const len = string.length; + const mustMatch = arguments.length > 2 && arguments[2] === true; + if (!mustMatch && len === 0) { + return 0; + } + let loweredCase = false; + for (;;) { + switch (encoding) { + case "ascii": + case "latin1": + case "binary": return len; + case "utf8": + case "utf-8": return utf8ToBytes(string).length; + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": return len * 2; + case "hex": return len >>> 1; + case "base64": return base64ToBytes(string).length; + default: + if (loweredCase) { + return mustMatch ? -1 : utf8ToBytes(string).length; + } + encoding = ("" + encoding).toLowerCase(); + loweredCase = true; + } + } +} +Buffer.byteLength = byteLength; +function slowToString(encoding, start, end) { + let loweredCase = false; + if (start === undefined || start < 0) { + start = 0; + } + if (start > this.length) { + return ""; + } + if (end === undefined || end > this.length) { + end = this.length; + } + if (end <= 0) { + return ""; + } + end >>>= 0; + start >>>= 0; + if (end <= start) { + return ""; + } + if (!encoding) { + encoding = "utf8"; + } + while (true) { + switch (encoding) { + case "hex": return hexSlice(this, start, end); + case "utf8": + case "utf-8": return utf8Slice(this, start, end); + case "ascii": return asciiSlice(this, start, end); + case "latin1": + case "binary": return latin1Slice(this, start, end); + case "base64": return base64Slice(this, start, end); + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": return utf16leSlice(this, start, end); + default: + if (loweredCase) { + throw new TypeError("Unknown encoding: " + encoding); + } + encoding = (encoding + "").toLowerCase(); + loweredCase = true; + } + } +} +Buffer.prototype._isBuffer = true; +function swap(b, n, m) { + const i = b[n]; + b[n] = b[m]; + b[m] = i; +} +Buffer.prototype.swap16 = function swap16() { + const len = this.length; + if (len % 2 !== 0) { + throw new RangeError("Buffer size must be a multiple of 16-bits"); + } + for (let i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this; +}; +Buffer.prototype.swap32 = function swap32() { + const len = this.length; + if (len % 4 !== 0) { + throw new RangeError("Buffer size must be a multiple of 32-bits"); + } + for (let i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this; +}; +Buffer.prototype.swap64 = function swap64() { + const len = this.length; + if (len % 8 !== 0) { + throw new RangeError("Buffer size must be a multiple of 64-bits"); + } + for (let i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this; +}; +Buffer.prototype.toString = function toString() { + const length = this.length; + if (length === 0) { + return ""; + } + if (arguments.length === 0) { + return utf8Slice(this, 0, length); + } + return Reflect.apply(slowToString, this, arguments); +}; +Buffer.prototype.toLocaleString = Buffer.prototype.toString; +Buffer.prototype.equals = function equals(b) { + if (!Buffer.isBuffer(b)) { + throw new TypeError("Argument must be a Buffer"); + } + if (this === b) { + return true; + } + return Buffer.compare(this, b) === 0; +}; +Buffer.prototype.inspect = function inspect() { + let str = ""; + const max = INSPECT_MAX_BYTES; + str = this.toString("hex", 0, max).replace(/(.{2})/g, "$1 ").trim(); + if (this.length > max) { + str += " ... "; + } + return ""; +}; +if (customInspectSymbol) { + Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect; +} +Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer.from(target, target.offset, target.byteLength); + } + if (!Buffer.isBuffer(target)) { + throw new TypeError("The \"target\" argument must be one of type Buffer or Uint8Array. " + "Received type " + typeof target); + } + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError("out of range index"); + } + if (thisStart >= thisEnd && start >= end) { + return 0; + } + if (thisStart >= thisEnd) { + return -1; + } + if (start >= end) { + return 1; + } + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + if (this === target) { + return 0; + } + let x = thisEnd - thisStart; + let y = end - start; + const len = Math.min(x, y); + const thisCopy = this.slice(thisStart, thisEnd); + const targetCopy = target.slice(start, end); + for (let i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break; + } + } + if (x < y) { + return -1; + } + if (y < x) { + return 1; + } + return 0; +}; +function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { + if (buffer.length === 0) { + return -1; + } + if (typeof byteOffset === "string") { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 2147483647) { + byteOffset = 2147483647; + } else if (byteOffset < -2147483648) { + byteOffset = -2147483648; + } + byteOffset = +byteOffset; + if (numberIsNaN(byteOffset)) { + byteOffset = dir ? 0 : buffer.length - 1; + } + if (byteOffset < 0) { + byteOffset = buffer.length + byteOffset; + } + if (byteOffset >= buffer.length) { + if (dir) { + return -1; + } else { + byteOffset = buffer.length - 1; + } + } else if (byteOffset < 0) { + if (dir) { + byteOffset = 0; + } else { + return -1; + } + } + if (typeof val === "string") { + val = Buffer.from(val, encoding); + } + if (Buffer.isBuffer(val)) { + if (val.length === 0) { + return -1; + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir); + } else if (typeof val === "number") { + val = val & 255; + if (typeof Uint8Array.prototype.indexOf === "function") { + return dir ? Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) : Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset); + } + return arrayIndexOf(buffer, [val], byteOffset, encoding, dir); + } + throw new TypeError("val must be string, number or Buffer"); +} +function arrayIndexOf(arr, val, byteOffset, encoding, dir) { + let indexSize = 1; + let arrLength = arr.length; + let valLength = val.length; + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") { + if (arr.length < 2 || val.length < 2) { + return -1; + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + function read(buf, i) { + return indexSize === 1 ? buf[i] : buf.readUInt16BE(i * indexSize); + } + let i; + if (dir) { + let foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) { + foundIndex = i; + } + if (i - foundIndex + 1 === valLength) { + return foundIndex * indexSize; + } + } else { + if (foundIndex !== -1) { + i -= i - foundIndex; + } + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) { + byteOffset = arrLength - valLength; + } + for (i = byteOffset; i >= 0; i--) { + let found = true; + for (let j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break; + } + } + if (found) { + return i; + } + } + } + return -1; +} +Buffer.prototype.includes = function includes(val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1; +}; +Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true); +}; +Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false); +}; +function hexWrite(buf, string, offset, length) { + offset = Number(offset) || 0; + const remaining = buf.length - offset; + if (length) { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } else { + length = remaining; + } + const strLen = string.length; + if (length > strLen / 2) { + length = strLen / 2; + } + let i; + for (i = 0; i < length; ++i) { + const parsed = Number.parseInt(string.slice(i * 2, i * 2 + 2), 16); + if (numberIsNaN(parsed)) { + return i; + } + buf[offset + i] = parsed; + } + return i; +} +function utf8Write(buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length); +} +function asciiWrite(buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length); +} +function base64Write(buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length); +} +function ucs2Write(buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length); +} +Buffer.prototype.write = function write(string, offset, length, encoding) { + if (offset === undefined) { + encoding = "utf8"; + length = this.length; + offset = 0; + } else if (length === undefined && typeof offset === "string") { + encoding = offset; + length = this.length; + offset = 0; + } else if (Number.isFinite(offset)) { + offset = offset >>> 0; + if (Number.isFinite(length)) { + length = length >>> 0; + if (encoding === undefined) { + encoding = "utf8"; + } + } else { + encoding = length; + length = undefined; + } + } else { + throw new TypeError("Buffer.write(string, encoding, offset[, length]) is no longer supported"); + } + const remaining = this.length - offset; + if (length === undefined || length > remaining) { + length = remaining; + } + if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) { + throw new RangeError("Attempt to write outside buffer bounds"); + } + if (!encoding) { + encoding = "utf8"; + } + let loweredCase = false; + for (;;) { + switch (encoding) { + case "hex": return hexWrite(this, string, offset, length); + case "utf8": + case "utf-8": return utf8Write(this, string, offset, length); + case "ascii": + case "latin1": + case "binary": return asciiWrite(this, string, offset, length); + case "base64": return base64Write(this, string, offset, length); + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": return ucs2Write(this, string, offset, length); + default: + if (loweredCase) { + throw new TypeError("Unknown encoding: " + encoding); + } + encoding = ("" + encoding).toLowerCase(); + loweredCase = true; + } + } +}; +Buffer.prototype.toJSON = function toJSON() { + return { + type: "Buffer", + data: Array.prototype.slice.call(this._arr || this, 0) + }; +}; +function base64Slice(buf, start, end) { + return start === 0 && end === buf.length ? base64.fromByteArray(buf) : base64.fromByteArray(buf.slice(start, end)); +} +function utf8Slice(buf, start, end) { + end = Math.min(buf.length, end); + const res = []; + let i = start; + while (i < end) { + const firstByte = buf[i]; + let codePoint = null; + let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1; + if (i + bytesPerSequence <= end) { + let secondByte, thirdByte, fourthByte, tempCodePoint; + switch (bytesPerSequence) { + case 1: + if (firstByte < 128) { + codePoint = firstByte; + } + break; + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 192) === 128) { + tempCodePoint = (firstByte & 31) << 6 | secondByte & 63; + if (tempCodePoint > 127) { + codePoint = tempCodePoint; + } + } + break; + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) { + tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63; + if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) { + codePoint = tempCodePoint; + } + } + break; + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) { + tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63; + if (tempCodePoint > 65535 && tempCodePoint < 1114112) { + codePoint = tempCodePoint; + } + } + } + } + if (codePoint === null) { + codePoint = 65533; + bytesPerSequence = 1; + } else if (codePoint > 65535) { + codePoint -= 65536; + res.push(codePoint >>> 10 & 1023 | 55296); + codePoint = 56320 | codePoint & 1023; + } + res.push(codePoint); + i += bytesPerSequence; + } + return decodeCodePointsArray(res); +} +const MAX_ARGUMENTS_LENGTH = 4096; +function decodeCodePointsArray(codePoints) { + const len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints); + } + let res = ""; + let i = 0; + while (i < len) { + res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)); + } + return res; +} +function asciiSlice(buf, start, end) { + let ret = ""; + end = Math.min(buf.length, end); + for (let i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 127); + } + return ret; +} +function latin1Slice(buf, start, end) { + let ret = ""; + end = Math.min(buf.length, end); + for (let i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret; +} +function hexSlice(buf, start, end) { + const len = buf.length; + if (!start || start < 0) { + start = 0; + } + if (!end || end < 0 || end > len) { + end = len; + } + let out = ""; + for (let i = start; i < end; ++i) { + out += hexSliceLookupTable[buf[i]]; + } + return out; +} +function utf16leSlice(buf, start, end) { + const bytes = buf.slice(start, end); + let res = ""; + for (let i = 0; i < bytes.length - 1; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res; +} +Buffer.prototype.slice = function slice(start, end) { + const len = this.length; + start = Math.trunc(start); + end = end === undefined ? len : Math.trunc(end); + if (start < 0) { + start += len; + if (start < 0) { + start = 0; + } + } else if (start > len) { + start = len; + } + if (end < 0) { + end += len; + if (end < 0) { + end = 0; + } + } else if (end > len) { + end = len; + } + if (end < start) { + end = start; + } + const newBuf = this.subarray(start, end); + Object.setPrototypeOf(newBuf, Buffer.prototype); + return newBuf; +}; +function checkOffset(offset, ext, length) { + if (offset % 1 !== 0 || offset < 0) { + throw new RangeError("offset is not uint"); + } + if (offset + ext > length) { + throw new RangeError("Trying to access beyond buffer length"); + } +} +Buffer.prototype.readUintLE = Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + let val = this[offset]; + let mul = 1; + let i = 0; + while (++i < byteLength && (mul *= 256)) { + val += this[offset + i] * mul; + } + return val; +}; +Buffer.prototype.readUintBE = Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + let val = this[offset + --byteLength]; + let mul = 1; + while (byteLength > 0 && (mul *= 256)) { + val += this[offset + --byteLength] * mul; + } + return val; +}; +Buffer.prototype.readUint8 = Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) { + checkOffset(offset, 1, this.length); + } + return this[offset]; +}; +Buffer.prototype.readUint16LE = Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) { + checkOffset(offset, 2, this.length); + } + return this[offset] | this[offset + 1] << 8; +}; +Buffer.prototype.readUint16BE = Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) { + checkOffset(offset, 2, this.length); + } + return this[offset] << 8 | this[offset + 1]; +}; +Buffer.prototype.readUint32LE = Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) { + checkOffset(offset, 4, this.length); + } + return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216; +}; +Buffer.prototype.readUint32BE = Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) { + checkOffset(offset, 4, this.length); + } + return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]); +}; +Buffer.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE(offset) { + offset = offset >>> 0; + validateNumber(offset, "offset"); + const first = this[offset]; + const last = this[offset + 7]; + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8); + } + const lo = first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24; + const hi = this[++offset] + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + last * 2 ** 24; + return BigInt(lo) + (BigInt(hi) << BigInt(32)); +}); +Buffer.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE(offset) { + offset = offset >>> 0; + validateNumber(offset, "offset"); + const first = this[offset]; + const last = this[offset + 7]; + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8); + } + const hi = first * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset]; + const lo = this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last; + return (BigInt(hi) << BigInt(32)) + BigInt(lo); +}); +Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + let val = this[offset]; + let mul = 1; + let i = 0; + while (++i < byteLength && (mul *= 256)) { + val += this[offset + i] * mul; + } + mul *= 128; + if (val >= mul) { + val -= Math.pow(2, 8 * byteLength); + } + return val; +}; +Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + let i = byteLength; + let mul = 1; + let val = this[offset + --i]; + while (i > 0 && (mul *= 256)) { + val += this[offset + --i] * mul; + } + mul *= 128; + if (val >= mul) { + val -= Math.pow(2, 8 * byteLength); + } + return val; +}; +Buffer.prototype.readInt8 = function readInt8(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) { + checkOffset(offset, 1, this.length); + } + if (!(this[offset] & 128)) { + return this[offset]; + } + return (255 - this[offset] + 1) * -1; +}; +Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) { + checkOffset(offset, 2, this.length); + } + const val = this[offset] | this[offset + 1] << 8; + return val & 32768 ? val | 4294901760 : val; +}; +Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) { + checkOffset(offset, 2, this.length); + } + const val = this[offset + 1] | this[offset] << 8; + return val & 32768 ? val | 4294901760 : val; +}; +Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) { + checkOffset(offset, 4, this.length); + } + return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24; +}; +Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) { + checkOffset(offset, 4, this.length); + } + return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]; +}; +Buffer.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE(offset) { + offset = offset >>> 0; + validateNumber(offset, "offset"); + const first = this[offset]; + const last = this[offset + 7]; + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8); + } + const val = this[offset + 4] + this[offset + 5] * 2 ** 8 + this[offset + 6] * 2 ** 16 + (last << 24); + return (BigInt(val) << BigInt(32)) + BigInt(first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24); +}); +Buffer.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE(offset) { + offset = offset >>> 0; + validateNumber(offset, "offset"); + const first = this[offset]; + const last = this[offset + 7]; + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8); + } + const val = (first << 24) + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset]; + return (BigInt(val) << BigInt(32)) + BigInt(this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last); +}); +Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) { + checkOffset(offset, 4, this.length); + } + return ieee754.read(this, offset, true, 23, 4); +}; +Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) { + checkOffset(offset, 4, this.length); + } + return ieee754.read(this, offset, false, 23, 4); +}; +Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) { + checkOffset(offset, 8, this.length); + } + return ieee754.read(this, offset, true, 52, 8); +}; +Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) { + checkOffset(offset, 8, this.length); + } + return ieee754.read(this, offset, false, 52, 8); +}; +function checkInt(buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) { + throw new TypeError("\"buffer\" argument must be a Buffer instance"); + } + if (value > max || value < min) { + throw new RangeError("\"value\" argument is out of bounds"); + } + if (offset + ext > buf.length) { + throw new RangeError("Index out of range"); + } +} +Buffer.prototype.writeUintLE = Buffer.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + let mul = 1; + let i = 0; + this[offset] = value & 255; + while (++i < byteLength && (mul *= 256)) { + this[offset + i] = value / mul & 255; + } + return offset + byteLength; +}; +Buffer.prototype.writeUintBE = Buffer.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + let i = byteLength - 1; + let mul = 1; + this[offset + i] = value & 255; + while (--i >= 0 && (mul *= 256)) { + this[offset + i] = value / mul & 255; + } + return offset + byteLength; +}; +Buffer.prototype.writeUint8 = Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + checkInt(this, value, offset, 1, 255, 0); + } + this[offset] = value & 255; + return offset + 1; +}; +Buffer.prototype.writeUint16LE = Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + checkInt(this, value, offset, 2, 65535, 0); + } + this[offset] = value & 255; + this[offset + 1] = value >>> 8; + return offset + 2; +}; +Buffer.prototype.writeUint16BE = Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + checkInt(this, value, offset, 2, 65535, 0); + } + this[offset] = value >>> 8; + this[offset + 1] = value & 255; + return offset + 2; +}; +Buffer.prototype.writeUint32LE = Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + checkInt(this, value, offset, 4, 4294967295, 0); + } + this[offset + 3] = value >>> 24; + this[offset + 2] = value >>> 16; + this[offset + 1] = value >>> 8; + this[offset] = value & 255; + return offset + 4; +}; +Buffer.prototype.writeUint32BE = Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + checkInt(this, value, offset, 4, 4294967295, 0); + } + this[offset] = value >>> 24; + this[offset + 1] = value >>> 16; + this[offset + 2] = value >>> 8; + this[offset + 3] = value & 255; + return offset + 4; +}; +function wrtBigUInt64LE(buf, value, offset, min, max) { + checkIntBI(value, min, max, buf, offset, 7); + let lo = Number(value & BigInt(4294967295)); + buf[offset++] = lo; + lo = lo >> 8; + buf[offset++] = lo; + lo = lo >> 8; + buf[offset++] = lo; + lo = lo >> 8; + buf[offset++] = lo; + let hi = Number(value >> BigInt(32) & BigInt(4294967295)); + buf[offset++] = hi; + hi = hi >> 8; + buf[offset++] = hi; + hi = hi >> 8; + buf[offset++] = hi; + hi = hi >> 8; + buf[offset++] = hi; + return offset; +} +function wrtBigUInt64BE(buf, value, offset, min, max) { + checkIntBI(value, min, max, buf, offset, 7); + let lo = Number(value & BigInt(4294967295)); + buf[offset + 7] = lo; + lo = lo >> 8; + buf[offset + 6] = lo; + lo = lo >> 8; + buf[offset + 5] = lo; + lo = lo >> 8; + buf[offset + 4] = lo; + let hi = Number(value >> BigInt(32) & BigInt(4294967295)); + buf[offset + 3] = hi; + hi = hi >> 8; + buf[offset + 2] = hi; + hi = hi >> 8; + buf[offset + 1] = hi; + hi = hi >> 8; + buf[offset] = hi; + return offset + 8; +} +Buffer.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE(value, offset = 0) { + return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff")); +}); +Buffer.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE(value, offset = 0) { + return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff")); +}); +Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + const limit = Math.pow(2, 8 * byteLength - 1); + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + let i = 0; + let mul = 1; + let sub = 0; + this[offset] = value & 255; + while (++i < byteLength && (mul *= 256)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = Math.trunc(value / mul) - sub & 255; + } + return offset + byteLength; +}; +Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + const limit = Math.pow(2, 8 * byteLength - 1); + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + let i = byteLength - 1; + let mul = 1; + let sub = 0; + this[offset + i] = value & 255; + while (--i >= 0 && (mul *= 256)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = Math.trunc(value / mul) - sub & 255; + } + return offset + byteLength; +}; +Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + checkInt(this, value, offset, 1, 127, -128); + } + if (value < 0) { + value = 255 + value + 1; + } + this[offset] = value & 255; + return offset + 1; +}; +Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + checkInt(this, value, offset, 2, 32767, -32768); + } + this[offset] = value & 255; + this[offset + 1] = value >>> 8; + return offset + 2; +}; +Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + checkInt(this, value, offset, 2, 32767, -32768); + } + this[offset] = value >>> 8; + this[offset + 1] = value & 255; + return offset + 2; +}; +Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + checkInt(this, value, offset, 4, 2147483647, -2147483648); + } + this[offset] = value & 255; + this[offset + 1] = value >>> 8; + this[offset + 2] = value >>> 16; + this[offset + 3] = value >>> 24; + return offset + 4; +}; +Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + checkInt(this, value, offset, 4, 2147483647, -2147483648); + } + if (value < 0) { + value = 4294967295 + value + 1; + } + this[offset] = value >>> 24; + this[offset + 1] = value >>> 16; + this[offset + 2] = value >>> 8; + this[offset + 3] = value & 255; + return offset + 4; +}; +Buffer.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE(value, offset = 0) { + return wrtBigUInt64LE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); +}); +Buffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE(value, offset = 0) { + return wrtBigUInt64BE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); +}); +function checkIEEE754(buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) { + throw new RangeError("Index out of range"); + } + if (offset < 0) { + throw new RangeError("Index out of range"); + } +} +function writeFloat(buf, value, offset, littleEndian, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 34028234663852886e22, -34028234663852886e22); + } + ieee754.write(buf, value, offset, littleEndian, 23, 4); + return offset + 4; +} +Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert); +}; +Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert); +}; +function writeDouble(buf, value, offset, littleEndian, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 17976931348623157e292, -17976931348623157e292); + } + ieee754.write(buf, value, offset, littleEndian, 52, 8); + return offset + 8; +} +Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert); +}; +Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert); +}; +Buffer.prototype.copy = function copy(target, targetStart, start, end) { + if (!Buffer.isBuffer(target)) { + throw new TypeError("argument should be a Buffer"); + } + if (!start) { + start = 0; + } + if (!end && end !== 0) { + end = this.length; + } + if (targetStart >= target.length) { + targetStart = target.length; + } + if (!targetStart) { + targetStart = 0; + } + if (end > 0 && end < start) { + end = start; + } + if (end === start) { + return 0; + } + if (target.length === 0 || this.length === 0) { + return 0; + } + if (targetStart < 0) { + throw new RangeError("targetStart out of bounds"); + } + if (start < 0 || start >= this.length) { + throw new RangeError("Index out of range"); + } + if (end < 0) { + throw new RangeError("sourceEnd out of bounds"); + } + if (end > this.length) { + end = this.length; + } + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + const len = end - start; + if (this === target && typeof Uint8Array.prototype.copyWithin === "function") { + this.copyWithin(targetStart, start, end); + } else { + Uint8Array.prototype.set.call(target, this.subarray(start, end), targetStart); + } + return len; +}; +Buffer.prototype.fill = function fill(val, start, end, encoding) { + if (typeof val === "string") { + if (typeof start === "string") { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === "string") { + encoding = end; + end = this.length; + } + if (encoding !== undefined && typeof encoding !== "string") { + throw new TypeError("encoding must be a string"); + } + if (typeof encoding === "string" && !Buffer.isEncoding(encoding)) { + throw new TypeError("Unknown encoding: " + encoding); + } + if (val.length === 1) { + const code = val.charCodeAt(0); + if (encoding === "utf8" && code < 128 || encoding === "latin1") { + val = code; + } + } + } else if (typeof val === "number") { + val = val & 255; + } else if (typeof val === "boolean") { + val = Number(val); + } + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError("Out of range index"); + } + if (end <= start) { + return this; + } + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + if (!val) { + val = 0; + } + let i; + if (typeof val === "number") { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + const bytes = Buffer.isBuffer(val) ? val : Buffer.from(val, encoding); + const len = bytes.length; + if (len === 0) { + throw new TypeError("The value \"" + val + "\" is invalid for argument \"value\""); + } + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + return this; +}; +const errors = {}; +function E(sym, getMessage, Base) { + errors[sym] = class NodeError extends Base { + constructor() { + super(); + Object.defineProperty(this, "message", { + value: Reflect.apply(getMessage, this, arguments), + writable: true, + configurable: true + }); + this.name = `${this.name} [${sym}]`; + this.stack; + delete this.name; + } + get code() { + return sym; + } + set code(value) { + Object.defineProperty(this, "code", { + configurable: true, + enumerable: true, + value, + writable: true + }); + } + toString() { + return `${this.name} [${sym}]: ${this.message}`; + } + }; +} +E("ERR_BUFFER_OUT_OF_BOUNDS", function(name) { + if (name) { + return `${name} is outside of buffer bounds`; + } + return "Attempt to access memory outside buffer bounds"; +}, RangeError); +E("ERR_INVALID_ARG_TYPE", function(name, actual) { + return `The "${name}" argument must be of type number. Received type ${typeof actual}`; +}, TypeError); +E("ERR_OUT_OF_RANGE", function(str, range, input) { + let msg = `The value of "${str}" is out of range.`; + let received = input; + if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) { + received = addNumericalSeparator(String(input)); + } else if (typeof input === "bigint") { + received = String(input); + if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) { + received = addNumericalSeparator(received); + } + received += "n"; + } + msg += ` It must be ${range}. Received ${received}`; + return msg; +}, RangeError); +function addNumericalSeparator(val) { + let res = ""; + let i = val.length; + const start = val[0] === "-" ? 1 : 0; + for (; i >= start + 4; i -= 3) { + res = `_${val.slice(i - 3, i)}${res}`; + } + return `${val.slice(0, i)}${res}`; +} +function checkBounds(buf, offset, byteLength) { + validateNumber(offset, "offset"); + if (buf[offset] === undefined || buf[offset + byteLength] === undefined) { + boundsError(offset, buf.length - (byteLength + 1)); + } +} +function checkIntBI(value, min, max, buf, offset, byteLength) { + if (value > max || value < min) { + const n = typeof min === "bigint" ? "n" : ""; + let range; + if (byteLength > 3) { + range = min === 0 || min === BigInt(0) ? `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}` : `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` + `${(byteLength + 1) * 8 - 1}${n}`; + } else { + range = `>= ${min}${n} and <= ${max}${n}`; + } + throw new errors.ERR_OUT_OF_RANGE("value", range, value); + } + checkBounds(buf, offset, byteLength); +} +function validateNumber(value, name) { + if (typeof value !== "number") { + throw new errors.ERR_INVALID_ARG_TYPE(name, "number", value); + } +} +function boundsError(value, length, type) { + if (Math.floor(value) !== value) { + validateNumber(value, type); + throw new errors.ERR_OUT_OF_RANGE(type || "offset", "an integer", value); + } + if (length < 0) { + throw new errors.ERR_BUFFER_OUT_OF_BOUNDS(); + } + throw new errors.ERR_OUT_OF_RANGE(type || "offset", `>= ${type ? 1 : 0} and <= ${length}`, value); +} +const INVALID_BASE64_RE = /[^\w+/-]/g; +function base64clean(str) { + str = str.split("=")[0]; + str = str.trim().replace(INVALID_BASE64_RE, ""); + if (str.length < 2) { + return ""; + } + while (str.length % 4 !== 0) { + str = str + "="; + } + return str; +} +function utf8ToBytes(string, units) { + units = units || Number.POSITIVE_INFINITY; + let codePoint; + const length = string.length; + let leadSurrogate = null; + const bytes = []; + for (let i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + if (codePoint > 55295 && codePoint < 57344) { + if (!leadSurrogate) { + if (codePoint > 56319) { + if ((units -= 3) > -1) { + bytes.push(239, 191, 189); + } + continue; + } else if (i + 1 === length) { + if ((units -= 3) > -1) { + bytes.push(239, 191, 189); + } + continue; + } + leadSurrogate = codePoint; + continue; + } + if (codePoint < 56320) { + if ((units -= 3) > -1) { + bytes.push(239, 191, 189); + } + leadSurrogate = codePoint; + continue; + } + codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536; + } else if (leadSurrogate && (units -= 3) > -1) { + bytes.push(239, 191, 189); + } + leadSurrogate = null; + if (codePoint < 128) { + if ((units -= 1) < 0) { + break; + } + bytes.push(codePoint); + } else if (codePoint < 2048) { + if ((units -= 2) < 0) { + break; + } + bytes.push(codePoint >> 6 | 192, codePoint & 63 | 128); + } else if (codePoint < 65536) { + if ((units -= 3) < 0) { + break; + } + bytes.push(codePoint >> 12 | 224, codePoint >> 6 & 63 | 128, codePoint & 63 | 128); + } else if (codePoint < 1114112) { + if ((units -= 4) < 0) { + break; + } + bytes.push(codePoint >> 18 | 240, codePoint >> 12 & 63 | 128, codePoint >> 6 & 63 | 128, codePoint & 63 | 128); + } else { + throw new Error("Invalid code point"); + } + } + return bytes; +} +function asciiToBytes(str) { + const byteArray = []; + for (let i = 0; i < str.length; ++i) { + byteArray.push(str.charCodeAt(i) & 255); + } + return byteArray; +} +function utf16leToBytes(str, units) { + let c, hi, lo; + const byteArray = []; + for (let i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) { + break; + } + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo, hi); + } + return byteArray; +} +function base64ToBytes(str) { + return base64.toByteArray(base64clean(str)); +} +function blitBuffer(src, dst, offset, length) { + let i; + for (i = 0; i < length; ++i) { + if (i + offset >= dst.length || i >= src.length) { + break; + } + dst[i + offset] = src[i]; + } + return i; +} +function isInstance(obj, type) { + return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name; +} +function numberIsNaN(obj) { + return obj !== obj; +} +const hexSliceLookupTable = function() { + const alphabet = "0123456789abcdef"; + const table = Array.from({ length: 256 }); + for (let i = 0; i < 16; ++i) { + const i16 = i * 16; + for (let j = 0; j < 16; ++j) { + table[i16 + j] = alphabet[i] + alphabet[j]; + } + } + return table; +}(); +function defineBigIntMethod(fn) { + return typeof BigInt === "undefined" ? BufferBigIntNotDefined : fn; +} +function BufferBigIntNotDefined() { + throw new Error("BigInt not supported"); +} diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/buffer/file.d.mts b/worker/node_modules/unenv/dist/runtime/node/internal/buffer/file.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..f62b3f5a1debbedca31e052295adb70b7d62e095 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/buffer/file.d.mts @@ -0,0 +1,14 @@ +import type nodeBuffer from "node:buffer"; +export declare class File extends Blob implements nodeBuffer.File { + readonly __unenv__: true; + size: number; + type: any; + name: string; + lastModified: number; + constructor(...args: any[]); + arrayBuffer(): Promise; + slice(): any; + text(): any; + stream(): any; + bytes(): Promise; +} diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/buffer/file.mjs b/worker/node_modules/unenv/dist/runtime/node/internal/buffer/file.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c187f96edbb642ff29abdcb02adc9f9b817cb80f --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/buffer/file.mjs @@ -0,0 +1,26 @@ +export class File extends Blob { + __unenv__ = true; + size = 0; + type = ""; + name = ""; + lastModified = 0; + constructor(...args) { + super(...args); + throw new Error("[unenv] buffer.File is not implemented"); + } + arrayBuffer() { + throw new Error("Not implemented"); + } + slice() { + throw new Error("Not implemented"); + } + text() { + throw new Error("Not implemented"); + } + stream() { + throw new Error("Not implemented"); + } + bytes() { + throw new Error("Not implemented"); + } +} diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/buffer/ieee754.d.mts b/worker/node_modules/unenv/dist/runtime/node/internal/buffer/ieee754.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..c789d36dba4efe4b7e21ea55c608a7ac8941ed7a --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/buffer/ieee754.d.mts @@ -0,0 +1,3 @@ +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ +export declare function read(buffer: Uint8Array, offset: number, isLE: boolean, mLen: number, nBytes: number); +export declare function write(buffer: Uint8Array, value: number, offset: number, isLE: boolean, mLen: number, nBytes: number); diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/buffer/ieee754.mjs b/worker/node_modules/unenv/dist/runtime/node/internal/buffer/ieee754.mjs new file mode 100644 index 0000000000000000000000000000000000000000..072f7e372034ff7a0838e2ee79daaa0cb32780a6 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/buffer/ieee754.mjs @@ -0,0 +1,88 @@ +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ +export function read(buffer, offset, isLE, mLen, nBytes) { + let e, m; + const eLen = nBytes * 8 - mLen - 1; + const eMax = (1 << eLen) - 1; + const eBias = eMax >> 1; + let nBits = -7; + let i = isLE ? nBytes - 1 : 0; + const d = isLE ? -1 : 1; + let s = buffer[offset + i]; + i += d; + e = s & (1 << -nBits) - 1; + s >>= -nBits; + nBits += eLen; + while (nBits > 0) { + e = e * 256 + buffer[offset + i]; + i += d; + nBits -= 8; + } + m = e & (1 << -nBits) - 1; + e >>= -nBits; + nBits += mLen; + while (nBits > 0) { + m = m * 256 + buffer[offset + i]; + i += d; + nBits -= 8; + } + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? Number.NaN : (s ? -1 : 1) * Number.POSITIVE_INFINITY; + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); +} +export function write(buffer, value, offset, isLE, mLen, nBytes) { + let e, m, c; + let eLen = nBytes * 8 - mLen - 1; + const eMax = (1 << eLen) - 1; + const eBias = eMax >> 1; + const rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; + let i = isLE ? 0 : nBytes - 1; + const d = isLE ? 1 : -1; + const s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; + value = Math.abs(value); + if (Number.isNaN(value) || value === Number.POSITIVE_INFINITY) { + m = Number.isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log2(value)); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + value += e + eBias >= 1 ? rt / c : rt * Math.pow(2, 1 - eBias); + if (value * c >= 2) { + e++; + c /= 2; + } + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + while (mLen >= 8) { + buffer[offset + i] = m & 255; + i += d; + m /= 256; + mLen -= 8; + } + e = e << mLen | m; + eLen += mLen; + while (eLen > 0) { + buffer[offset + i] = e & 255; + i += d; + e /= 256; + eLen -= 8; + } + buffer[offset + i - d] |= s * 128; +} diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/crypto/constants.d.mts b/worker/node_modules/unenv/dist/runtime/node/internal/crypto/constants.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..46fd8ae4d7f400bc3e0d4df0405be0e8de1cb23e --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/crypto/constants.d.mts @@ -0,0 +1,56 @@ +export declare const SSL_OP_ALL = 2147485776; +export declare const SSL_OP_ALLOW_NO_DHE_KEX = 1024; +export declare const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION = 262144; +export declare const SSL_OP_CIPHER_SERVER_PREFERENCE = 4194304; +export declare const SSL_OP_CISCO_ANYCONNECT = 32768; +export declare const SSL_OP_COOKIE_EXCHANGE = 8192; +export declare const SSL_OP_CRYPTOPRO_TLSEXT_BUG = 2147483648; +export declare const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS = 2048; +export declare const SSL_OP_LEGACY_SERVER_CONNECT = 4; +export declare const SSL_OP_NO_COMPRESSION = 131072; +export declare const SSL_OP_NO_ENCRYPT_THEN_MAC = 524288; +export declare const SSL_OP_NO_QUERY_MTU = 4096; +export declare const SSL_OP_NO_RENEGOTIATION = 1073741824; +export declare const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION = 65536; +export declare const SSL_OP_NO_SSLv2 = 0; +export declare const SSL_OP_NO_SSLv3 = 33554432; +export declare const SSL_OP_NO_TICKET = 16384; +export declare const SSL_OP_NO_TLSv1 = 67108864; +export declare const SSL_OP_NO_TLSv1_1 = 268435456; +export declare const SSL_OP_NO_TLSv1_2 = 134217728; +export declare const SSL_OP_NO_TLSv1_3 = 536870912; +export declare const SSL_OP_PRIORITIZE_CHACHA = 2097152; +export declare const SSL_OP_TLS_ROLLBACK_BUG = 8388608; +export declare const ENGINE_METHOD_RSA = 1; +export declare const ENGINE_METHOD_DSA = 2; +export declare const ENGINE_METHOD_DH = 4; +export declare const ENGINE_METHOD_RAND = 8; +export declare const ENGINE_METHOD_EC = 2048; +export declare const ENGINE_METHOD_CIPHERS = 64; +export declare const ENGINE_METHOD_DIGESTS = 128; +export declare const ENGINE_METHOD_PKEY_METHS = 512; +export declare const ENGINE_METHOD_PKEY_ASN1_METHS = 1024; +export declare const ENGINE_METHOD_ALL = 65535; +export declare const ENGINE_METHOD_NONE = 0; +export declare const DH_CHECK_P_NOT_SAFE_PRIME = 2; +export declare const DH_CHECK_P_NOT_PRIME = 1; +export declare const DH_UNABLE_TO_CHECK_GENERATOR = 4; +export declare const DH_NOT_SUITABLE_GENERATOR = 8; +export declare const RSA_PKCS1_PADDING = 1; +export declare const RSA_NO_PADDING = 3; +export declare const RSA_PKCS1_OAEP_PADDING = 4; +export declare const RSA_X931_PADDING = 5; +export declare const RSA_PKCS1_PSS_PADDING = 6; +export declare const RSA_PSS_SALTLEN_DIGEST = -1; +export declare const RSA_PSS_SALTLEN_MAX_SIGN = -2; +export declare const RSA_PSS_SALTLEN_AUTO = -2; +export declare const POINT_CONVERSION_COMPRESSED = 2; +export declare const POINT_CONVERSION_UNCOMPRESSED = 4; +export declare const POINT_CONVERSION_HYBRID = 6; +export declare const defaultCoreCipherList = ""; +export declare const defaultCipherList = ""; +export declare const OPENSSL_VERSION_NUMBER = 0; +export declare const TLS1_VERSION = 0; +export declare const TLS1_1_VERSION = 0; +export declare const TLS1_2_VERSION = 0; +export declare const TLS1_3_VERSION = 0; diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/crypto/constants.mjs b/worker/node_modules/unenv/dist/runtime/node/internal/crypto/constants.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8977522e693a248fe3133f69f36ffd81542b0766 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/crypto/constants.mjs @@ -0,0 +1,56 @@ +export const SSL_OP_ALL = 2147485776; +export const SSL_OP_ALLOW_NO_DHE_KEX = 1024; +export const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION = 262144; +export const SSL_OP_CIPHER_SERVER_PREFERENCE = 4194304; +export const SSL_OP_CISCO_ANYCONNECT = 32768; +export const SSL_OP_COOKIE_EXCHANGE = 8192; +export const SSL_OP_CRYPTOPRO_TLSEXT_BUG = 2147483648; +export const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS = 2048; +export const SSL_OP_LEGACY_SERVER_CONNECT = 4; +export const SSL_OP_NO_COMPRESSION = 131072; +export const SSL_OP_NO_ENCRYPT_THEN_MAC = 524288; +export const SSL_OP_NO_QUERY_MTU = 4096; +export const SSL_OP_NO_RENEGOTIATION = 1073741824; +export const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION = 65536; +export const SSL_OP_NO_SSLv2 = 0; +export const SSL_OP_NO_SSLv3 = 33554432; +export const SSL_OP_NO_TICKET = 16384; +export const SSL_OP_NO_TLSv1 = 67108864; +export const SSL_OP_NO_TLSv1_1 = 268435456; +export const SSL_OP_NO_TLSv1_2 = 134217728; +export const SSL_OP_NO_TLSv1_3 = 536870912; +export const SSL_OP_PRIORITIZE_CHACHA = 2097152; +export const SSL_OP_TLS_ROLLBACK_BUG = 8388608; +export const ENGINE_METHOD_RSA = 1; +export const ENGINE_METHOD_DSA = 2; +export const ENGINE_METHOD_DH = 4; +export const ENGINE_METHOD_RAND = 8; +export const ENGINE_METHOD_EC = 2048; +export const ENGINE_METHOD_CIPHERS = 64; +export const ENGINE_METHOD_DIGESTS = 128; +export const ENGINE_METHOD_PKEY_METHS = 512; +export const ENGINE_METHOD_PKEY_ASN1_METHS = 1024; +export const ENGINE_METHOD_ALL = 65535; +export const ENGINE_METHOD_NONE = 0; +export const DH_CHECK_P_NOT_SAFE_PRIME = 2; +export const DH_CHECK_P_NOT_PRIME = 1; +export const DH_UNABLE_TO_CHECK_GENERATOR = 4; +export const DH_NOT_SUITABLE_GENERATOR = 8; +export const RSA_PKCS1_PADDING = 1; +export const RSA_NO_PADDING = 3; +export const RSA_PKCS1_OAEP_PADDING = 4; +export const RSA_X931_PADDING = 5; +export const RSA_PKCS1_PSS_PADDING = 6; +export const RSA_PSS_SALTLEN_DIGEST = -1; +export const RSA_PSS_SALTLEN_MAX_SIGN = -2; +export const RSA_PSS_SALTLEN_AUTO = -2; +export const POINT_CONVERSION_COMPRESSED = 2; +export const POINT_CONVERSION_UNCOMPRESSED = 4; +export const POINT_CONVERSION_HYBRID = 6; +export const defaultCoreCipherList = ""; +export const defaultCipherList = ""; +export const OPENSSL_VERSION_NUMBER = 0; +export const TLS1_VERSION = 0; +export const TLS1_1_VERSION = 0; +export const TLS1_2_VERSION = 0; +export const TLS1_3_VERSION = 0; diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/crypto/node.d.mts b/worker/node_modules/unenv/dist/runtime/node/internal/crypto/node.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..ceaca95ff413dd6400cc283e5ef6052f0d91ecf9 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/crypto/node.d.mts @@ -0,0 +1,72 @@ +import type nodeCrypto from "node:crypto"; +export declare const webcrypto: unknown; +export declare const randomBytes: typeof nodeCrypto.randomBytes; +export declare const rng: unknown; +export declare const prng: unknown; +export declare const fips: typeof nodeCrypto.fips; +export declare const checkPrime: unknown; +export declare const checkPrimeSync: unknown; +/** @deprecated */ +export declare const createCipher: unknown; +/** @deprecated */ +export declare const createDecipher: unknown; +export declare const pseudoRandomBytes: unknown; +export declare const createCipheriv: unknown; +export declare const createDecipheriv: unknown; +export declare const createDiffieHellman: unknown; +export declare const createDiffieHellmanGroup: unknown; +export declare const createECDH: unknown; +export declare const createHash: unknown; +export declare const createHmac: unknown; +export declare const createPrivateKey: unknown; +export declare const createPublicKey: unknown; +export declare const createSecretKey: unknown; +export declare const createSign: unknown; +export declare const createVerify: unknown; +export declare const diffieHellman: unknown; +export declare const generatePrime: unknown; +export declare const generatePrimeSync: unknown; +export declare const getCiphers: unknown; +export declare const getCipherInfo: unknown; +export declare const getCurves: unknown; +export declare const getDiffieHellman: unknown; +export declare const getHashes: unknown; +export declare const hkdf: unknown; +export declare const hkdfSync: unknown; +export declare const pbkdf2: unknown; +export declare const pbkdf2Sync: unknown; +export declare const generateKeyPair: unknown; +export declare const generateKeyPairSync: unknown; +export declare const generateKey: unknown; +export declare const generateKeySync: unknown; +export declare const privateDecrypt: unknown; +export declare const privateEncrypt: unknown; +export declare const publicDecrypt: unknown; +export declare const publicEncrypt: unknown; +export declare const randomFill: unknown; +export declare const randomFillSync: unknown; +export declare const randomInt: unknown; +export declare const scrypt: unknown; +export declare const scryptSync: unknown; +export declare const sign: unknown; +export declare const setEngine: unknown; +export declare const timingSafeEqual: unknown; +export declare const getFips: unknown; +export declare const setFips: unknown; +export declare const verify: unknown; +export declare const secureHeapUsed: unknown; +export declare const hash: unknown; +export declare const Certificate: typeof nodeCrypto.Certificate; +export declare const Cipher: typeof nodeCrypto.Cipher; +export declare const Cipheriv: typeof nodeCrypto.Cipheriv; +export declare const Decipher: typeof nodeCrypto.Decipher; +export declare const Decipheriv: typeof nodeCrypto.Decipheriv; +export declare const DiffieHellman: typeof nodeCrypto.DiffieHellman; +export declare const DiffieHellmanGroup: typeof nodeCrypto.DiffieHellmanGroup; +export declare const ECDH: typeof nodeCrypto.ECDH; +export declare const Hash: typeof nodeCrypto.Hash; +export declare const Hmac: typeof nodeCrypto.Hmac; +export declare const KeyObject: typeof nodeCrypto.KeyObject; +export declare const Sign: typeof nodeCrypto.Sign; +export declare const Verify: typeof nodeCrypto.Verify; +export declare const X509Certificate: typeof nodeCrypto.X509Certificate; diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/crypto/node.mjs b/worker/node_modules/unenv/dist/runtime/node/internal/crypto/node.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a75892be37482cb2588864ede2547b7008da4b31 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/crypto/node.mjs @@ -0,0 +1,101 @@ +import { notImplemented, notImplementedClass } from "../../../_internal/utils.mjs"; +import { getRandomValues } from "./web.mjs"; +const MAX_RANDOM_VALUE_BYTES = 65536; +export const webcrypto = new Proxy(globalThis.crypto, { get(_, key) { + if (key === "CryptoKey") { + return globalThis.CryptoKey; + } + if (typeof globalThis.crypto[key] === "function") { + return globalThis.crypto[key].bind(globalThis.crypto); + } + return globalThis.crypto[key]; +} }); +export const randomBytes = (size, cb) => { + const bytes = Buffer.alloc(size, 0, undefined); + for (let generated = 0; generated < size; generated += MAX_RANDOM_VALUE_BYTES) { + getRandomValues( + // Use subarray to get a view of the buffer + Uint8Array.prototype.subarray.call(bytes, generated, generated + MAX_RANDOM_VALUE_BYTES) +); + } + if (typeof cb === "function") { + cb(null, bytes); + return undefined; + } + return bytes; +}; +export const rng = randomBytes; +export const prng = randomBytes; +export const fips = false; +export const checkPrime = /*@__PURE__*/ notImplemented("crypto.checkPrime"); +export const checkPrimeSync = /*@__PURE__*/ notImplemented("crypto.checkPrimeSync"); +/** @deprecated */ +export const createCipher = /*@__PURE__*/ notImplemented("crypto.createCipher"); +/** @deprecated */ +export const createDecipher = /*@__PURE__*/ notImplemented("crypto.createDecipher"); +export const pseudoRandomBytes = /*@__PURE__*/ notImplemented("crypto.pseudoRandomBytes"); +export const createCipheriv = /*@__PURE__*/ notImplemented("crypto.createCipheriv"); +export const createDecipheriv = /*@__PURE__*/ notImplemented("crypto.createDecipheriv"); +export const createDiffieHellman = /*@__PURE__*/ notImplemented("crypto.createDiffieHellman"); +export const createDiffieHellmanGroup = /*@__PURE__*/ notImplemented("crypto.createDiffieHellmanGroup"); +export const createECDH = /*@__PURE__*/ notImplemented("crypto.createECDH"); +export const createHash = /*@__PURE__*/ notImplemented("crypto.createHash"); +export const createHmac = /*@__PURE__*/ notImplemented("crypto.createHmac"); +export const createPrivateKey = /*@__PURE__*/ notImplemented("crypto.createPrivateKey"); +export const createPublicKey = /*@__PURE__*/ notImplemented("crypto.createPublicKey"); +export const createSecretKey = /*@__PURE__*/ notImplemented("crypto.createSecretKey"); +export const createSign = /*@__PURE__*/ notImplemented("crypto.createSign"); +export const createVerify = /*@__PURE__*/ notImplemented("crypto.createVerify"); +export const diffieHellman = /*@__PURE__*/ notImplemented("crypto.diffieHellman"); +export const generatePrime = /*@__PURE__*/ notImplemented("crypto.generatePrime"); +export const generatePrimeSync = /*@__PURE__*/ notImplemented("crypto.generatePrimeSync"); +export const getCiphers = /*@__PURE__*/ notImplemented("crypto.getCiphers"); +export const getCipherInfo = /*@__PURE__*/ notImplemented("crypto.getCipherInfo"); +export const getCurves = /*@__PURE__*/ notImplemented("crypto.getCurves"); +export const getDiffieHellman = /*@__PURE__*/ notImplemented("crypto.getDiffieHellman"); +export const getHashes = /*@__PURE__*/ notImplemented("crypto.getHashes"); +export const hkdf = /*@__PURE__*/ notImplemented("crypto.hkdf"); +export const hkdfSync = /*@__PURE__*/ notImplemented("crypto.hkdfSync"); +export const pbkdf2 = /*@__PURE__*/ notImplemented("crypto.pbkdf2"); +export const pbkdf2Sync = /*@__PURE__*/ notImplemented("crypto.pbkdf2Sync"); +export const generateKeyPair = /*@__PURE__*/ notImplemented("crypto.generateKeyPair"); +export const generateKeyPairSync = /*@__PURE__*/ notImplemented("crypto.generateKeyPairSync"); +export const generateKey = /*@__PURE__*/ notImplemented("crypto.generateKey"); +export const generateKeySync = /*@__PURE__*/ notImplemented("crypto.generateKeySync"); +export const privateDecrypt = /*@__PURE__*/ notImplemented("crypto.privateDecrypt"); +export const privateEncrypt = /*@__PURE__*/ notImplemented("crypto.privateEncrypt"); +export const publicDecrypt = /*@__PURE__*/ notImplemented("crypto.publicDecrypt"); +export const publicEncrypt = /*@__PURE__*/ notImplemented("crypto.publicEncrypt"); +export const randomFill = /*@__PURE__*/ notImplemented("crypto.randomFill"); +export const randomFillSync = /*@__PURE__*/ notImplemented("crypto.randomFillSync"); +export const randomInt = /*@__PURE__*/ notImplemented("crypto.randomInt"); +export const scrypt = /*@__PURE__*/ notImplemented("crypto.scrypt"); +export const scryptSync = /*@__PURE__*/ notImplemented("crypto.scryptSync"); +export const sign = /*@__PURE__*/ notImplemented("crypto.sign"); +export const setEngine = /*@__PURE__*/ notImplemented("crypto.setEngine"); +export const timingSafeEqual = /*@__PURE__*/ notImplemented("crypto.timingSafeEqual"); +export const getFips = /*@__PURE__*/ notImplemented("crypto.getFips"); +export const setFips = /*@__PURE__*/ notImplemented("crypto.setFips"); +export const verify = /*@__PURE__*/ notImplemented("crypto.verify"); +export const secureHeapUsed = /*@__PURE__*/ notImplemented("crypto.secureHeapUsed"); +export const hash = /*@__PURE__*/ notImplemented("crypto.hash"); +export const Certificate = /*@__PURE__*/ notImplementedClass("crypto.Certificate"); +export const Cipher = /*@__PURE__*/ notImplementedClass("crypto.Cipher"); +export const Cipheriv = /*@__PURE__*/ notImplementedClass( + "crypto.Cipheriv" + // @ts-expect-error not typed yet +); +export const Decipher = /*@__PURE__*/ notImplementedClass("crypto.Decipher"); +export const Decipheriv = /*@__PURE__*/ notImplementedClass( + "crypto.Decipheriv" + // @ts-expect-error not typed yet +); +export const DiffieHellman = /*@__PURE__*/ notImplementedClass("crypto.DiffieHellman"); +export const DiffieHellmanGroup = /*@__PURE__*/ notImplementedClass("crypto.DiffieHellmanGroup"); +export const ECDH = /*@__PURE__*/ notImplementedClass("crypto.ECDH"); +export const Hash = /*@__PURE__*/ notImplementedClass("crypto.Hash"); +export const Hmac = /*@__PURE__*/ notImplementedClass("crypto.Hmac"); +export const KeyObject = /*@__PURE__*/ notImplementedClass("crypto.KeyObject"); +export const Sign = /*@__PURE__*/ notImplementedClass("crypto.Sign"); +export const Verify = /*@__PURE__*/ notImplementedClass("crypto.Verify"); +export const X509Certificate = /*@__PURE__*/ notImplementedClass("crypto.X509Certificate"); diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/crypto/web.d.mts b/worker/node_modules/unenv/dist/runtime/node/internal/crypto/web.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..682e80061229830cfc84dfc7b5d46acf7e0e1328 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/crypto/web.d.mts @@ -0,0 +1,3 @@ +export declare const subtle: SubtleCrypto; +export declare const randomUUID: Crypto["randomUUID"]; +export declare const getRandomValues: Crypto["getRandomValues"]; diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/crypto/web.mjs b/worker/node_modules/unenv/dist/runtime/node/internal/crypto/web.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7554e1c3cc8d1f6da1b17de469b2dbb886ecd1f9 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/crypto/web.mjs @@ -0,0 +1,7 @@ +export const subtle = globalThis.crypto?.subtle; +export const randomUUID = () => { + return globalThis.crypto?.randomUUID(); +}; +export const getRandomValues = (array) => { + return globalThis.crypto?.getRandomValues(array); +}; diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/dgram/socket.d.mts b/worker/node_modules/unenv/dist/runtime/node/internal/dgram/socket.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..de95b5773bf4c604faf4345e85f2aa958538d2b7 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/dgram/socket.d.mts @@ -0,0 +1,31 @@ +import { EventEmitter } from "node:events"; +import type nodeNet from "node:net"; +import type nodeDgram from "node:dgram"; +export declare class Socket extends EventEmitter implements nodeDgram.Socket { + readonly __unenv__: true; + bind(): this; + close(): this; + ref(): this; + unref(): this; + getRecvBufferSize(): number; + getSendBufferSize(): number; + getSendQueueSize(): number; + getSendQueueCount(): number; + setMulticastLoopback(): boolean; + setMulticastTTL(): number; + setTTL(): number; + address(): nodeNet.AddressInfo; + remoteAddress(): nodeNet.AddressInfo; + [Symbol.asyncDispose](); + addMembership(); + addSourceSpecificMembership(); + connect(); + disconnect(); + dropMembership(); + dropSourceSpecificMembership(); + send(); + setSendBufferSize(); + setBroadcast(); + setRecvBufferSize(); + setMulticastInterface(); +} diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/dgram/socket.mjs b/worker/node_modules/unenv/dist/runtime/node/internal/dgram/socket.mjs new file mode 100644 index 0000000000000000000000000000000000000000..be6c229b5219246f166af4ba0abce1f62f668f49 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/dgram/socket.mjs @@ -0,0 +1,61 @@ +import { EventEmitter } from "node:events"; +export class Socket extends EventEmitter { + __unenv__ = true; + bind() { + return this; + } + close() { + return this; + } + ref() { + return this; + } + unref() { + return this; + } + getRecvBufferSize() { + return 1e5; + } + getSendBufferSize() { + return 1e4; + } + getSendQueueSize() { + return 0; + } + getSendQueueCount() { + return 0; + } + setMulticastLoopback() { + return false; + } + setMulticastTTL() { + return 1; + } + setTTL() { + return 1; + } + address() { + return { + address: "127.0.0.1", + family: "IPv4", + port: 1234 + }; + } + remoteAddress() { + throw new Error("ERR_SOCKET_DGRAM_NOT_CONNECTED"); + } + [Symbol.asyncDispose]() { + return Promise.resolve(); + } + addMembership() {} + addSourceSpecificMembership() {} + connect() {} + disconnect() {} + dropMembership() {} + dropSourceSpecificMembership() {} + send() {} + setSendBufferSize() {} + setBroadcast() {} + setRecvBufferSize() {} + setMulticastInterface() {} +} diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/diagnostics_channel/channel.d.mts b/worker/node_modules/unenv/dist/runtime/node/internal/diagnostics_channel/channel.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..f1edd014cf3cf5bcc1dd28489e426b3eef7600df --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/diagnostics_channel/channel.d.mts @@ -0,0 +1,18 @@ +import type nodeDiagnosticsChannel from "node:diagnostics_channel"; +export declare const getChannels: unknown; +export declare class Channel< + StoreType, + ContextType +> implements nodeDiagnosticsChannel.Channel { + readonly __unenv__: true; + name: nodeDiagnosticsChannel.Channel["name"]; + get hasSubscribers(); + _subscribers: nodeDiagnosticsChannel.ChannelListener[]; + constructor(name: nodeDiagnosticsChannel.Channel["name"]); + subscribe(onMessage: nodeDiagnosticsChannel.ChannelListener); + unsubscribe(onMessage: nodeDiagnosticsChannel.ChannelListener); + publish(message: unknown): void; + bindStore(); + unbindStore(); + runStores(); +} diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/diagnostics_channel/channel.mjs b/worker/node_modules/unenv/dist/runtime/node/internal/diagnostics_channel/channel.mjs new file mode 100644 index 0000000000000000000000000000000000000000..09910d2beaa33327622964d874da76d3ee5516ac --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/diagnostics_channel/channel.mjs @@ -0,0 +1,40 @@ +import { createNotImplementedError } from "../../../_internal/utils.mjs"; +const channels = {}; +export const getChannels = () => channels; +export class Channel { + __unenv__ = true; + name; + get hasSubscribers() { + return this._subscribers.length > 0; + } + _subscribers; + constructor(name) { + this.name = name; + this._subscribers = []; + const channels = getChannels(); + channels[name] = this; + } + subscribe(onMessage) { + this._subscribers.push(onMessage); + } + unsubscribe(onMessage) { + const index = this._subscribers.indexOf(onMessage); + if (index === -1) return false; + this._subscribers.splice(index, 1); + return true; + } + publish(message) { + for (const subscriber of this._subscribers) { + subscriber(message, this.name); + } + } + bindStore() { + throw createNotImplementedError("Channel.bindStore"); + } + unbindStore() { + throw createNotImplementedError("Channel.unbindStore"); + } + runStores() { + throw createNotImplementedError("Channel.runStores"); + } +} diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/diagnostics_channel/tracing-channel.d.mts b/worker/node_modules/unenv/dist/runtime/node/internal/diagnostics_channel/tracing-channel.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..e429177f1063d24d874968c5dfb43cfe7c83d053 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/diagnostics_channel/tracing-channel.d.mts @@ -0,0 +1,19 @@ +import type nodeDagnosticsChannel from "node:diagnostics_channel"; +import { Channel } from "./channel.mjs"; +export declare class TracingChannel< + StoreType = unknown, + ContextType extends object = object +> implements nodeDagnosticsChannel.TracingChannel { + readonly __unenv__: true; + asyncEnd: Channel; + asyncStart: Channel; + end: Channel; + error: Channel; + start: Channel; + constructor(nameOrChannels: string | nodeDagnosticsChannel.TracingChannelCollection); + subscribe(handlers: nodeDagnosticsChannel.TracingChannelSubscribers): void; + unsubscribe(handlers: nodeDagnosticsChannel.TracingChannelSubscribers): void; + traceSync(); + tracePromise(); + traceCallback(); +} diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/diagnostics_channel/tracing-channel.mjs b/worker/node_modules/unenv/dist/runtime/node/internal/diagnostics_channel/tracing-channel.mjs new file mode 100644 index 0000000000000000000000000000000000000000..151ac100ed87ecd869fe14cf21f4777d8a0a0e70 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/diagnostics_channel/tracing-channel.mjs @@ -0,0 +1,48 @@ +import { createNotImplementedError } from "../../../_internal/utils.mjs"; +import { Channel } from "./channel.mjs"; +export class TracingChannel { + __unenv__ = true; + asyncEnd = new Channel("asyncEnd"); + asyncStart = new Channel("asyncStart"); + end = new Channel("end"); + error = new Channel("error"); + start = new Channel("start"); + constructor(nameOrChannels) { + if (typeof nameOrChannels === "string") { + this.asyncEnd = new Channel(`trace:${nameOrChannels}:asyncEnd`); + this.asyncStart = new Channel(`trace:${nameOrChannels}:asyncStart`); + this.end = new Channel(`trace:${nameOrChannels}:end`); + this.error = new Channel(`trace:${nameOrChannels}:error`); + this.start = new Channel(`trace:${nameOrChannels}:start`); + } else { + this.asyncStart = nameOrChannels.asyncStart; + this.asyncEnd = nameOrChannels.asyncEnd; + this.end = nameOrChannels.end; + this.error = nameOrChannels.error; + this.start = nameOrChannels.start; + } + } + subscribe(handlers) { + this.asyncEnd?.subscribe(handlers.asyncEnd); + this.asyncStart?.subscribe(handlers.asyncStart); + this.end?.subscribe(handlers.end); + this.error?.subscribe(handlers.error); + this.start?.subscribe(handlers.start); + } + unsubscribe(handlers) { + this.asyncEnd?.unsubscribe(handlers.asyncEnd); + this.asyncStart?.unsubscribe(handlers.asyncStart); + this.end?.unsubscribe(handlers.end); + this.error?.unsubscribe(handlers.error); + this.start?.unsubscribe(handlers.start); + } + traceSync() { + throw createNotImplementedError("TracingChannel.traceSync"); + } + tracePromise() { + throw createNotImplementedError("TracingChannel.tracePromise"); + } + traceCallback() { + throw createNotImplementedError("TracingChannel.traceCallback"); + } +} diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/dns/constants.d.mts b/worker/node_modules/unenv/dist/runtime/node/internal/dns/constants.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..75b0ee66b96699f487bf85e65df9cfbfe5e0cb5d --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/dns/constants.d.mts @@ -0,0 +1,27 @@ +export declare const ADDRCONFIG = 1024; +export declare const ALL = 256; +export declare const V4MAPPED = 2048; +export declare const NODATA = "ENODATA"; +export declare const FORMERR = "EFORMERR"; +export declare const SERVFAIL = "ESERVFAIL"; +export declare const NOTFOUND = "ENOTFOUND"; +export declare const NOTIMP = "ENOTIMP"; +export declare const REFUSED = "EREFUSED"; +export declare const BADQUERY = "EBADQUERY"; +export declare const BADNAME = "EBADNAME"; +export declare const BADFAMILY = "EBADFAMILY"; +export declare const BADRESP = "EBADRESP"; +export declare const CONNREFUSED = "ECONNREFUSED"; +export declare const TIMEOUT = "ETIMEOUT"; +export declare const EOF = "EOF"; +export declare const FILE = "EFILE"; +export declare const NOMEM = "ENOMEM"; +export declare const DESTRUCTION = "EDESTRUCTION"; +export declare const BADSTR = "EBADSTR"; +export declare const BADFLAGS = "EBADFLAGS"; +export declare const NONAME = "ENONAME"; +export declare const BADHINTS = "EBADHINTS"; +export declare const NOTINITIALIZED = "ENOTINITIALIZED"; +export declare const LOADIPHLPAPI = "ELOADIPHLPAPI"; +export declare const ADDRGETNETWORKPARAMS = "EADDRGETNETWORKPARAMS"; +export declare const CANCELLED = "ECANCELLED"; diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/dns/constants.mjs b/worker/node_modules/unenv/dist/runtime/node/internal/dns/constants.mjs new file mode 100644 index 0000000000000000000000000000000000000000..fb098277e0bb6026545cde1b3a71e38facbaacfc --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/dns/constants.mjs @@ -0,0 +1,27 @@ +export const ADDRCONFIG = 1024; +export const ALL = 256; +export const V4MAPPED = 2048; +export const NODATA = "ENODATA"; +export const FORMERR = "EFORMERR"; +export const SERVFAIL = "ESERVFAIL"; +export const NOTFOUND = "ENOTFOUND"; +export const NOTIMP = "ENOTIMP"; +export const REFUSED = "EREFUSED"; +export const BADQUERY = "EBADQUERY"; +export const BADNAME = "EBADNAME"; +export const BADFAMILY = "EBADFAMILY"; +export const BADRESP = "EBADRESP"; +export const CONNREFUSED = "ECONNREFUSED"; +export const TIMEOUT = "ETIMEOUT"; +export const EOF = "EOF"; +export const FILE = "EFILE"; +export const NOMEM = "ENOMEM"; +export const DESTRUCTION = "EDESTRUCTION"; +export const BADSTR = "EBADSTR"; +export const BADFLAGS = "EBADFLAGS"; +export const NONAME = "ENONAME"; +export const BADHINTS = "EBADHINTS"; +export const NOTINITIALIZED = "ENOTINITIALIZED"; +export const LOADIPHLPAPI = "ELOADIPHLPAPI"; +export const ADDRGETNETWORKPARAMS = "EADDRGETNETWORKPARAMS"; +export const CANCELLED = "ECANCELLED"; diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/domain/domain.d.mts b/worker/node_modules/unenv/dist/runtime/node/internal/domain/domain.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..abbcdbc894e7b792010872d8755b61c4add5d74d --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/domain/domain.d.mts @@ -0,0 +1,13 @@ +import { EventEmitter } from "node:events"; +import type nodeDomain from "node:domain"; +export declare class Domain extends EventEmitter implements nodeDomain.Domain { + readonly __unenv__: true; + members: unknown; + add(); + enter(); + exit(); + remove(); + bind(callback: T): T; + intercept(callback: T): T; + run(fn: (...args: any[]) => T, ...args: any[]): T; +} diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/domain/domain.mjs b/worker/node_modules/unenv/dist/runtime/node/internal/domain/domain.mjs new file mode 100644 index 0000000000000000000000000000000000000000..bde96011ac8c2c574e840ab552e395decbade366 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/domain/domain.mjs @@ -0,0 +1,19 @@ +import { createNotImplementedError } from "../../../_internal/utils.mjs"; +import { EventEmitter } from "node:events"; +export class Domain extends EventEmitter { + __unenv__ = true; + members = []; + add() {} + enter() {} + exit() {} + remove() {} + bind(callback) { + throw createNotImplementedError("Domain.bind"); + } + intercept(callback) { + throw createNotImplementedError("Domain.intercept"); + } + run(fn, ...args) { + throw createNotImplementedError("Domain.run"); + } +} diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/events/events.d.mts b/worker/node_modules/unenv/dist/runtime/node/internal/events/events.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..a1771498b92822a54a54044cc43694b185241659 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/events/events.d.mts @@ -0,0 +1,171 @@ +import type nodeEvents from "node:events"; +import { EventEmitter as NodeEventEmitter } from "node:events"; +type Listener = (...args: any[]) => void; +export declare class _EventEmitter implements NodeEventEmitter { + _events: any; + _eventsCount: number; + _maxListeners: number | undefined; + static captureRejectionSymbol; + static errorMonitor; + static kMaxEventTargetListeners; + static kMaxEventTargetListenersWarned; + static usingDomains: boolean; + static get on(); + static get once(); + static get getEventListeners(); + static get getMaxListeners(); + static get addAbortListener(); + static get EventEmitterAsyncResource(); + static get EventEmitter(); + static setMaxListeners(n?, ...eventTargets: (_EventEmitter | EventTarget)[]); + static listenerCount(emitter: NodeEventEmitter, type: string); + static init(); + static get captureRejections(); + static set captureRejections(value); + static get defaultMaxListeners(); + static set defaultMaxListeners(arg); + constructor(opts?: any); + /** + * Increases the max listeners of the event emitter. + * @param {number} n + * @returns {EventEmitter} + */ + setMaxListeners(n: number); + /** + * Returns the current max listener value for the event emitter. + * @returns {number} + */ + getMaxListeners(); + /** + * Synchronously calls each of the listeners registered + * for the event. + * @param {...any} [args] + * @returns {boolean} + */ + emit(type: string | symbol, ...args: any[]); + /** + * Adds a listener to the event emitter. + * @returns {EventEmitter} + */ + addListener(type: string | symbol, listener: Listener); + on(type: string | symbol, listener: Listener); + /** + * Adds the `listener` function to the beginning of + * the listeners array. + */ + prependListener(type: string | symbol, listener: Listener); + /** + * Adds a one-time `listener` function to the event emitter. + */ + once(type: string | symbol, listener: Listener); + /** + * Adds a one-time `listener` function to the beginning of + * the listeners array. + */ + prependOnceListener(type: string | symbol, listener: Listener); + /** + * Removes the specified `listener` from the listeners array. + * @param {string | symbol} type + * @param {Function} listener + * @returns {EventEmitter} + */ + removeListener(type: string | symbol, listener: Listener); + off(type: string | symbol, listener: Listener); + /** + * Removes all listeners from the event emitter. (Only + * removes listeners for a specific event name if specified + * as `type`). + */ + removeAllListeners(type?: string | symbol); + /** + * Returns a copy of the array of listeners for the event name + * specified as `type`. + * @param {string | symbol} type + * @returns {Function[]} + */ + listeners(type: string | symbol); + /** + * Returns a copy of the array of listeners and wrappers for + * the event name specified as `type`. + * @returns {Function[]} + */ + rawListeners(type: string | symbol); + /** + * Returns an array listing the events for which + * the emitter has registered listeners. + * @returns {any[]} + */ + eventNames(); + /** + * Returns the number of listeners listening to event name + */ + listenerCount(eventName: string | symbol, listener?: Listener): number; +} +export declare class EventEmitterAsyncResource extends _EventEmitter { + /** + * @param {{ + * name?: string, + * triggerAsyncId?: number, + * requireManualDestroy?: boolean, + * }} [options] + */ + constructor(options: any); + /** + * @param {symbol,string} event + * @param {...any} args + * @returns {boolean} + */ + emit(event: string | symbol, ...args: any[]): boolean; + /** + * @returns {void} + */ + emitDestroy(); + /** + * @type {number} + */ + get asyncId(); + /** + * @type {number} + */ + get triggerAsyncId(); + /** + * @type {EventEmitterReferencingAsyncResource} + */ + get asyncResource(); +} +/** +* Returns an `AsyncIterator` that iterates `event` events. +* @param {EventEmitter} emitter +* @param {string | symbol} event +* @param {{ +* signal: AbortSignal; +* close?: string[]; +* highWaterMark?: number, +* lowWaterMark?: number +* }} [options] +* @returns {AsyncIterator} +*/ +export declare const on: typeof nodeEvents.on; +/** +* Creates a `Promise` that is fulfilled when the emitter +* emits the given event. +* @param {EventEmitter} emitter +* @param {string} name +* @param {{ signal: AbortSignal; }} [options] +* @returns {Promise} +*/ +export declare const once: typeof nodeEvents.once; +export declare const addAbortListener: typeof nodeEvents.addAbortListener; +/** +* Returns a copy of the array of listeners for the event name +* specified as `type`. +* @returns {Function[]} +*/ +export declare const getEventListeners: typeof nodeEvents.getEventListeners; +/** +* Returns the max listeners set. +* @param {EventEmitter | EventTarget} emitterOrTarget +* @returns {number} +*/ +export declare const getMaxListeners: typeof nodeEvents.getMaxListeners; +export {}; diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/events/events.mjs b/worker/node_modules/unenv/dist/runtime/node/internal/events/events.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3d923ee1945e4c830b4273845695ef7e8bafe78b --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/events/events.mjs @@ -0,0 +1,947 @@ +import { AsyncResource } from "node:async_hooks"; +let defaultMaxListeners = 10; +const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () {}).prototype); +const inspect = (value, _opts) => value; +const ERR_INVALID_THIS = Error; +const ERR_UNHANDLED_ERROR = Error; +const ERR_INVALID_ARG_TYPE = Error; +const AbortError = Error; +const genericNodeError = Error; +const kRejection = /*@__PURE__*/ Symbol.for("nodejs.rejection"); +const kCapture = /*@__PURE__*/ Symbol.for("kCapture"); +const kErrorMonitor = /*@__PURE__*/ Symbol.for("events.errorMonitor"); +const kShapeMode = /*@__PURE__*/ Symbol.for("shapeMode"); +const kMaxEventTargetListeners = /*@__PURE__*/ Symbol.for("events.maxEventTargetListeners"); +const kEnhanceStackBeforeInspector = /*@__PURE__*/ Symbol.for("kEnhanceStackBeforeInspector"); +const kWatermarkData = /*@__PURE__*/ Symbol.for("nodejs.watermarkData"); +const kEventEmitter = /*@__PURE__*/ Symbol.for("kEventEmitter"); +const kAsyncResource = /*@__PURE__*/ Symbol.for("kAsyncResource"); +const kFirstEventParam = /*@__PURE__*/ Symbol.for("kFirstEventParam"); +const kResistStopPropagation = /*@__PURE__*/ Symbol.for("kResistStopPropagation"); +const kMaxEventTargetListenersWarned = /*@__PURE__*/ Symbol.for("events.maxEventTargetListenersWarned"); +export class _EventEmitter { + _events = undefined; + _eventsCount = 0; + _maxListeners = defaultMaxListeners; + [kCapture] = false; + [kShapeMode] = false; + static captureRejectionSymbol = kRejection; + static errorMonitor = kErrorMonitor; + static kMaxEventTargetListeners = kMaxEventTargetListeners; + static kMaxEventTargetListenersWarned = kMaxEventTargetListenersWarned; + static usingDomains = false; + static get on() { + return on; + } + static get once() { + return once; + } + static get getEventListeners() { + return getEventListeners; + } + static get getMaxListeners() { + return getMaxListeners; + } + static get addAbortListener() { + return addAbortListener; + } + static get EventEmitterAsyncResource() { + return EventEmitterAsyncResource; + } + static get EventEmitter() { + return _EventEmitter; + } + static setMaxListeners(n = defaultMaxListeners, ...eventTargets) { + if (eventTargets.length === 0) { + defaultMaxListeners = n; + } else { + for (const target of eventTargets) { + if (isEventTarget(target)) { + target[kMaxEventTargetListeners] = n; + target[kMaxEventTargetListenersWarned] = false; + } else if (typeof target.setMaxListeners === "function") { + target.setMaxListeners(n); + } else { + throw new ERR_INVALID_ARG_TYPE( + "eventTargets", + ["EventEmitter", "EventTarget"], + // @ts-expect-error + target +); + } + } + } + } + static listenerCount(emitter, type) { + if (typeof emitter.listenerCount === "function") { + return emitter.listenerCount(type); + } + _EventEmitter.prototype.listenerCount.call(emitter, type); + } + static init() { + throw new Error("EventEmitter.init() is not implemented."); + } + static get captureRejections() { + return this[kCapture]; + } + static set captureRejections(value) { + this[kCapture] = value; + } + static get defaultMaxListeners() { + return defaultMaxListeners; + } + static set defaultMaxListeners(arg) { + defaultMaxListeners = arg; + } + constructor(opts) { + if (this._events === undefined || this._events === Object.getPrototypeOf(this)._events) { + this._events = { __proto__: null }; + this._eventsCount = 0; + this[kShapeMode] = false; + } else { + this[kShapeMode] = true; + } + this._maxListeners = this._maxListeners || undefined; + if (opts?.captureRejections) { + this[kCapture] = Boolean(opts.captureRejections); + } else { + this[kCapture] = _EventEmitter.prototype[kCapture]; + } + } + /** + * Increases the max listeners of the event emitter. + * @param {number} n + * @returns {EventEmitter} + */ + setMaxListeners(n) { + this._maxListeners = n; + return this; + } + /** + * Returns the current max listener value for the event emitter. + * @returns {number} + */ + getMaxListeners() { + return _getMaxListeners(this); + } + /** + * Synchronously calls each of the listeners registered + * for the event. + * @param {...any} [args] + * @returns {boolean} + */ + emit(type, ...args) { + let doError = type === "error"; + const events = this._events; + if (events !== undefined) { + if (doError && events[kErrorMonitor] !== undefined) this.emit(kErrorMonitor, ...args); + doError = doError && events.error === undefined; + } else if (!doError) return false; + if (doError) { + let er; + if (args.length > 0) er = args[0]; + if (er instanceof Error) { + try { + const capture = {}; + Error.captureStackTrace?.(capture, _EventEmitter.prototype.emit); + Object.defineProperty(er, kEnhanceStackBeforeInspector, { + __proto__: null, + value: Function.prototype.bind(enhanceStackTrace, this, er, capture), + configurable: true + }); + } catch {} + throw er; + } + let stringifiedEr; + try { + stringifiedEr = inspect(er); + } catch { + stringifiedEr = er; + } + const err = new ERR_UNHANDLED_ERROR(stringifiedEr); + err.context = er; + throw err; + } + const handler = events[type]; + if (handler === undefined) return false; + if (typeof handler === "function") { + const result = handler.apply(this, args); + if (result !== undefined && result !== null) { + addCatch(this, result, type, args); + } + } else { + const len = handler.length; + const listeners = arrayClone(handler); + for (let i = 0; i < len; ++i) { + const result = listeners[i].apply(this, args); + if (result !== undefined && result !== null) { + addCatch(this, result, type, args); + } + } + } + return true; + } + /** + * Adds a listener to the event emitter. + * @returns {EventEmitter} + */ + addListener(type, listener) { + _addListener(this, type, listener, false); + return this; + } + on(type, listener) { + return this.addListener(type, listener); + } + /** + * Adds the `listener` function to the beginning of + * the listeners array. + */ + prependListener(type, listener) { + _addListener(this, type, listener, true); + return this; + } + /** + * Adds a one-time `listener` function to the event emitter. + */ + once(type, listener) { + checkListener(listener); + this.on(type, _onceWrap(this, type, listener)); + return this; + } + /** + * Adds a one-time `listener` function to the beginning of + * the listeners array. + */ + prependOnceListener(type, listener) { + checkListener(listener); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + } + /** + * Removes the specified `listener` from the listeners array. + * @param {string | symbol} type + * @param {Function} listener + * @returns {EventEmitter} + */ + removeListener(type, listener) { + checkListener(listener); + const events = this._events; + if (events === undefined) return this; + const list = events[type]; + if (list === undefined) return this; + if (list === listener || list.listener === listener) { + this._eventsCount -= 1; + if (this[kShapeMode]) { + events[type] = undefined; + } else if (this._eventsCount === 0) { + this._events = { __proto__: null }; + } else { + delete events[type]; + if (events.removeListener) this.emit("removeListener", type, list.listener || listener); + } + } else if (typeof list !== "function") { + let position = -1; + for (let i = list.length - 1; i >= 0; i--) { + if (list[i] === listener || list[i].listener === listener) { + position = i; + break; + } + } + if (position < 0) return this; + if (position === 0) list.shift(); + else { + spliceOne(list, position); + } + if (list.length === 1) events[type] = list[0]; + if (events.removeListener !== undefined) this.emit("removeListener", type, listener); + } + return this; + } + off(type, listener) { + return this.removeListener(type, listener); + } + /** + * Removes all listeners from the event emitter. (Only + * removes listeners for a specific event name if specified + * as `type`). + */ + removeAllListeners(type) { + const events = this._events; + if (events === undefined) return this; + if (events.removeListener === undefined) { + if (arguments.length === 0) { + this._events = { __proto__: null }; + this._eventsCount = 0; + } else if (events[type] !== undefined) { + if (--this._eventsCount === 0) this._events = { __proto__: null }; + else delete events[type]; + } + this[kShapeMode] = false; + return this; + } + if (arguments.length === 0) { + for (const key of Reflect.ownKeys(events)) { + if (key === "removeListener") continue; + this.removeAllListeners(key); + } + this.removeAllListeners("removeListener"); + this._events = { __proto__: null }; + this._eventsCount = 0; + this[kShapeMode] = false; + return this; + } + const listeners = events[type]; + if (typeof listeners === "function") { + this.removeListener(type, listeners); + } else if (listeners !== undefined) { + for (let i = listeners.length - 1; i >= 0; i--) { + this.removeListener(type, listeners[i]); + } + } + return this; + } + /** + * Returns a copy of the array of listeners for the event name + * specified as `type`. + * @param {string | symbol} type + * @returns {Function[]} + */ + listeners(type) { + return _listeners(this, type, true); + } + /** + * Returns a copy of the array of listeners and wrappers for + * the event name specified as `type`. + * @returns {Function[]} + */ + rawListeners(type) { + return _listeners(this, type, false); + } + /** + * Returns an array listing the events for which + * the emitter has registered listeners. + * @returns {any[]} + */ + eventNames() { + return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; + } + /** + * Returns the number of listeners listening to event name + */ + listenerCount(eventName, listener) { + const events = this._events; + if (events !== undefined) { + const evlistener = events[eventName]; + if (typeof evlistener === "function") { + if (listener != null) { + return listener === evlistener || listener === evlistener.listener ? 1 : 0; + } + return 1; + } else if (evlistener !== undefined) { + if (listener != null) { + let matching = 0; + for (let i = 0, l = evlistener.length; i < l; i++) { + if (evlistener[i] === listener || evlistener[i].listener === listener) { + matching++; + } + } + return matching; + } + return evlistener.length; + } + } + return 0; + } +} +export class EventEmitterAsyncResource extends _EventEmitter { + /** + * @param {{ + * name?: string, + * triggerAsyncId?: number, + * requireManualDestroy?: boolean, + * }} [options] + */ + constructor(options) { + let name; + if (typeof options === "string") { + name = options; + options = undefined; + } else { + name = options?.name || new.target.name; + } + super(options); + this[kAsyncResource] = new EventEmitterReferencingAsyncResource(this, name, options); + } + /** + * @param {symbol,string} event + * @param {...any} args + * @returns {boolean} + */ + emit(event, ...args) { + if (this[kAsyncResource] === undefined) throw new ERR_INVALID_THIS("EventEmitterAsyncResource"); + const { asyncResource } = this; + Array.prototype.unshift(args, super.emit, this, event); + return Reflect.apply(asyncResource.runInAsyncScope, asyncResource, args); + } + /** + * @returns {void} + */ + emitDestroy() { + if (this[kAsyncResource] === undefined) throw new ERR_INVALID_THIS("EventEmitterAsyncResource"); + this.asyncResource.emitDestroy(); + } + /** + * @type {number} + */ + get asyncId() { + if (this[kAsyncResource] === undefined) throw new ERR_INVALID_THIS("EventEmitterAsyncResource"); + return this.asyncResource.asyncId(); + } + /** + * @type {number} + */ + get triggerAsyncId() { + if (this[kAsyncResource] === undefined) throw new ERR_INVALID_THIS("EventEmitterAsyncResource"); + return this.asyncResource.triggerAsyncId(); + } + /** + * @type {EventEmitterReferencingAsyncResource} + */ + get asyncResource() { + if (this[kAsyncResource] === undefined) throw new ERR_INVALID_THIS("EventEmitterAsyncResource"); + return this[kAsyncResource]; + } +} +class EventEmitterReferencingAsyncResource extends AsyncResource { + /** + * @param {EventEmitter} ee + * @param {string} [type] + * @param {{ + * triggerAsyncId?: number, + * requireManualDestroy?: boolean, + * }} [options] + */ + constructor(ee, type, options) { + super(type, options); + this[kEventEmitter] = ee; + } + /** + * @type {EventEmitter} + */ + get eventEmitter() { + if (this[kEventEmitter] === undefined) throw new ERR_INVALID_THIS("EventEmitterReferencingAsyncResource"); + return this[kEventEmitter]; + } +} +/** +* Returns an `AsyncIterator` that iterates `event` events. +* @param {EventEmitter} emitter +* @param {string | symbol} event +* @param {{ +* signal: AbortSignal; +* close?: string[]; +* highWaterMark?: number, +* lowWaterMark?: number +* }} [options] +* @returns {AsyncIterator} +*/ +export const on = function on(emitter, event, options = {}) { + const signal = options.signal; + if (signal?.aborted) { + throw new AbortError(undefined, { cause: signal?.reason }); + } + const highWatermark = options.highWaterMark ?? options.highWatermark ?? Number.MAX_SAFE_INTEGER; + const lowWatermark = options.lowWaterMark ?? options.lowWatermark ?? 1; + const unconsumedEvents = new FixedQueue(); + const unconsumedPromises = new FixedQueue(); + let paused = false; + let error = null; + let finished = false; + let size = 0; + const iterator = Object.setPrototypeOf({ + next() { + if (size) { + const value = unconsumedEvents.shift(); + size--; + if (paused && size < lowWatermark) { + emitter.resume?.(); + paused = false; + } + return Promise.resolve(createIterResult(value, false)); + } + if (error) { + const p = Promise.reject(error); + error = null; + return p; + } + if (finished) return closeHandler(); + return new Promise(function(resolve, reject) { + unconsumedPromises.push({ + resolve, + reject + }); + }); + }, + return() { + return closeHandler(); + }, + throw(err) { + if (!err || !(err instanceof Error)) { + throw new ERR_INVALID_ARG_TYPE( + "EventEmitter.AsyncIterator", + "Error", + // @ts-expect-error + err +); + } + errorHandler(err); + }, + [Symbol.asyncIterator]() { + return this; + }, + [kWatermarkData]: { + get size() { + return size; + }, + get low() { + return lowWatermark; + }, + get high() { + return highWatermark; + }, + get isPaused() { + return paused; + } + } + }, AsyncIteratorPrototype); + const { addEventListener, removeAll } = listenersController(); + addEventListener(emitter, event, options[kFirstEventParam] ? eventHandler : function(...args) { + return eventHandler(args); + }); + if (event !== "error" && typeof emitter.on === "function") { + addEventListener(emitter, "error", errorHandler); + } + const closeEvents = options?.close; + if (closeEvents?.length) { + for (const closeEvent of closeEvents) { + addEventListener(emitter, closeEvent, closeHandler); + } + } + const abortListenerDisposable = signal ? addAbortListener(signal, abortListener) : null; + return iterator; + function abortListener() { + errorHandler(new AbortError(undefined, { cause: signal?.reason })); + } + function eventHandler(value) { + if (unconsumedPromises.isEmpty()) { + size++; + if (!paused && size > highWatermark) { + paused = true; + emitter.pause?.(); + } + unconsumedEvents.push(value); + } else unconsumedPromises.shift().resolve(createIterResult(value, false)); + } + function errorHandler(err) { + if (unconsumedPromises.isEmpty()) error = err; + else unconsumedPromises.shift().reject(err); + closeHandler(); + } + function closeHandler() { + abortListenerDisposable?.[Symbol.dispose](); + removeAll(); + finished = true; + const doneResult = createIterResult(undefined, true); + while (!unconsumedPromises.isEmpty()) { + unconsumedPromises.shift().resolve(doneResult); + } + return Promise.resolve(doneResult); + } +}; +/** +* Creates a `Promise` that is fulfilled when the emitter +* emits the given event. +* @param {EventEmitter} emitter +* @param {string} name +* @param {{ signal: AbortSignal; }} [options] +* @returns {Promise} +*/ +export const once = async function once(emitter, name, options = {}) { + const signal = options?.signal; + if (signal?.aborted) { + throw new AbortError(undefined, { cause: signal?.reason }); + } + return new Promise((resolve, reject) => { + const errorListener = (err) => { + if (typeof emitter.removeListener === "function") { + emitter.removeListener(name, resolver); + } + if (signal != null) { + eventTargetAgnosticRemoveListener(signal, "abort", abortListener); + } + reject(err); + }; + const resolver = (...args) => { + if (typeof emitter.removeListener === "function") { + emitter.removeListener("error", errorListener); + } + if (signal != null) { + eventTargetAgnosticRemoveListener(signal, "abort", abortListener); + } + resolve(args); + }; + const opts = { + __proto__: null, + once: true, + [kResistStopPropagation]: true + }; + eventTargetAgnosticAddListener(emitter, name, resolver, opts); + if (name !== "error" && typeof emitter.once === "function") { + emitter.once("error", errorListener); + } + function abortListener() { + eventTargetAgnosticRemoveListener(emitter, name, resolver); + eventTargetAgnosticRemoveListener(emitter, "error", errorListener); + reject(new AbortError(undefined, { cause: signal?.reason })); + } + if (signal != null) { + eventTargetAgnosticAddListener(signal, "abort", abortListener, { + __proto__: null, + once: true, + [kResistStopPropagation]: true + }); + } + }); +}; +export const addAbortListener = function addAbortListener(signal, listener) { + if (signal === undefined) { + throw new ERR_INVALID_ARG_TYPE("signal", "AbortSignal", signal); + } + let removeEventListener; + if (signal.aborted) { + queueMicrotask(() => listener()); + } else { + signal.addEventListener("abort", listener, { + __proto__: null, + once: true, + [kResistStopPropagation]: true + }); + removeEventListener = () => { + signal.removeEventListener("abort", listener); + }; + } + return { + __proto__: null, + [Symbol.dispose]() { + removeEventListener?.(); + } + }; +}; +/** +* Returns a copy of the array of listeners for the event name +* specified as `type`. +* @returns {Function[]} +*/ +export const getEventListeners = function getEventListeners(emitterOrTarget, type) { + if (typeof emitterOrTarget.listeners === "function") { + return emitterOrTarget.listeners(type); + } + if (isEventTarget(emitterOrTarget)) { + const root = emitterOrTarget[kEvents].get(type); + const listeners = []; + let handler = root?.next; + while (handler?.listener !== undefined) { + const listener = handler.listener?.deref ? handler.listener.deref() : handler.listener; + listeners.push(listener); + handler = handler.next; + } + return listeners; + } + throw new ERR_INVALID_ARG_TYPE( + "emitter", + ["EventEmitter", "EventTarget"], + // @ts-expect-error + emitterOrTarget +); +}; +/** +* Returns the max listeners set. +* @param {EventEmitter | EventTarget} emitterOrTarget +* @returns {number} +*/ +export const getMaxListeners = function getMaxListeners(emitterOrTarget) { + if (typeof emitterOrTarget?.getMaxListeners === "function") { + return _getMaxListeners(emitterOrTarget); + } else if (emitterOrTarget?.[kMaxEventTargetListeners]) { + return emitterOrTarget[kMaxEventTargetListeners]; + } + throw new ERR_INVALID_ARG_TYPE( + "emitter", + ["EventEmitter", "EventTarget"], + // @ts-expect-error + emitterOrTarget +); +}; +const kSize = 2048; +const kMask = kSize - 1; +class FixedCircularBuffer { + bottom; + top; + list; + next; + constructor() { + this.bottom = 0; + this.top = 0; + this.list = new Array(kSize); + this.next = null; + } + isEmpty() { + return this.top === this.bottom; + } + isFull() { + return (this.top + 1 & kMask) === this.bottom; + } + push(data) { + this.list[this.top] = data; + this.top = this.top + 1 & kMask; + } + shift() { + const nextItem = this.list[this.bottom]; + if (nextItem === undefined) return null; + this.list[this.bottom] = undefined; + this.bottom = this.bottom + 1 & kMask; + return nextItem; + } +} +class FixedQueue { + head; + tail; + constructor() { + this.head = this.tail = new FixedCircularBuffer(); + } + isEmpty() { + return this.head.isEmpty(); + } + push(data) { + if (this.head.isFull()) { + this.head = this.head.next = new FixedCircularBuffer(); + } + this.head.push(data); + } + shift() { + const tail = this.tail; + const next = tail.shift(); + if (tail.isEmpty() && tail.next !== null) { + this.tail = tail.next; + tail.next = null; + } + return next; + } +} +function isEventTarget(emitter) { + return typeof emitter?.addEventListener === "function"; +} +function checkListener(listener) {} +function addCatch(that, promise, type, args) { + if (!that[kCapture]) { + return; + } + try { + const then = promise.then; + if (typeof then === "function") { + then.call(promise, undefined, function(err) { + process.nextTick(emitUnhandledRejectionOrErr, that, err, type, args); + }); + } + } catch (error_) { + that.emit("error", error_); + } +} +function emitUnhandledRejectionOrErr(ee, err, type, args) { + if (typeof ee[kRejection] === "function") { + ee[kRejection](err, type, ...args); + } else { + const prev = ee[kCapture]; + try { + ee[kCapture] = false; + ee.emit("error", err); + } finally { + ee[kCapture] = prev; + } + } +} +function _getMaxListeners(that) { + if (that._maxListeners === undefined) return defaultMaxListeners; + return that._maxListeners; +} +function enhanceStackTrace(err, own) { + let ctorInfo = ""; + try { + const { name } = this.constructor; + if (name !== "EventEmitter") ctorInfo = ` on ${name} instance`; + } catch {} + const sep = `\nEmitted 'error' event${ctorInfo} at:\n`; + const ownStack = (own.stack || "").split("\n").slice(1); + return err.stack + sep + ownStack.join("\n"); +} +function _addListener(target, type, listener, prepend) { + let m; + let events; + let existing; + checkListener(listener); + events = target._events; + if (events === undefined) { + events = target._events = { __proto__: null }; + target._eventsCount = 0; + } else { + if (events.newListener !== undefined) { + target.emit("newListener", type, listener.listener ?? listener); + events = target._events; + } + existing = events[type]; + } + if (existing === undefined) { + events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === "function") { + existing = events[type] = prepend ? [listener, existing] : [existing, listener]; + } else if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + m = _getMaxListeners(target); + if (m > 0 && existing.length > m && !existing.warned) { + existing.warned = true; + const w = new genericNodeError(`Possible EventEmitter memory leak detected. ${existing.length} ${String(type)} listeners ` + `added to ${inspect(target, { depth: -1 })}. MaxListeners is ${m}. Use emitter.setMaxListeners() to increase limit`, { + name: "MaxListenersExceededWarning", + emitter: target, + type, + count: existing.length + }); + process.emitWarning(w); + } + } + return target; +} +function onceWrapper() { + if (!this.fired) { + this.target.removeListener(this.type, this.wrapFn); + this.fired = true; + if (arguments.length === 0) return this.listener.call(this.target); + return this.listener.apply(this.target, arguments); + } +} +function _onceWrap(target, type, listener) { + const state = { + fired: false, + wrapFn: undefined, + target, + type, + listener + }; + const wrapped = onceWrapper.bind(state); + wrapped.listener = listener; + state.wrapFn = wrapped; + return wrapped; +} +function _listeners(target, type, unwrap) { + const events = target._events; + if (events === undefined) return []; + const evlistener = events[type]; + if (evlistener === undefined) return []; + if (typeof evlistener === "function") return unwrap ? [evlistener.listener || evlistener] : [evlistener]; + return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener); +} +function arrayClone(arr) { + switch (arr.length) { + case 2: return [arr[0], arr[1]]; + case 3: return [ + arr[0], + arr[1], + arr[2] + ]; + case 4: return [ + arr[0], + arr[1], + arr[2], + arr[3] + ]; + case 5: return [ + arr[0], + arr[1], + arr[2], + arr[3], + arr[4] + ]; + case 6: return [ + arr[0], + arr[1], + arr[2], + arr[3], + arr[4], + arr[5] + ]; + } + return Array.prototype.slice(arr); +} +function unwrapListeners(arr) { + const ret = arrayClone(arr); + for (let i = 0; i < ret.length; ++i) { + const orig = ret[i].listener; + if (typeof orig === "function") ret[i] = orig; + } + return ret; +} +function createIterResult(value, done) { + return { + value, + done + }; +} +function eventTargetAgnosticRemoveListener(emitter, name, listener, flags) { + if (typeof emitter.removeListener === "function") { + emitter.removeListener(name, listener); + } else if (typeof emitter.removeEventListener === "function") { + emitter.removeEventListener(name, listener, flags); + } else { + throw new ERR_INVALID_ARG_TYPE("emitter", "EventEmitter", emitter); + } +} +function eventTargetAgnosticAddListener(emitter, name, listener, flags) { + if (typeof emitter.on === "function") { + if (flags?.once) { + emitter.once(name, listener); + } else { + emitter.on(name, listener); + } + } else if (typeof emitter.addEventListener === "function") { + emitter.addEventListener(name, listener, flags); + } else { + throw new ERR_INVALID_ARG_TYPE("emitter", "EventEmitter", emitter); + } +} +function listenersController() { + const listeners = []; + return { + addEventListener(emitter, event, handler, flags) { + eventTargetAgnosticAddListener(emitter, event, handler, flags); + Array.prototype.push(listeners, [ + emitter, + event, + handler, + flags + ]); + }, + removeAll() { + while (listeners.length > 0) { + Reflect.apply(eventTargetAgnosticRemoveListener, undefined, listeners.pop()); + } + } + }; +} +function spliceOne(list, index) { + for (; index + 1 < list.length; index++) list[index] = list[index + 1]; + list.pop(); +} diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/fs/classes.d.mts b/worker/node_modules/unenv/dist/runtime/node/internal/fs/classes.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..7cc1acd7c9294ccde0bf4d40aadd3227e5d8cbee --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/fs/classes.d.mts @@ -0,0 +1,8 @@ +import type nodeFs from "node:fs"; +export declare const Dir: typeof nodeFs.Dir; +export declare const Dirent: typeof nodeFs.Dirent; +export declare const Stats: typeof nodeFs.Stats; +export declare const ReadStream: typeof nodeFs.ReadStream; +export declare const WriteStream: typeof nodeFs.WriteStream; +export declare const FileReadStream: unknown; +export declare const FileWriteStream: unknown; diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/fs/classes.mjs b/worker/node_modules/unenv/dist/runtime/node/internal/fs/classes.mjs new file mode 100644 index 0000000000000000000000000000000000000000..edaacf5a36554466ea3f8071d38834b759080a68 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/fs/classes.mjs @@ -0,0 +1,8 @@ +import { notImplementedClass } from "../../../_internal/utils.mjs"; +export const Dir = /*@__PURE__*/ notImplementedClass("fs.Dir"); +export const Dirent = /*@__PURE__*/ notImplementedClass("fs.Dirent"); +export const Stats = /*@__PURE__*/ notImplementedClass("fs.Stats"); +export const ReadStream = /*@__PURE__*/ notImplementedClass("fs.ReadStream"); +export const WriteStream = /*@__PURE__*/ notImplementedClass("fs.WriteStream"); +export const FileReadStream = ReadStream; +export const FileWriteStream = WriteStream; diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/fs/constants.d.mts b/worker/node_modules/unenv/dist/runtime/node/internal/fs/constants.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..ee6946905d3dfb7963bcb060eeb92ea207cc3075 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/fs/constants.d.mts @@ -0,0 +1,58 @@ +export declare const UV_FS_SYMLINK_DIR = 1; +export declare const UV_FS_SYMLINK_JUNCTION = 2; +export declare const O_RDONLY = 0; +export declare const O_WRONLY = 1; +export declare const O_RDWR = 2; +export declare const UV_DIRENT_UNKNOWN = 0; +export declare const UV_DIRENT_FILE = 1; +export declare const UV_DIRENT_DIR = 2; +export declare const UV_DIRENT_LINK = 3; +export declare const UV_DIRENT_FIFO = 4; +export declare const UV_DIRENT_SOCKET = 5; +export declare const UV_DIRENT_CHAR = 6; +export declare const UV_DIRENT_BLOCK = 7; +export declare const EXTENSIONLESS_FORMAT_JAVASCRIPT = 0; +export declare const EXTENSIONLESS_FORMAT_WASM = 1; +export declare const S_IFMT = 61440; +export declare const S_IFREG = 32768; +export declare const S_IFDIR = 16384; +export declare const S_IFCHR = 8192; +export declare const S_IFBLK = 24576; +export declare const S_IFIFO = 4096; +export declare const S_IFLNK = 40960; +export declare const S_IFSOCK = 49152; +export declare const O_CREAT = 64; +export declare const O_EXCL = 128; +export declare const UV_FS_O_FILEMAP = 0; +export declare const O_NOCTTY = 256; +export declare const O_TRUNC = 512; +export declare const O_APPEND = 1024; +export declare const O_DIRECTORY = 65536; +export declare const O_NOATIME = 262144; +export declare const O_NOFOLLOW = 131072; +export declare const O_SYNC = 1052672; +export declare const O_DSYNC = 4096; +export declare const O_DIRECT = 16384; +export declare const O_NONBLOCK = 2048; +export declare const S_IRWXU = 448; +export declare const S_IRUSR = 256; +export declare const S_IWUSR = 128; +export declare const S_IXUSR = 64; +export declare const S_IRWXG = 56; +export declare const S_IRGRP = 32; +export declare const S_IWGRP = 16; +export declare const S_IXGRP = 8; +export declare const S_IRWXO = 7; +export declare const S_IROTH = 4; +export declare const S_IWOTH = 2; +export declare const S_IXOTH = 1; +export declare const F_OK = 0; +export declare const R_OK = 4; +export declare const W_OK = 2; +export declare const X_OK = 1; +export declare const UV_FS_COPYFILE_EXCL = 1; +export declare const COPYFILE_EXCL = 1; +export declare const UV_FS_COPYFILE_FICLONE = 2; +export declare const COPYFILE_FICLONE = 2; +export declare const UV_FS_COPYFILE_FICLONE_FORCE = 4; +export declare const COPYFILE_FICLONE_FORCE = 4; diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/fs/constants.mjs b/worker/node_modules/unenv/dist/runtime/node/internal/fs/constants.mjs new file mode 100644 index 0000000000000000000000000000000000000000..0c21e8029e8e69f5048edac4a872162f9ecabf28 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/fs/constants.mjs @@ -0,0 +1,58 @@ +export const UV_FS_SYMLINK_DIR = 1; +export const UV_FS_SYMLINK_JUNCTION = 2; +export const O_RDONLY = 0; +export const O_WRONLY = 1; +export const O_RDWR = 2; +export const UV_DIRENT_UNKNOWN = 0; +export const UV_DIRENT_FILE = 1; +export const UV_DIRENT_DIR = 2; +export const UV_DIRENT_LINK = 3; +export const UV_DIRENT_FIFO = 4; +export const UV_DIRENT_SOCKET = 5; +export const UV_DIRENT_CHAR = 6; +export const UV_DIRENT_BLOCK = 7; +export const EXTENSIONLESS_FORMAT_JAVASCRIPT = 0; +export const EXTENSIONLESS_FORMAT_WASM = 1; +export const S_IFMT = 61440; +export const S_IFREG = 32768; +export const S_IFDIR = 16384; +export const S_IFCHR = 8192; +export const S_IFBLK = 24576; +export const S_IFIFO = 4096; +export const S_IFLNK = 40960; +export const S_IFSOCK = 49152; +export const O_CREAT = 64; +export const O_EXCL = 128; +export const UV_FS_O_FILEMAP = 0; +export const O_NOCTTY = 256; +export const O_TRUNC = 512; +export const O_APPEND = 1024; +export const O_DIRECTORY = 65536; +export const O_NOATIME = 262144; +export const O_NOFOLLOW = 131072; +export const O_SYNC = 1052672; +export const O_DSYNC = 4096; +export const O_DIRECT = 16384; +export const O_NONBLOCK = 2048; +export const S_IRWXU = 448; +export const S_IRUSR = 256; +export const S_IWUSR = 128; +export const S_IXUSR = 64; +export const S_IRWXG = 56; +export const S_IRGRP = 32; +export const S_IWGRP = 16; +export const S_IXGRP = 8; +export const S_IRWXO = 7; +export const S_IROTH = 4; +export const S_IWOTH = 2; +export const S_IXOTH = 1; +export const F_OK = 0; +export const R_OK = 4; +export const W_OK = 2; +export const X_OK = 1; +export const UV_FS_COPYFILE_EXCL = 1; +export const COPYFILE_EXCL = 1; +export const UV_FS_COPYFILE_FICLONE = 2; +export const COPYFILE_FICLONE = 2; +export const UV_FS_COPYFILE_FICLONE_FORCE = 4; +export const COPYFILE_FICLONE_FORCE = 4; diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/fs/fs.d.mts b/worker/node_modules/unenv/dist/runtime/node/internal/fs/fs.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..c3273d98a0efa32c602e546c8d23f29dc1e404d2 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/fs/fs.d.mts @@ -0,0 +1,94 @@ +import type nodeFs from "node:fs"; +export declare const access: typeof nodeFs.access; +export declare const appendFile: typeof nodeFs.appendFile; +export declare const chown: typeof nodeFs.chown; +export declare const chmod: typeof nodeFs.chmod; +export declare const copyFile: typeof nodeFs.copyFile; +export declare const cp: typeof nodeFs.cp; +export declare const lchown: typeof nodeFs.lchown; +export declare const lchmod: typeof nodeFs.lchmod; +export declare const link: typeof nodeFs.link; +export declare const lstat: typeof nodeFs.lstat; +export declare const lutimes: typeof nodeFs.lutimes; +export declare const mkdir: typeof nodeFs.mkdir; +export declare const mkdtemp: typeof nodeFs.mkdtemp; +export declare const realpath: typeof nodeFs.realpath; +export declare const open: typeof nodeFs.open; +export declare const opendir: typeof nodeFs.opendir; +export declare const readdir: typeof nodeFs.readdir; +export declare const readFile: typeof nodeFs.readFile; +export declare const readlink: typeof nodeFs.readlink; +export declare const rename: typeof nodeFs.rename; +export declare const rm: typeof nodeFs.rm; +export declare const rmdir: typeof nodeFs.rmdir; +export declare const stat: typeof nodeFs.stat; +export declare const symlink: typeof nodeFs.symlink; +export declare const truncate: typeof nodeFs.truncate; +export declare const unlink: typeof nodeFs.unlink; +export declare const utimes: typeof nodeFs.utimes; +export declare const writeFile: typeof nodeFs.writeFile; +export declare const statfs: typeof nodeFs.statfs; +export declare const close: typeof nodeFs.close; +export declare const createReadStream: typeof nodeFs.createReadStream; +export declare const createWriteStream: typeof nodeFs.createWriteStream; +export declare const exists: typeof nodeFs.exists; +export declare const fchown: typeof nodeFs.fchown; +export declare const fchmod: typeof nodeFs.fchmod; +export declare const fdatasync: typeof nodeFs.fdatasync; +export declare const fstat: typeof nodeFs.fstat; +export declare const fsync: typeof nodeFs.fsync; +export declare const ftruncate: typeof nodeFs.ftruncate; +export declare const futimes: typeof nodeFs.futimes; +export declare const lstatSync: typeof nodeFs.lstatSync; +export declare const read: typeof nodeFs.read; +export declare const readv: typeof nodeFs.readv; +export declare const realpathSync: typeof nodeFs.realpathSync; +export declare const statSync: typeof nodeFs.statSync; +export declare const unwatchFile: typeof nodeFs.unwatchFile; +export declare const watch: typeof nodeFs.watch; +export declare const watchFile: typeof nodeFs.watchFile; +export declare const write: typeof nodeFs.write; +export declare const writev: typeof nodeFs.writev; +export declare const _toUnixTimestamp: unknown; +export declare const openAsBlob: typeof nodeFs.openAsBlob; +export declare const glob: typeof nodeFs.glob; +export declare const appendFileSync: unknown; +export declare const accessSync: unknown; +export declare const chownSync: unknown; +export declare const chmodSync: unknown; +export declare const closeSync: unknown; +export declare const copyFileSync: unknown; +export declare const cpSync: unknown; +export declare const existsSync: typeof nodeFs.existsSync; +export declare const fchownSync: unknown; +export declare const fchmodSync: unknown; +export declare const fdatasyncSync: unknown; +export declare const fstatSync: typeof nodeFs.fstatSync; +export declare const fsyncSync: unknown; +export declare const ftruncateSync: unknown; +export declare const futimesSync: unknown; +export declare const lchownSync: unknown; +export declare const lchmodSync: unknown; +export declare const linkSync: unknown; +export declare const lutimesSync: unknown; +export declare const mkdirSync: unknown; +export declare const mkdtempSync: typeof nodeFs.mkdtempSync; +export declare const openSync: unknown; +export declare const opendirSync: unknown; +export declare const readdirSync: typeof nodeFs.readdirSync; +export declare const readSync: unknown; +export declare const readvSync: unknown; +export declare const readFileSync: typeof nodeFs.readFileSync; +export declare const readlinkSync: typeof nodeFs.readlinkSync; +export declare const renameSync: unknown; +export declare const rmSync: unknown; +export declare const rmdirSync: unknown; +export declare const symlinkSync: unknown; +export declare const truncateSync: unknown; +export declare const unlinkSync: unknown; +export declare const utimesSync: unknown; +export declare const writeFileSync: unknown; +export declare const writeSync: unknown; +export declare const writevSync: unknown; +export declare const statfsSync: typeof nodeFs.statfsSync; +export declare const globSync: unknown; diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/fs/fs.mjs b/worker/node_modules/unenv/dist/runtime/node/internal/fs/fs.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d4fb73135c2b5e1b165c915072ee3fc65e6b1ce0 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/fs/fs.mjs @@ -0,0 +1,104 @@ +import { notImplemented, notImplementedAsync } from "../../../_internal/utils.mjs"; +import * as fsp from "./promises.mjs"; +function callbackify(fn) { + const fnc = function(...args) { + const cb = args.pop(); + fn().catch((error) => cb(error)).then((val) => cb(undefined, val)); + }; + fnc.__promisify__ = fn; + fnc.native = fnc; + return fnc; +} +export const access = callbackify(fsp.access); +export const appendFile = callbackify(fsp.appendFile); +export const chown = callbackify(fsp.chown); +export const chmod = callbackify(fsp.chmod); +export const copyFile = callbackify(fsp.copyFile); +export const cp = callbackify(fsp.cp); +export const lchown = callbackify(fsp.lchown); +export const lchmod = callbackify(fsp.lchmod); +export const link = callbackify(fsp.link); +export const lstat = callbackify(fsp.lstat); +export const lutimes = callbackify(fsp.lutimes); +export const mkdir = callbackify(fsp.mkdir); +export const mkdtemp = callbackify(fsp.mkdtemp); +export const realpath = callbackify(fsp.realpath); +export const open = callbackify(fsp.open); +export const opendir = callbackify(fsp.opendir); +export const readdir = callbackify(fsp.readdir); +export const readFile = callbackify(fsp.readFile); +export const readlink = callbackify(fsp.readlink); +export const rename = callbackify(fsp.rename); +export const rm = callbackify(fsp.rm); +export const rmdir = callbackify(fsp.rmdir); +export const stat = callbackify(fsp.stat); +export const symlink = callbackify(fsp.symlink); +export const truncate = callbackify(fsp.truncate); +export const unlink = callbackify(fsp.unlink); +export const utimes = callbackify(fsp.utimes); +export const writeFile = callbackify(fsp.writeFile); +export const statfs = callbackify(fsp.statfs); +export const close = /*@__PURE__*/ notImplementedAsync("fs.close"); +export const createReadStream = /*@__PURE__*/ notImplementedAsync("fs.createReadStream"); +export const createWriteStream = /*@__PURE__*/ notImplementedAsync("fs.createWriteStream"); +export const exists = /*@__PURE__*/ notImplementedAsync("fs.exists"); +export const fchown = /*@__PURE__*/ notImplementedAsync("fs.fchown"); +export const fchmod = /*@__PURE__*/ notImplementedAsync("fs.fchmod"); +export const fdatasync = /*@__PURE__*/ notImplementedAsync("fs.fdatasync"); +export const fstat = /*@__PURE__*/ notImplementedAsync("fs.fstat"); +export const fsync = /*@__PURE__*/ notImplementedAsync("fs.fsync"); +export const ftruncate = /*@__PURE__*/ notImplementedAsync("fs.ftruncate"); +export const futimes = /*@__PURE__*/ notImplementedAsync("fs.futimes"); +export const lstatSync = /*@__PURE__*/ notImplementedAsync("fs.lstatSync"); +export const read = /*@__PURE__*/ notImplementedAsync("fs.read"); +export const readv = /*@__PURE__*/ notImplementedAsync("fs.readv"); +export const realpathSync = /*@__PURE__*/ notImplementedAsync("fs.realpathSync"); +export const statSync = /*@__PURE__*/ notImplementedAsync("fs.statSync"); +export const unwatchFile = /*@__PURE__*/ notImplementedAsync("fs.unwatchFile"); +export const watch = /*@__PURE__*/ notImplementedAsync("fs.watch"); +export const watchFile = /*@__PURE__*/ notImplementedAsync("fs.watchFile"); +export const write = /*@__PURE__*/ notImplementedAsync("fs.write"); +export const writev = /*@__PURE__*/ notImplementedAsync("fs.writev"); +export const _toUnixTimestamp = /*@__PURE__*/ notImplementedAsync("fs._toUnixTimestamp"); +export const openAsBlob = /*@__PURE__*/ notImplementedAsync("fs.openAsBlob"); +export const glob = /*@__PURE__*/ notImplementedAsync("fs.glob"); +export const appendFileSync = /*@__PURE__*/ notImplemented("fs.appendFileSync"); +export const accessSync = /*@__PURE__*/ notImplemented("fs.accessSync"); +export const chownSync = /*@__PURE__*/ notImplemented("fs.chownSync"); +export const chmodSync = /*@__PURE__*/ notImplemented("fs.chmodSync"); +export const closeSync = /*@__PURE__*/ notImplemented("fs.closeSync"); +export const copyFileSync = /*@__PURE__*/ notImplemented("fs.copyFileSync"); +export const cpSync = /*@__PURE__*/ notImplemented("fs.cpSync"); +export const existsSync = () => false; +export const fchownSync = /*@__PURE__*/ notImplemented("fs.fchownSync"); +export const fchmodSync = /*@__PURE__*/ notImplemented("fs.fchmodSync"); +export const fdatasyncSync = /*@__PURE__*/ notImplemented("fs.fdatasyncSync"); +export const fstatSync = /*@__PURE__*/ notImplemented("fs.fstatSync"); +export const fsyncSync = /*@__PURE__*/ notImplemented("fs.fsyncSync"); +export const ftruncateSync = /*@__PURE__*/ notImplemented("fs.ftruncateSync"); +export const futimesSync = /*@__PURE__*/ notImplemented("fs.futimesSync"); +export const lchownSync = /*@__PURE__*/ notImplemented("fs.lchownSync"); +export const lchmodSync = /*@__PURE__*/ notImplemented("fs.lchmodSync"); +export const linkSync = /*@__PURE__*/ notImplemented("fs.linkSync"); +export const lutimesSync = /*@__PURE__*/ notImplemented("fs.lutimesSync"); +export const mkdirSync = /*@__PURE__*/ notImplemented("fs.mkdirSync"); +export const mkdtempSync = /*@__PURE__*/ notImplemented("fs.mkdtempSync"); +export const openSync = /*@__PURE__*/ notImplemented("fs.openSync"); +export const opendirSync = /*@__PURE__*/ notImplemented("fs.opendirSync"); +export const readdirSync = /*@__PURE__*/ notImplemented("fs.readdirSync"); +export const readSync = /*@__PURE__*/ notImplemented("fs.readSync"); +export const readvSync = /*@__PURE__*/ notImplemented("fs.readvSync"); +export const readFileSync = /*@__PURE__*/ notImplemented("fs.readFileSync"); +export const readlinkSync = /*@__PURE__*/ notImplemented("fs.readlinkSync"); +export const renameSync = /*@__PURE__*/ notImplemented("fs.renameSync"); +export const rmSync = /*@__PURE__*/ notImplemented("fs.rmSync"); +export const rmdirSync = /*@__PURE__*/ notImplemented("fs.rmdirSync"); +export const symlinkSync = /*@__PURE__*/ notImplemented("fs.symlinkSync"); +export const truncateSync = /*@__PURE__*/ notImplemented("fs.truncateSync"); +export const unlinkSync = /*@__PURE__*/ notImplemented("fs.unlinkSync"); +export const utimesSync = /*@__PURE__*/ notImplemented("fs.utimesSync"); +export const writeFileSync = /*@__PURE__*/ notImplemented("fs.writeFileSync"); +export const writeSync = /*@__PURE__*/ notImplemented("fs.writeSync"); +export const writevSync = /*@__PURE__*/ notImplemented("fs.writevSync"); +export const statfsSync = /*@__PURE__*/ notImplemented("fs.statfsSync"); +export const globSync = /*@__PURE__*/ notImplemented("fs.globSync"); diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/fs/promises.d.mts b/worker/node_modules/unenv/dist/runtime/node/internal/fs/promises.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..c8cf04570245ec3b146b761f005fbdfad1bf0d99 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/fs/promises.d.mts @@ -0,0 +1,32 @@ +import type nodeFsPromises from "node:fs/promises"; +export declare const access: unknown; +export declare const copyFile: unknown; +export declare const cp: unknown; +export declare const open: unknown; +export declare const opendir: unknown; +export declare const rename: unknown; +export declare const truncate: unknown; +export declare const rm: unknown; +export declare const rmdir: unknown; +export declare const mkdir: typeof nodeFsPromises.mkdir; +export declare const readdir: typeof nodeFsPromises.readdir; +export declare const readlink: typeof nodeFsPromises.readlink; +export declare const symlink: unknown; +export declare const lstat: typeof nodeFsPromises.lstat; +export declare const stat: typeof nodeFsPromises.stat; +export declare const link: unknown; +export declare const unlink: unknown; +export declare const chmod: unknown; +export declare const lchmod: unknown; +export declare const lchown: unknown; +export declare const chown: unknown; +export declare const utimes: unknown; +export declare const lutimes: unknown; +export declare const realpath: typeof nodeFsPromises.realpath; +export declare const mkdtemp: typeof nodeFsPromises.mkdtemp; +export declare const writeFile: unknown; +export declare const appendFile: unknown; +export declare const readFile: typeof nodeFsPromises.readFile; +export declare const watch: typeof nodeFsPromises.watch; +export declare const statfs: typeof nodeFsPromises.statfs; +export declare const glob: unknown; diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/fs/promises.mjs b/worker/node_modules/unenv/dist/runtime/node/internal/fs/promises.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6ba4adbd0d4e605c35cb0616900aef1cd55b036f --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/fs/promises.mjs @@ -0,0 +1,32 @@ +import { notImplemented } from "../../../_internal/utils.mjs"; +export const access = /*@__PURE__*/ notImplemented("fs.access"); +export const copyFile = /*@__PURE__*/ notImplemented("fs.copyFile"); +export const cp = /*@__PURE__*/ notImplemented("fs.cp"); +export const open = /*@__PURE__*/ notImplemented("fs.open"); +export const opendir = /*@__PURE__*/ notImplemented("fs.opendir"); +export const rename = /*@__PURE__*/ notImplemented("fs.rename"); +export const truncate = /*@__PURE__*/ notImplemented("fs.truncate"); +export const rm = /*@__PURE__*/ notImplemented("fs.rm"); +export const rmdir = /*@__PURE__*/ notImplemented("fs.rmdir"); +export const mkdir = /*@__PURE__*/ notImplemented("fs.mkdir"); +export const readdir = /*@__PURE__*/ notImplemented("fs.readdir"); +export const readlink = /*@__PURE__*/ notImplemented("fs.readlink"); +export const symlink = /*@__PURE__*/ notImplemented("fs.symlink"); +export const lstat = /*@__PURE__*/ notImplemented("fs.lstat"); +export const stat = /*@__PURE__*/ notImplemented("fs.stat"); +export const link = /*@__PURE__*/ notImplemented("fs.link"); +export const unlink = /*@__PURE__*/ notImplemented("fs.unlink"); +export const chmod = /*@__PURE__*/ notImplemented("fs.chmod"); +export const lchmod = /*@__PURE__*/ notImplemented("fs.lchmod"); +export const lchown = /*@__PURE__*/ notImplemented("fs.lchown"); +export const chown = /*@__PURE__*/ notImplemented("fs.chown"); +export const utimes = /*@__PURE__*/ notImplemented("fs.utimes"); +export const lutimes = /*@__PURE__*/ notImplemented("fs.lutimes"); +export const realpath = /*@__PURE__*/ notImplemented("fs.realpath"); +export const mkdtemp = /*@__PURE__*/ notImplemented("fs.mkdtemp"); +export const writeFile = /*@__PURE__*/ notImplemented("fs.writeFile"); +export const appendFile = /*@__PURE__*/ notImplemented("fs.appendFile"); +export const readFile = /*@__PURE__*/ notImplemented("fs.readFile"); +export const watch = /*@__PURE__*/ notImplemented("fs.watch"); +export const statfs = /*@__PURE__*/ notImplemented("fs.statfs"); +export const glob = /*@__PURE__*/ notImplemented("fs.glob"); diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/http/agent.d.mts b/worker/node_modules/unenv/dist/runtime/node/internal/http/agent.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..113fda9b4f48d938cef38faad71f3070abad1d75 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/http/agent.d.mts @@ -0,0 +1,12 @@ +import type nodeHttp from "node:http"; +import { EventEmitter } from "node:events"; +export declare class Agent extends EventEmitter implements nodeHttp.Agent { + __unenv__: {}; + maxFreeSockets: number; + maxSockets: number; + maxTotalSockets: number; + readonly freeSockets: {}; + readonly sockets: {}; + readonly requests: {}; + destroy(): void; +} diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/http/agent.mjs b/worker/node_modules/unenv/dist/runtime/node/internal/http/agent.mjs new file mode 100644 index 0000000000000000000000000000000000000000..93af3ac9974efd2f3f8ff25f1955718cdcb1afd0 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/http/agent.mjs @@ -0,0 +1,11 @@ +import { EventEmitter } from "node:events"; +export class Agent extends EventEmitter { + __unenv__ = {}; + maxFreeSockets = 256; + maxSockets = Infinity; + maxTotalSockets = Infinity; + freeSockets = {}; + sockets = {}; + requests = {}; + destroy() {} +} diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/http/constants.d.mts b/worker/node_modules/unenv/dist/runtime/node/internal/http/constants.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..64bb7183634c516e0056c71c1562e993caebf58b --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/http/constants.d.mts @@ -0,0 +1,67 @@ +export declare const METHODS: unknown; +export declare const STATUS_CODES: { + 100: string + 101: string + 102: string + 103: string + 200: string + 201: string + 202: string + 203: string + 204: string + 205: string + 206: string + 207: string + 208: string + 226: string + 300: string + 301: string + 302: string + 303: string + 304: string + 305: string + 307: string + 308: string + 400: string + 401: string + 402: string + 403: string + 404: string + 405: string + 406: string + 407: string + 408: string + 409: string + 410: string + 411: string + 412: string + 413: string + 414: string + 415: string + 416: string + 417: string + 418: string + 421: string + 422: string + 423: string + 424: string + 425: string + 426: string + 428: string + 429: string + 431: string + 451: string + 500: string + 501: string + 502: string + 503: string + 504: string + 505: string + 506: string + 507: string + 508: string + 509: string + 510: string + 511: string +}; +export declare const maxHeaderSize = 16384; diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/http/constants.mjs b/worker/node_modules/unenv/dist/runtime/node/internal/http/constants.mjs new file mode 100644 index 0000000000000000000000000000000000000000..bc433eacb2ab48faab9d681bfbf62081cb385b21 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/http/constants.mjs @@ -0,0 +1,103 @@ +export const METHODS = [ + "ACL", + "BIND", + "CHECKOUT", + "CONNECT", + "COPY", + "DELETE", + "GET", + "HEAD", + "LINK", + "LOCK", + "M-SEARCH", + "MERGE", + "MKACTIVITY", + "MKCALENDAR", + "MKCOL", + "MOVE", + "NOTIFY", + "OPTIONS", + "PATCH", + "POST", + "PRI", + "PROPFIND", + "PROPPATCH", + "PURGE", + "PUT", + "REBIND", + "REPORT", + "SEARCH", + "SOURCE", + "SUBSCRIBE", + "TRACE", + "UNBIND", + "UNLINK", + "UNLOCK", + "UNSUBSCRIBE" +]; +export const STATUS_CODES = { + 100: "Continue", + 101: "Switching Protocols", + 102: "Processing", + 103: "Early Hints", + 200: "OK", + 201: "Created", + 202: "Accepted", + 203: "Non-Authoritative Information", + 204: "No Content", + 205: "Reset Content", + 206: "Partial Content", + 207: "Multi-Status", + 208: "Already Reported", + 226: "IM Used", + 300: "Multiple Choices", + 301: "Moved Permanently", + 302: "Found", + 303: "See Other", + 304: "Not Modified", + 305: "Use Proxy", + 307: "Temporary Redirect", + 308: "Permanent Redirect", + 400: "Bad Request", + 401: "Unauthorized", + 402: "Payment Required", + 403: "Forbidden", + 404: "Not Found", + 405: "Method Not Allowed", + 406: "Not Acceptable", + 407: "Proxy Authentication Required", + 408: "Request Timeout", + 409: "Conflict", + 410: "Gone", + 411: "Length Required", + 412: "Precondition Failed", + 413: "Payload Too Large", + 414: "URI Too Long", + 415: "Unsupported Media Type", + 416: "Range Not Satisfiable", + 417: "Expectation Failed", + 418: "I'm a Teapot", + 421: "Misdirected Request", + 422: "Unprocessable Entity", + 423: "Locked", + 424: "Failed Dependency", + 425: "Too Early", + 426: "Upgrade Required", + 428: "Precondition Required", + 429: "Too Many Requests", + 431: "Request Header Fields Too Large", + 451: "Unavailable For Legal Reasons", + 500: "Internal Server Error", + 501: "Not Implemented", + 502: "Bad Gateway", + 503: "Service Unavailable", + 504: "Gateway Timeout", + 505: "HTTP Version Not Supported", + 506: "Variant Also Negotiates", + 507: "Insufficient Storage", + 508: "Loop Detected", + 509: "Bandwidth Limit Exceeded", + 510: "Not Extended", + 511: "Network Authentication Required" +}; +export const maxHeaderSize = 16384; diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/http/request.d.mts b/worker/node_modules/unenv/dist/runtime/node/internal/http/request.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..d3cfc642d3fe8b2c3c685c37d94beb569a95d3c5 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/http/request.d.mts @@ -0,0 +1,29 @@ +import type NodeHttp from "node:http"; +import { Socket } from "node:net"; +import { Readable } from "node:stream"; +export declare class IncomingMessage extends Readable implements NodeHttp.IncomingMessage { + __unenv__: {}; + aborted: boolean; + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + complete: boolean; + connection: Socket; + socket: Socket; + headers: NodeHttp.IncomingHttpHeaders; + trailers: {}; + method: string; + url: string; + statusCode: number; + statusMessage: string; + closed: boolean; + errored: Error | null; + readable: boolean; + constructor(socket?: Socket); + get rawHeaders(); + get rawTrailers(): unknown; + setTimeout(_msecs: number, _callback?: () => void); + get headersDistinct(); + get trailersDistinct(); + _read(); +} diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/http/request.mjs b/worker/node_modules/unenv/dist/runtime/node/internal/http/request.mjs new file mode 100644 index 0000000000000000000000000000000000000000..dba90203e43b2eeb7f86c75e6033ad77e7535787 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/http/request.mjs @@ -0,0 +1,51 @@ +import { Socket } from "node:net"; +import { Readable } from "node:stream"; +import { rawHeaders } from "../../../_internal/utils.mjs"; +export class IncomingMessage extends Readable { + __unenv__ = {}; + aborted = false; + httpVersion = "1.1"; + httpVersionMajor = 1; + httpVersionMinor = 1; + complete = true; + connection; + socket; + headers = {}; + trailers = {}; + method = "GET"; + url = "/"; + statusCode = 200; + statusMessage = ""; + closed = false; + errored = null; + readable = false; + constructor(socket) { + super(); + this.socket = this.connection = socket || new Socket(); + } + get rawHeaders() { + return rawHeaders(this.headers); + } + get rawTrailers() { + return []; + } + setTimeout(_msecs, _callback) { + return this; + } + get headersDistinct() { + return _distinct(this.headers); + } + get trailersDistinct() { + return _distinct(this.trailers); + } + _read() {} +} +function _distinct(obj) { + const d = {}; + for (const [key, value] of Object.entries(obj)) { + if (key) { + d[key] = (Array.isArray(value) ? value : [value]).filter(Boolean); + } + } + return d; +} diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/http/response.d.mts b/worker/node_modules/unenv/dist/runtime/node/internal/http/response.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..ebed2077fe174fe21efef07b3cfe8625e6f09aa2 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/http/response.d.mts @@ -0,0 +1,40 @@ +import type nodeHttp from "node:http"; +import type { Socket } from "node:net"; +import type { Callback } from "../../../_internal/types.mjs"; +import { Writable } from "node:stream"; +export declare class ServerResponse extends Writable implements nodeHttp.ServerResponse { + readonly __unenv__: true; + statusCode: number; + statusMessage: string; + upgrading: boolean; + chunkedEncoding: boolean; + shouldKeepAlive: boolean; + useChunkedEncodingByDefault: boolean; + sendDate: boolean; + finished: boolean; + headersSent: boolean; + strictContentLength: boolean; + connection: Socket | null; + socket: Socket | null; + req: nodeHttp.IncomingMessage; + _headers: Record; + constructor(req: nodeHttp.IncomingMessage); + assignSocket(socket: Socket): void; + _flush(); + detachSocket(_socket: Socket): void; + writeContinue(_callback?: Callback): void; + writeHead(statusCode: number, arg1?: string | nodeHttp.OutgoingHttpHeaders | nodeHttp.OutgoingHttpHeader[], arg2?: nodeHttp.OutgoingHttpHeaders | nodeHttp.OutgoingHttpHeader[]); + writeProcessing(): void; + setTimeout(_msecs: number, _callback?: Callback): this; + appendHeader(name: string, value: string | string[]); + setHeader(name: string, value: number | string | readonly string[]): this; + setHeaders(headers: Headers | Map): this; + getHeader(name: string): number | string | string[] | undefined; + getHeaders(): nodeHttp.OutgoingHttpHeaders; + getHeaderNames(): string[]; + hasHeader(name: string): boolean; + removeHeader(name: string): void; + addTrailers(_headers: nodeHttp.OutgoingHttpHeaders | ReadonlyArray<[string, string]>): void; + flushHeaders(): void; + writeEarlyHints(_headers: nodeHttp.OutgoingHttpHeaders, cb: () => void): void; +} diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/http/response.mjs b/worker/node_modules/unenv/dist/runtime/node/internal/http/response.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d54e1c830b22d00ccb1d51910de348486720149d --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/http/response.mjs @@ -0,0 +1,96 @@ +import { Writable } from "node:stream"; +export class ServerResponse extends Writable { + __unenv__ = true; + statusCode = 200; + statusMessage = ""; + upgrading = false; + chunkedEncoding = false; + shouldKeepAlive = false; + useChunkedEncodingByDefault = false; + sendDate = false; + finished = false; + headersSent = false; + strictContentLength = false; + connection = null; + socket = null; + req; + _headers = {}; + constructor(req) { + super(); + this.req = req; + } + assignSocket(socket) { + socket._httpMessage = this; + this.socket = socket; + this.connection = socket; + this.emit("socket", socket); + this._flush(); + } + _flush() { + this.flushHeaders(); + } + detachSocket(_socket) {} + writeContinue(_callback) {} + writeHead(statusCode, arg1, arg2) { + if (statusCode) { + this.statusCode = statusCode; + } + if (typeof arg1 === "string") { + this.statusMessage = arg1; + arg1 = undefined; + } + const headers = arg2 || arg1; + if (headers) { + if (Array.isArray(headers)) {} else { + for (const key in headers) { + this.setHeader(key, headers[key]); + } + } + } + this.headersSent = true; + return this; + } + writeProcessing() {} + setTimeout(_msecs, _callback) { + return this; + } + appendHeader(name, value) { + name = name.toLowerCase(); + const current = this._headers[name]; + const all = [...Array.isArray(current) ? current : [current], ...Array.isArray(value) ? value : [value]].filter(Boolean); + this._headers[name] = all.length > 1 ? all : all[0]; + return this; + } + setHeader(name, value) { + this._headers[name.toLowerCase()] = Array.isArray(value) ? [...value] : value; + return this; + } + setHeaders(headers) { + for (const [key, value] of headers.entries()) { + this.setHeader(key, value); + } + return this; + } + getHeader(name) { + return this._headers[name.toLowerCase()]; + } + getHeaders() { + return this._headers; + } + getHeaderNames() { + return Object.keys(this._headers); + } + hasHeader(name) { + return name.toLowerCase() in this._headers; + } + removeHeader(name) { + delete this._headers[name.toLowerCase()]; + } + addTrailers(_headers) {} + flushHeaders() {} + writeEarlyHints(_headers, cb) { + if (typeof cb === "function") { + cb(); + } + } +} diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/http2/constants.d.mts b/worker/node_modules/unenv/dist/runtime/node/internal/http2/constants.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..a5f076e15e7cfdd52201bdaa997112fef3ccc4aa --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/http2/constants.d.mts @@ -0,0 +1,240 @@ +export declare const NGHTTP2_ERR_FRAME_SIZE_ERROR = -522; +export declare const NGHTTP2_SESSION_SERVER = 0; +export declare const NGHTTP2_SESSION_CLIENT = 1; +export declare const NGHTTP2_STREAM_STATE_IDLE = 1; +export declare const NGHTTP2_STREAM_STATE_OPEN = 2; +export declare const NGHTTP2_STREAM_STATE_RESERVED_LOCAL = 3; +export declare const NGHTTP2_STREAM_STATE_RESERVED_REMOTE = 4; +export declare const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL = 5; +export declare const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE = 6; +export declare const NGHTTP2_STREAM_STATE_CLOSED = 7; +export declare const NGHTTP2_FLAG_NONE = 0; +export declare const NGHTTP2_FLAG_END_STREAM = 1; +export declare const NGHTTP2_FLAG_END_HEADERS = 4; +export declare const NGHTTP2_FLAG_ACK = 1; +export declare const NGHTTP2_FLAG_PADDED = 8; +export declare const NGHTTP2_FLAG_PRIORITY = 32; +export declare const DEFAULT_SETTINGS_HEADER_TABLE_SIZE = 4096; +export declare const DEFAULT_SETTINGS_ENABLE_PUSH = 1; +export declare const DEFAULT_SETTINGS_MAX_CONCURRENT_STREAMS = 4294967295; +export declare const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE = 65535; +export declare const DEFAULT_SETTINGS_MAX_FRAME_SIZE = 16384; +export declare const DEFAULT_SETTINGS_MAX_HEADER_LIST_SIZE = 65535; +export declare const DEFAULT_SETTINGS_ENABLE_CONNECT_PROTOCOL = 0; +export declare const MAX_MAX_FRAME_SIZE = 16777215; +export declare const MIN_MAX_FRAME_SIZE = 16384; +export declare const MAX_INITIAL_WINDOW_SIZE = 2147483647; +export declare const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE = 1; +export declare const NGHTTP2_SETTINGS_ENABLE_PUSH = 2; +export declare const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS = 3; +export declare const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE = 4; +export declare const NGHTTP2_SETTINGS_MAX_FRAME_SIZE = 5; +export declare const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE = 6; +export declare const NGHTTP2_SETTINGS_ENABLE_CONNECT_PROTOCOL = 8; +export declare const PADDING_STRATEGY_NONE = 0; +export declare const PADDING_STRATEGY_ALIGNED = 1; +export declare const PADDING_STRATEGY_MAX = 2; +export declare const PADDING_STRATEGY_CALLBACK = 1; +export declare const NGHTTP2_NO_ERROR = 0; +export declare const NGHTTP2_PROTOCOL_ERROR = 1; +export declare const NGHTTP2_INTERNAL_ERROR = 2; +export declare const NGHTTP2_FLOW_CONTROL_ERROR = 3; +export declare const NGHTTP2_SETTINGS_TIMEOUT = 4; +export declare const NGHTTP2_STREAM_CLOSED = 5; +export declare const NGHTTP2_FRAME_SIZE_ERROR = 6; +export declare const NGHTTP2_REFUSED_STREAM = 7; +export declare const NGHTTP2_CANCEL = 8; +export declare const NGHTTP2_COMPRESSION_ERROR = 9; +export declare const NGHTTP2_CONNECT_ERROR = 10; +export declare const NGHTTP2_ENHANCE_YOUR_CALM = 11; +export declare const NGHTTP2_INADEQUATE_SECURITY = 12; +export declare const NGHTTP2_HTTP_1_1_REQUIRED = 13; +export declare const NGHTTP2_DEFAULT_WEIGHT = 16; +export declare const HTTP2_HEADER_STATUS = ":status"; +export declare const HTTP2_HEADER_METHOD = ":method"; +export declare const HTTP2_HEADER_AUTHORITY = ":authority"; +export declare const HTTP2_HEADER_SCHEME = ":scheme"; +export declare const HTTP2_HEADER_PATH = ":path"; +export declare const HTTP2_HEADER_PROTOCOL = ":protocol"; +export declare const HTTP2_HEADER_ACCEPT_ENCODING = "accept-encoding"; +export declare const HTTP2_HEADER_ACCEPT_LANGUAGE = "accept-language"; +export declare const HTTP2_HEADER_ACCEPT_RANGES = "accept-ranges"; +export declare const HTTP2_HEADER_ACCEPT = "accept"; +export declare const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS = "access-control-allow-credentials"; +export declare const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_HEADERS = "access-control-allow-headers"; +export declare const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_METHODS = "access-control-allow-methods"; +export declare const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN = "access-control-allow-origin"; +export declare const HTTP2_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS = "access-control-expose-headers"; +export declare const HTTP2_HEADER_ACCESS_CONTROL_REQUEST_HEADERS = "access-control-request-headers"; +export declare const HTTP2_HEADER_ACCESS_CONTROL_REQUEST_METHOD = "access-control-request-method"; +export declare const HTTP2_HEADER_AGE = "age"; +export declare const HTTP2_HEADER_AUTHORIZATION = "authorization"; +export declare const HTTP2_HEADER_CACHE_CONTROL = "cache-control"; +export declare const HTTP2_HEADER_CONNECTION = "connection"; +export declare const HTTP2_HEADER_CONTENT_DISPOSITION = "content-disposition"; +export declare const HTTP2_HEADER_CONTENT_ENCODING = "content-encoding"; +export declare const HTTP2_HEADER_CONTENT_LENGTH = "content-length"; +export declare const HTTP2_HEADER_CONTENT_TYPE = "content-type"; +export declare const HTTP2_HEADER_COOKIE = "cookie"; +export declare const HTTP2_HEADER_DATE = "date"; +export declare const HTTP2_HEADER_ETAG = "etag"; +export declare const HTTP2_HEADER_FORWARDED = "forwarded"; +export declare const HTTP2_HEADER_HOST = "host"; +export declare const HTTP2_HEADER_IF_MODIFIED_SINCE = "if-modified-since"; +export declare const HTTP2_HEADER_IF_NONE_MATCH = "if-none-match"; +export declare const HTTP2_HEADER_IF_RANGE = "if-range"; +export declare const HTTP2_HEADER_LAST_MODIFIED = "last-modified"; +export declare const HTTP2_HEADER_LINK = "link"; +export declare const HTTP2_HEADER_LOCATION = "location"; +export declare const HTTP2_HEADER_RANGE = "range"; +export declare const HTTP2_HEADER_REFERER = "referer"; +export declare const HTTP2_HEADER_SERVER = "server"; +export declare const HTTP2_HEADER_SET_COOKIE = "set-cookie"; +export declare const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY = "strict-transport-security"; +export declare const HTTP2_HEADER_TRANSFER_ENCODING = "transfer-encoding"; +export declare const HTTP2_HEADER_TE = "te"; +export declare const HTTP2_HEADER_UPGRADE_INSECURE_REQUESTS = "upgrade-insecure-requests"; +export declare const HTTP2_HEADER_UPGRADE = "upgrade"; +export declare const HTTP2_HEADER_USER_AGENT = "user-agent"; +export declare const HTTP2_HEADER_VARY = "vary"; +export declare const HTTP2_HEADER_X_CONTENT_TYPE_OPTIONS = "x-content-type-options"; +export declare const HTTP2_HEADER_X_FRAME_OPTIONS = "x-frame-options"; +export declare const HTTP2_HEADER_KEEP_ALIVE = "keep-alive"; +export declare const HTTP2_HEADER_PROXY_CONNECTION = "proxy-connection"; +export declare const HTTP2_HEADER_X_XSS_PROTECTION = "x-xss-protection"; +export declare const HTTP2_HEADER_ALT_SVC = "alt-svc"; +export declare const HTTP2_HEADER_CONTENT_SECURITY_POLICY = "content-security-policy"; +export declare const HTTP2_HEADER_EARLY_DATA = "early-data"; +export declare const HTTP2_HEADER_EXPECT_CT = "expect-ct"; +export declare const HTTP2_HEADER_ORIGIN = "origin"; +export declare const HTTP2_HEADER_PURPOSE = "purpose"; +export declare const HTTP2_HEADER_TIMING_ALLOW_ORIGIN = "timing-allow-origin"; +export declare const HTTP2_HEADER_X_FORWARDED_FOR = "x-forwarded-for"; +export declare const HTTP2_HEADER_PRIORITY = "priority"; +export declare const HTTP2_HEADER_ACCEPT_CHARSET = "accept-charset"; +export declare const HTTP2_HEADER_ACCESS_CONTROL_MAX_AGE = "access-control-max-age"; +export declare const HTTP2_HEADER_ALLOW = "allow"; +export declare const HTTP2_HEADER_CONTENT_LANGUAGE = "content-language"; +export declare const HTTP2_HEADER_CONTENT_LOCATION = "content-location"; +export declare const HTTP2_HEADER_CONTENT_MD5 = "content-md5"; +export declare const HTTP2_HEADER_CONTENT_RANGE = "content-range"; +export declare const HTTP2_HEADER_DNT = "dnt"; +export declare const HTTP2_HEADER_EXPECT = "expect"; +export declare const HTTP2_HEADER_EXPIRES = "expires"; +export declare const HTTP2_HEADER_FROM = "from"; +export declare const HTTP2_HEADER_IF_MATCH = "if-match"; +export declare const HTTP2_HEADER_IF_UNMODIFIED_SINCE = "if-unmodified-since"; +export declare const HTTP2_HEADER_MAX_FORWARDS = "max-forwards"; +export declare const HTTP2_HEADER_PREFER = "prefer"; +export declare const HTTP2_HEADER_PROXY_AUTHENTICATE = "proxy-authenticate"; +export declare const HTTP2_HEADER_PROXY_AUTHORIZATION = "proxy-authorization"; +export declare const HTTP2_HEADER_REFRESH = "refresh"; +export declare const HTTP2_HEADER_RETRY_AFTER = "retry-after"; +export declare const HTTP2_HEADER_TRAILER = "trailer"; +export declare const HTTP2_HEADER_TK = "tk"; +export declare const HTTP2_HEADER_VIA = "via"; +export declare const HTTP2_HEADER_WARNING = "warning"; +export declare const HTTP2_HEADER_WWW_AUTHENTICATE = "www-authenticate"; +export declare const HTTP2_HEADER_HTTP2_SETTINGS = "http2-settings"; +export declare const HTTP2_METHOD_ACL = "ACL"; +export declare const HTTP2_METHOD_BASELINE_CONTROL = "BASELINE-CONTROL"; +export declare const HTTP2_METHOD_BIND = "BIND"; +export declare const HTTP2_METHOD_CHECKIN = "CHECKIN"; +export declare const HTTP2_METHOD_CHECKOUT = "CHECKOUT"; +export declare const HTTP2_METHOD_CONNECT = "CONNECT"; +export declare const HTTP2_METHOD_COPY = "COPY"; +export declare const HTTP2_METHOD_DELETE = "DELETE"; +export declare const HTTP2_METHOD_GET = "GET"; +export declare const HTTP2_METHOD_HEAD = "HEAD"; +export declare const HTTP2_METHOD_LABEL = "LABEL"; +export declare const HTTP2_METHOD_LINK = "LINK"; +export declare const HTTP2_METHOD_LOCK = "LOCK"; +export declare const HTTP2_METHOD_MERGE = "MERGE"; +export declare const HTTP2_METHOD_MKACTIVITY = "MKACTIVITY"; +export declare const HTTP2_METHOD_MKCALENDAR = "MKCALENDAR"; +export declare const HTTP2_METHOD_MKCOL = "MKCOL"; +export declare const HTTP2_METHOD_MKREDIRECTREF = "MKREDIRECTREF"; +export declare const HTTP2_METHOD_MKWORKSPACE = "MKWORKSPACE"; +export declare const HTTP2_METHOD_MOVE = "MOVE"; +export declare const HTTP2_METHOD_OPTIONS = "OPTIONS"; +export declare const HTTP2_METHOD_ORDERPATCH = "ORDERPATCH"; +export declare const HTTP2_METHOD_PATCH = "PATCH"; +export declare const HTTP2_METHOD_POST = "POST"; +export declare const HTTP2_METHOD_PRI = "PRI"; +export declare const HTTP2_METHOD_PROPFIND = "PROPFIND"; +export declare const HTTP2_METHOD_PROPPATCH = "PROPPATCH"; +export declare const HTTP2_METHOD_PUT = "PUT"; +export declare const HTTP2_METHOD_REBIND = "REBIND"; +export declare const HTTP2_METHOD_REPORT = "REPORT"; +export declare const HTTP2_METHOD_SEARCH = "SEARCH"; +export declare const HTTP2_METHOD_TRACE = "TRACE"; +export declare const HTTP2_METHOD_UNBIND = "UNBIND"; +export declare const HTTP2_METHOD_UNCHECKOUT = "UNCHECKOUT"; +export declare const HTTP2_METHOD_UNLINK = "UNLINK"; +export declare const HTTP2_METHOD_UNLOCK = "UNLOCK"; +export declare const HTTP2_METHOD_UPDATE = "UPDATE"; +export declare const HTTP2_METHOD_UPDATEREDIRECTREF = "UPDATEREDIRECTREF"; +export declare const HTTP2_METHOD_VERSION_CONTROL = "VERSION-CONTROL"; +export declare const HTTP_STATUS_CONTINUE = 100; +export declare const HTTP_STATUS_SWITCHING_PROTOCOLS = 101; +export declare const HTTP_STATUS_PROCESSING = 102; +export declare const HTTP_STATUS_EARLY_HINTS = 103; +export declare const HTTP_STATUS_OK = 200; +export declare const HTTP_STATUS_CREATED = 201; +export declare const HTTP_STATUS_ACCEPTED = 202; +export declare const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION = 203; +export declare const HTTP_STATUS_NO_CONTENT = 204; +export declare const HTTP_STATUS_RESET_CONTENT = 205; +export declare const HTTP_STATUS_PARTIAL_CONTENT = 206; +export declare const HTTP_STATUS_MULTI_STATUS = 207; +export declare const HTTP_STATUS_ALREADY_REPORTED = 208; +export declare const HTTP_STATUS_IM_USED = 226; +export declare const HTTP_STATUS_MULTIPLE_CHOICES = 300; +export declare const HTTP_STATUS_MOVED_PERMANENTLY = 301; +export declare const HTTP_STATUS_FOUND = 302; +export declare const HTTP_STATUS_SEE_OTHER = 303; +export declare const HTTP_STATUS_NOT_MODIFIED = 304; +export declare const HTTP_STATUS_USE_PROXY = 305; +export declare const HTTP_STATUS_TEMPORARY_REDIRECT = 307; +export declare const HTTP_STATUS_PERMANENT_REDIRECT = 308; +export declare const HTTP_STATUS_BAD_REQUEST = 400; +export declare const HTTP_STATUS_UNAUTHORIZED = 401; +export declare const HTTP_STATUS_PAYMENT_REQUIRED = 402; +export declare const HTTP_STATUS_FORBIDDEN = 403; +export declare const HTTP_STATUS_NOT_FOUND = 404; +export declare const HTTP_STATUS_METHOD_NOT_ALLOWED = 405; +export declare const HTTP_STATUS_NOT_ACCEPTABLE = 406; +export declare const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED = 407; +export declare const HTTP_STATUS_REQUEST_TIMEOUT = 408; +export declare const HTTP_STATUS_CONFLICT = 409; +export declare const HTTP_STATUS_GONE = 410; +export declare const HTTP_STATUS_LENGTH_REQUIRED = 411; +export declare const HTTP_STATUS_PRECONDITION_FAILED = 412; +export declare const HTTP_STATUS_PAYLOAD_TOO_LARGE = 413; +export declare const HTTP_STATUS_URI_TOO_LONG = 414; +export declare const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE = 415; +export declare const HTTP_STATUS_RANGE_NOT_SATISFIABLE = 416; +export declare const HTTP_STATUS_EXPECTATION_FAILED = 417; +export declare const HTTP_STATUS_TEAPOT = 418; +export declare const HTTP_STATUS_MISDIRECTED_REQUEST = 421; +export declare const HTTP_STATUS_UNPROCESSABLE_ENTITY = 422; +export declare const HTTP_STATUS_LOCKED = 423; +export declare const HTTP_STATUS_FAILED_DEPENDENCY = 424; +export declare const HTTP_STATUS_TOO_EARLY = 425; +export declare const HTTP_STATUS_UPGRADE_REQUIRED = 426; +export declare const HTTP_STATUS_PRECONDITION_REQUIRED = 428; +export declare const HTTP_STATUS_TOO_MANY_REQUESTS = 429; +export declare const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE = 431; +export declare const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS = 451; +export declare const HTTP_STATUS_INTERNAL_SERVER_ERROR = 500; +export declare const HTTP_STATUS_NOT_IMPLEMENTED = 501; +export declare const HTTP_STATUS_BAD_GATEWAY = 502; +export declare const HTTP_STATUS_SERVICE_UNAVAILABLE = 503; +export declare const HTTP_STATUS_GATEWAY_TIMEOUT = 504; +export declare const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED = 505; +export declare const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES = 506; +export declare const HTTP_STATUS_INSUFFICIENT_STORAGE = 507; +export declare const HTTP_STATUS_LOOP_DETECTED = 508; +export declare const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED = 509; +export declare const HTTP_STATUS_NOT_EXTENDED = 510; +export declare const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED = 511; diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/http2/constants.mjs b/worker/node_modules/unenv/dist/runtime/node/internal/http2/constants.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1783b28bd12563be2e47f28d368cbc465161aaf6 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/http2/constants.mjs @@ -0,0 +1,240 @@ +export const NGHTTP2_ERR_FRAME_SIZE_ERROR = -522; +export const NGHTTP2_SESSION_SERVER = 0; +export const NGHTTP2_SESSION_CLIENT = 1; +export const NGHTTP2_STREAM_STATE_IDLE = 1; +export const NGHTTP2_STREAM_STATE_OPEN = 2; +export const NGHTTP2_STREAM_STATE_RESERVED_LOCAL = 3; +export const NGHTTP2_STREAM_STATE_RESERVED_REMOTE = 4; +export const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL = 5; +export const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE = 6; +export const NGHTTP2_STREAM_STATE_CLOSED = 7; +export const NGHTTP2_FLAG_NONE = 0; +export const NGHTTP2_FLAG_END_STREAM = 1; +export const NGHTTP2_FLAG_END_HEADERS = 4; +export const NGHTTP2_FLAG_ACK = 1; +export const NGHTTP2_FLAG_PADDED = 8; +export const NGHTTP2_FLAG_PRIORITY = 32; +export const DEFAULT_SETTINGS_HEADER_TABLE_SIZE = 4096; +export const DEFAULT_SETTINGS_ENABLE_PUSH = 1; +export const DEFAULT_SETTINGS_MAX_CONCURRENT_STREAMS = 4294967295; +export const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE = 65535; +export const DEFAULT_SETTINGS_MAX_FRAME_SIZE = 16384; +export const DEFAULT_SETTINGS_MAX_HEADER_LIST_SIZE = 65535; +export const DEFAULT_SETTINGS_ENABLE_CONNECT_PROTOCOL = 0; +export const MAX_MAX_FRAME_SIZE = 16777215; +export const MIN_MAX_FRAME_SIZE = 16384; +export const MAX_INITIAL_WINDOW_SIZE = 2147483647; +export const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE = 1; +export const NGHTTP2_SETTINGS_ENABLE_PUSH = 2; +export const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS = 3; +export const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE = 4; +export const NGHTTP2_SETTINGS_MAX_FRAME_SIZE = 5; +export const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE = 6; +export const NGHTTP2_SETTINGS_ENABLE_CONNECT_PROTOCOL = 8; +export const PADDING_STRATEGY_NONE = 0; +export const PADDING_STRATEGY_ALIGNED = 1; +export const PADDING_STRATEGY_MAX = 2; +export const PADDING_STRATEGY_CALLBACK = 1; +export const NGHTTP2_NO_ERROR = 0; +export const NGHTTP2_PROTOCOL_ERROR = 1; +export const NGHTTP2_INTERNAL_ERROR = 2; +export const NGHTTP2_FLOW_CONTROL_ERROR = 3; +export const NGHTTP2_SETTINGS_TIMEOUT = 4; +export const NGHTTP2_STREAM_CLOSED = 5; +export const NGHTTP2_FRAME_SIZE_ERROR = 6; +export const NGHTTP2_REFUSED_STREAM = 7; +export const NGHTTP2_CANCEL = 8; +export const NGHTTP2_COMPRESSION_ERROR = 9; +export const NGHTTP2_CONNECT_ERROR = 10; +export const NGHTTP2_ENHANCE_YOUR_CALM = 11; +export const NGHTTP2_INADEQUATE_SECURITY = 12; +export const NGHTTP2_HTTP_1_1_REQUIRED = 13; +export const NGHTTP2_DEFAULT_WEIGHT = 16; +export const HTTP2_HEADER_STATUS = ":status"; +export const HTTP2_HEADER_METHOD = ":method"; +export const HTTP2_HEADER_AUTHORITY = ":authority"; +export const HTTP2_HEADER_SCHEME = ":scheme"; +export const HTTP2_HEADER_PATH = ":path"; +export const HTTP2_HEADER_PROTOCOL = ":protocol"; +export const HTTP2_HEADER_ACCEPT_ENCODING = "accept-encoding"; +export const HTTP2_HEADER_ACCEPT_LANGUAGE = "accept-language"; +export const HTTP2_HEADER_ACCEPT_RANGES = "accept-ranges"; +export const HTTP2_HEADER_ACCEPT = "accept"; +export const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS = "access-control-allow-credentials"; +export const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_HEADERS = "access-control-allow-headers"; +export const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_METHODS = "access-control-allow-methods"; +export const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN = "access-control-allow-origin"; +export const HTTP2_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS = "access-control-expose-headers"; +export const HTTP2_HEADER_ACCESS_CONTROL_REQUEST_HEADERS = "access-control-request-headers"; +export const HTTP2_HEADER_ACCESS_CONTROL_REQUEST_METHOD = "access-control-request-method"; +export const HTTP2_HEADER_AGE = "age"; +export const HTTP2_HEADER_AUTHORIZATION = "authorization"; +export const HTTP2_HEADER_CACHE_CONTROL = "cache-control"; +export const HTTP2_HEADER_CONNECTION = "connection"; +export const HTTP2_HEADER_CONTENT_DISPOSITION = "content-disposition"; +export const HTTP2_HEADER_CONTENT_ENCODING = "content-encoding"; +export const HTTP2_HEADER_CONTENT_LENGTH = "content-length"; +export const HTTP2_HEADER_CONTENT_TYPE = "content-type"; +export const HTTP2_HEADER_COOKIE = "cookie"; +export const HTTP2_HEADER_DATE = "date"; +export const HTTP2_HEADER_ETAG = "etag"; +export const HTTP2_HEADER_FORWARDED = "forwarded"; +export const HTTP2_HEADER_HOST = "host"; +export const HTTP2_HEADER_IF_MODIFIED_SINCE = "if-modified-since"; +export const HTTP2_HEADER_IF_NONE_MATCH = "if-none-match"; +export const HTTP2_HEADER_IF_RANGE = "if-range"; +export const HTTP2_HEADER_LAST_MODIFIED = "last-modified"; +export const HTTP2_HEADER_LINK = "link"; +export const HTTP2_HEADER_LOCATION = "location"; +export const HTTP2_HEADER_RANGE = "range"; +export const HTTP2_HEADER_REFERER = "referer"; +export const HTTP2_HEADER_SERVER = "server"; +export const HTTP2_HEADER_SET_COOKIE = "set-cookie"; +export const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY = "strict-transport-security"; +export const HTTP2_HEADER_TRANSFER_ENCODING = "transfer-encoding"; +export const HTTP2_HEADER_TE = "te"; +export const HTTP2_HEADER_UPGRADE_INSECURE_REQUESTS = "upgrade-insecure-requests"; +export const HTTP2_HEADER_UPGRADE = "upgrade"; +export const HTTP2_HEADER_USER_AGENT = "user-agent"; +export const HTTP2_HEADER_VARY = "vary"; +export const HTTP2_HEADER_X_CONTENT_TYPE_OPTIONS = "x-content-type-options"; +export const HTTP2_HEADER_X_FRAME_OPTIONS = "x-frame-options"; +export const HTTP2_HEADER_KEEP_ALIVE = "keep-alive"; +export const HTTP2_HEADER_PROXY_CONNECTION = "proxy-connection"; +export const HTTP2_HEADER_X_XSS_PROTECTION = "x-xss-protection"; +export const HTTP2_HEADER_ALT_SVC = "alt-svc"; +export const HTTP2_HEADER_CONTENT_SECURITY_POLICY = "content-security-policy"; +export const HTTP2_HEADER_EARLY_DATA = "early-data"; +export const HTTP2_HEADER_EXPECT_CT = "expect-ct"; +export const HTTP2_HEADER_ORIGIN = "origin"; +export const HTTP2_HEADER_PURPOSE = "purpose"; +export const HTTP2_HEADER_TIMING_ALLOW_ORIGIN = "timing-allow-origin"; +export const HTTP2_HEADER_X_FORWARDED_FOR = "x-forwarded-for"; +export const HTTP2_HEADER_PRIORITY = "priority"; +export const HTTP2_HEADER_ACCEPT_CHARSET = "accept-charset"; +export const HTTP2_HEADER_ACCESS_CONTROL_MAX_AGE = "access-control-max-age"; +export const HTTP2_HEADER_ALLOW = "allow"; +export const HTTP2_HEADER_CONTENT_LANGUAGE = "content-language"; +export const HTTP2_HEADER_CONTENT_LOCATION = "content-location"; +export const HTTP2_HEADER_CONTENT_MD5 = "content-md5"; +export const HTTP2_HEADER_CONTENT_RANGE = "content-range"; +export const HTTP2_HEADER_DNT = "dnt"; +export const HTTP2_HEADER_EXPECT = "expect"; +export const HTTP2_HEADER_EXPIRES = "expires"; +export const HTTP2_HEADER_FROM = "from"; +export const HTTP2_HEADER_IF_MATCH = "if-match"; +export const HTTP2_HEADER_IF_UNMODIFIED_SINCE = "if-unmodified-since"; +export const HTTP2_HEADER_MAX_FORWARDS = "max-forwards"; +export const HTTP2_HEADER_PREFER = "prefer"; +export const HTTP2_HEADER_PROXY_AUTHENTICATE = "proxy-authenticate"; +export const HTTP2_HEADER_PROXY_AUTHORIZATION = "proxy-authorization"; +export const HTTP2_HEADER_REFRESH = "refresh"; +export const HTTP2_HEADER_RETRY_AFTER = "retry-after"; +export const HTTP2_HEADER_TRAILER = "trailer"; +export const HTTP2_HEADER_TK = "tk"; +export const HTTP2_HEADER_VIA = "via"; +export const HTTP2_HEADER_WARNING = "warning"; +export const HTTP2_HEADER_WWW_AUTHENTICATE = "www-authenticate"; +export const HTTP2_HEADER_HTTP2_SETTINGS = "http2-settings"; +export const HTTP2_METHOD_ACL = "ACL"; +export const HTTP2_METHOD_BASELINE_CONTROL = "BASELINE-CONTROL"; +export const HTTP2_METHOD_BIND = "BIND"; +export const HTTP2_METHOD_CHECKIN = "CHECKIN"; +export const HTTP2_METHOD_CHECKOUT = "CHECKOUT"; +export const HTTP2_METHOD_CONNECT = "CONNECT"; +export const HTTP2_METHOD_COPY = "COPY"; +export const HTTP2_METHOD_DELETE = "DELETE"; +export const HTTP2_METHOD_GET = "GET"; +export const HTTP2_METHOD_HEAD = "HEAD"; +export const HTTP2_METHOD_LABEL = "LABEL"; +export const HTTP2_METHOD_LINK = "LINK"; +export const HTTP2_METHOD_LOCK = "LOCK"; +export const HTTP2_METHOD_MERGE = "MERGE"; +export const HTTP2_METHOD_MKACTIVITY = "MKACTIVITY"; +export const HTTP2_METHOD_MKCALENDAR = "MKCALENDAR"; +export const HTTP2_METHOD_MKCOL = "MKCOL"; +export const HTTP2_METHOD_MKREDIRECTREF = "MKREDIRECTREF"; +export const HTTP2_METHOD_MKWORKSPACE = "MKWORKSPACE"; +export const HTTP2_METHOD_MOVE = "MOVE"; +export const HTTP2_METHOD_OPTIONS = "OPTIONS"; +export const HTTP2_METHOD_ORDERPATCH = "ORDERPATCH"; +export const HTTP2_METHOD_PATCH = "PATCH"; +export const HTTP2_METHOD_POST = "POST"; +export const HTTP2_METHOD_PRI = "PRI"; +export const HTTP2_METHOD_PROPFIND = "PROPFIND"; +export const HTTP2_METHOD_PROPPATCH = "PROPPATCH"; +export const HTTP2_METHOD_PUT = "PUT"; +export const HTTP2_METHOD_REBIND = "REBIND"; +export const HTTP2_METHOD_REPORT = "REPORT"; +export const HTTP2_METHOD_SEARCH = "SEARCH"; +export const HTTP2_METHOD_TRACE = "TRACE"; +export const HTTP2_METHOD_UNBIND = "UNBIND"; +export const HTTP2_METHOD_UNCHECKOUT = "UNCHECKOUT"; +export const HTTP2_METHOD_UNLINK = "UNLINK"; +export const HTTP2_METHOD_UNLOCK = "UNLOCK"; +export const HTTP2_METHOD_UPDATE = "UPDATE"; +export const HTTP2_METHOD_UPDATEREDIRECTREF = "UPDATEREDIRECTREF"; +export const HTTP2_METHOD_VERSION_CONTROL = "VERSION-CONTROL"; +export const HTTP_STATUS_CONTINUE = 100; +export const HTTP_STATUS_SWITCHING_PROTOCOLS = 101; +export const HTTP_STATUS_PROCESSING = 102; +export const HTTP_STATUS_EARLY_HINTS = 103; +export const HTTP_STATUS_OK = 200; +export const HTTP_STATUS_CREATED = 201; +export const HTTP_STATUS_ACCEPTED = 202; +export const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION = 203; +export const HTTP_STATUS_NO_CONTENT = 204; +export const HTTP_STATUS_RESET_CONTENT = 205; +export const HTTP_STATUS_PARTIAL_CONTENT = 206; +export const HTTP_STATUS_MULTI_STATUS = 207; +export const HTTP_STATUS_ALREADY_REPORTED = 208; +export const HTTP_STATUS_IM_USED = 226; +export const HTTP_STATUS_MULTIPLE_CHOICES = 300; +export const HTTP_STATUS_MOVED_PERMANENTLY = 301; +export const HTTP_STATUS_FOUND = 302; +export const HTTP_STATUS_SEE_OTHER = 303; +export const HTTP_STATUS_NOT_MODIFIED = 304; +export const HTTP_STATUS_USE_PROXY = 305; +export const HTTP_STATUS_TEMPORARY_REDIRECT = 307; +export const HTTP_STATUS_PERMANENT_REDIRECT = 308; +export const HTTP_STATUS_BAD_REQUEST = 400; +export const HTTP_STATUS_UNAUTHORIZED = 401; +export const HTTP_STATUS_PAYMENT_REQUIRED = 402; +export const HTTP_STATUS_FORBIDDEN = 403; +export const HTTP_STATUS_NOT_FOUND = 404; +export const HTTP_STATUS_METHOD_NOT_ALLOWED = 405; +export const HTTP_STATUS_NOT_ACCEPTABLE = 406; +export const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED = 407; +export const HTTP_STATUS_REQUEST_TIMEOUT = 408; +export const HTTP_STATUS_CONFLICT = 409; +export const HTTP_STATUS_GONE = 410; +export const HTTP_STATUS_LENGTH_REQUIRED = 411; +export const HTTP_STATUS_PRECONDITION_FAILED = 412; +export const HTTP_STATUS_PAYLOAD_TOO_LARGE = 413; +export const HTTP_STATUS_URI_TOO_LONG = 414; +export const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE = 415; +export const HTTP_STATUS_RANGE_NOT_SATISFIABLE = 416; +export const HTTP_STATUS_EXPECTATION_FAILED = 417; +export const HTTP_STATUS_TEAPOT = 418; +export const HTTP_STATUS_MISDIRECTED_REQUEST = 421; +export const HTTP_STATUS_UNPROCESSABLE_ENTITY = 422; +export const HTTP_STATUS_LOCKED = 423; +export const HTTP_STATUS_FAILED_DEPENDENCY = 424; +export const HTTP_STATUS_TOO_EARLY = 425; +export const HTTP_STATUS_UPGRADE_REQUIRED = 426; +export const HTTP_STATUS_PRECONDITION_REQUIRED = 428; +export const HTTP_STATUS_TOO_MANY_REQUESTS = 429; +export const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE = 431; +export const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS = 451; +export const HTTP_STATUS_INTERNAL_SERVER_ERROR = 500; +export const HTTP_STATUS_NOT_IMPLEMENTED = 501; +export const HTTP_STATUS_BAD_GATEWAY = 502; +export const HTTP_STATUS_SERVICE_UNAVAILABLE = 503; +export const HTTP_STATUS_GATEWAY_TIMEOUT = 504; +export const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED = 505; +export const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES = 506; +export const HTTP_STATUS_INSUFFICIENT_STORAGE = 507; +export const HTTP_STATUS_LOOP_DETECTED = 508; +export const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED = 509; +export const HTTP_STATUS_NOT_EXTENDED = 510; +export const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED = 511; diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/net/server.d.mts b/worker/node_modules/unenv/dist/runtime/node/internal/net/server.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..d61a7c36634f8272bc04886f55e45c4c882e4f1e --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/net/server.d.mts @@ -0,0 +1,16 @@ +import type nodeNet from "node:net"; +import { EventEmitter } from "node:events"; +export declare class Server extends EventEmitter implements nodeNet.Server { + readonly __unenv__: true; + maxConnections: number; + connections: number; + readonly listening: boolean; + constructor(arg1?: nodeNet.ServerOpts | ((socket: nodeNet.Socket) => void), arg2?: (socket: nodeNet.Socket) => void); + listen(): this; + close(callback?: (err?: Error) => void): this; + address(): nodeNet.AddressInfo | string | null; + getConnections(cb: (error: Error | null, count: number) => void): void; + ref(): this; + unref(): this; + [Symbol.asyncDispose](): Promise; +} diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/net/server.mjs b/worker/node_modules/unenv/dist/runtime/node/internal/net/server.mjs new file mode 100644 index 0000000000000000000000000000000000000000..df1542e0726d692bc83cb90787debba419418dd6 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/net/server.mjs @@ -0,0 +1,32 @@ +import { createNotImplementedError } from "../../../_internal/utils.mjs"; +import { EventEmitter } from "node:events"; +export class Server extends EventEmitter { + __unenv__ = true; + maxConnections = 1; + connections = 0; + listening = false; + constructor(arg1, arg2) { + super(); + } + listen() { + throw createNotImplementedError("node:net.Server.listen()"); + } + close(callback) { + throw createNotImplementedError("node:net.Server.close()"); + } + address() { + return null; + } + getConnections(cb) { + cb(null, 0); + } + ref() { + return this; + } + unref() { + return this; + } + [Symbol.asyncDispose]() { + return Promise.resolve(); + } +} diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/net/socket.d.mts b/worker/node_modules/unenv/dist/runtime/node/internal/net/socket.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..69ff1e17060ef721326da4f29eab6e59110ebf90 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/net/socket.d.mts @@ -0,0 +1,43 @@ +import type nodeNet from "node:net"; +import { type Callback, type BufferEncoding } from "../../../_internal/types.mjs"; +import { Duplex } from "../stream/duplex.mjs"; +export declare class Socket extends Duplex implements nodeNet.Socket { + readonly __unenv__: true; + readonly bufferSize: number; + readonly bytesRead: number; + readonly bytesWritten: number; + readonly connecting: boolean; + readonly destroyed: boolean; + readonly pending: boolean; + readonly localAddress: string; + readonly localPort: number; + readonly remoteAddress?: string; + readonly remoteFamily?: string; + readonly remotePort?: number; + readonly autoSelectFamilyAttemptedAddresses: readonly []; + readonly readyState: nodeNet.SocketReadyState; + constructor(_options?: nodeNet.SocketConstructorOpts); + write(_buffer: Uint8Array | string, _arg1?: BufferEncoding | Callback, _arg2?: Callback): boolean; + connect(_arg1: number | string | nodeNet.SocketConnectOpts, _arg2?: string | Callback, _arg3?: Callback); + end(_arg1?: Callback | Uint8Array | string, _arg2?: BufferEncoding | Callback, _arg3?: Callback); + setEncoding(_encoding?: BufferEncoding): this; + pause(); + resume(); + setTimeout(_timeout: number, _callback?: Callback): this; + setNoDelay(_noDelay?: boolean): this; + setKeepAlive(_enable?: boolean, _initialDelay?: number): this; + address(): {}; + unref(); + ref(); + destroySoon(); + resetAndDestroy(); +} +export declare class SocketAddress implements nodeNet.SocketAddress { + readonly __unenv__: true; + address: string; + family: "ipv4" | "ipv6"; + port: number; + flowlabel: number; + static parse(_address: string, _port?: number): undefined; + constructor(options: nodeNet.SocketAddress); +} diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/net/socket.mjs b/worker/node_modules/unenv/dist/runtime/node/internal/net/socket.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7542c796d6bb973d1ccb596d63981cc9d91e0cbd --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/net/socket.mjs @@ -0,0 +1,81 @@ +import { Duplex } from "../stream/duplex.mjs"; +export class Socket extends Duplex { + __unenv__ = true; + bufferSize = 0; + bytesRead = 0; + bytesWritten = 0; + connecting = false; + destroyed = false; + pending = false; + localAddress = ""; + localPort = 0; + remoteAddress = ""; + remoteFamily = ""; + remotePort = 0; + autoSelectFamilyAttemptedAddresses = []; + readyState = "readOnly"; + constructor(_options) { + super(); + } + write(_buffer, _arg1, _arg2) { + return false; + } + connect(_arg1, _arg2, _arg3) { + return this; + } + end(_arg1, _arg2, _arg3) { + return this; + } + setEncoding(_encoding) { + return this; + } + pause() { + return this; + } + resume() { + return this; + } + setTimeout(_timeout, _callback) { + return this; + } + setNoDelay(_noDelay) { + return this; + } + setKeepAlive(_enable, _initialDelay) { + return this; + } + address() { + return {}; + } + unref() { + return this; + } + ref() { + return this; + } + destroySoon() { + this.destroy(); + } + resetAndDestroy() { + const err = new Error("ERR_SOCKET_CLOSED"); + err.code = "ERR_SOCKET_CLOSED"; + this.destroy(err); + return this; + } +} +export class SocketAddress { + __unenv__ = true; + address; + family; + port; + flowlabel; + static parse(_address, _port) { + return undefined; + } + constructor(options) { + this.address = options.address; + this.family = options.family; + this.port = options.port; + this.flowlabel = options.flowlabel; + } +} diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/os/constants.d.mts b/worker/node_modules/unenv/dist/runtime/node/internal/os/constants.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..4f2d2f69927d570b3394ec166c1b84a09fc360fa --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/os/constants.d.mts @@ -0,0 +1,132 @@ +export declare const UV_UDP_REUSEADDR = 4; +export declare const dlopen: { + RTLD_LAZY: number + RTLD_NOW: number + RTLD_GLOBAL: number + RTLD_LOCAL: number + RTLD_DEEPBIND: number +}; +export declare const errno: { + E2BIG: number + EACCES: number + EADDRINUSE: number + EADDRNOTAVAIL: number + EAFNOSUPPORT: number + EAGAIN: number + EALREADY: number + EBADF: number + EBADMSG: number + EBUSY: number + ECANCELED: number + ECHILD: number + ECONNABORTED: number + ECONNREFUSED: number + ECONNRESET: number + EDEADLK: number + EDESTADDRREQ: number + EDOM: number + EDQUOT: number + EEXIST: number + EFAULT: number + EFBIG: number + EHOSTUNREACH: number + EIDRM: number + EILSEQ: number + EINPROGRESS: number + EINTR: number + EINVAL: number + EIO: number + EISCONN: number + EISDIR: number + ELOOP: number + EMFILE: number + EMLINK: number + EMSGSIZE: number + EMULTIHOP: number + ENAMETOOLONG: number + ENETDOWN: number + ENETRESET: number + ENETUNREACH: number + ENFILE: number + ENOBUFS: number + ENODATA: number + ENODEV: number + ENOENT: number + ENOEXEC: number + ENOLCK: number + ENOLINK: number + ENOMEM: number + ENOMSG: number + ENOPROTOOPT: number + ENOSPC: number + ENOSR: number + ENOSTR: number + ENOSYS: number + ENOTCONN: number + ENOTDIR: number + ENOTEMPTY: number + ENOTSOCK: number + ENOTSUP: number + ENOTTY: number + ENXIO: number + EOPNOTSUPP: number + EOVERFLOW: number + EPERM: number + EPIPE: number + EPROTO: number + EPROTONOSUPPORT: number + EPROTOTYPE: number + ERANGE: number + EROFS: number + ESPIPE: number + ESRCH: number + ESTALE: number + ETIME: number + ETIMEDOUT: number + ETXTBSY: number + EWOULDBLOCK: number + EXDEV: number +}; +export declare const signals: { + SIGHUP: number + SIGINT: number + SIGQUIT: number + SIGILL: number + SIGTRAP: number + SIGABRT: number + SIGIOT: number + SIGBUS: number + SIGFPE: number + SIGKILL: number + SIGUSR1: number + SIGSEGV: number + SIGUSR2: number + SIGPIPE: number + SIGALRM: number + SIGTERM: number + SIGCHLD: number + SIGSTKFLT: number + SIGCONT: number + SIGSTOP: number + SIGTSTP: number + SIGTTIN: number + SIGTTOU: number + SIGURG: number + SIGXCPU: number + SIGXFSZ: number + SIGVTALRM: number + SIGPROF: number + SIGWINCH: number + SIGIO: number + SIGPOLL: number + SIGPWR: number + SIGSYS: number +}; +export declare const priority: { + PRIORITY_LOW: number + PRIORITY_BELOW_NORMAL: number + PRIORITY_NORMAL: number + PRIORITY_ABOVE_NORMAL: number + PRIORITY_HIGH: number + PRIORITY_HIGHEST: number +}; diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/os/constants.mjs b/worker/node_modules/unenv/dist/runtime/node/internal/os/constants.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e9c22bb90eb72fd8d3e17bccb3bc3152cafab307 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/os/constants.mjs @@ -0,0 +1,132 @@ +export const UV_UDP_REUSEADDR = 4; +export const dlopen = { + RTLD_LAZY: 1, + RTLD_NOW: 2, + RTLD_GLOBAL: 256, + RTLD_LOCAL: 0, + RTLD_DEEPBIND: 8 +}; +export const errno = { + E2BIG: 7, + EACCES: 13, + EADDRINUSE: 98, + EADDRNOTAVAIL: 99, + EAFNOSUPPORT: 97, + EAGAIN: 11, + EALREADY: 114, + EBADF: 9, + EBADMSG: 74, + EBUSY: 16, + ECANCELED: 125, + ECHILD: 10, + ECONNABORTED: 103, + ECONNREFUSED: 111, + ECONNRESET: 104, + EDEADLK: 35, + EDESTADDRREQ: 89, + EDOM: 33, + EDQUOT: 122, + EEXIST: 17, + EFAULT: 14, + EFBIG: 27, + EHOSTUNREACH: 113, + EIDRM: 43, + EILSEQ: 84, + EINPROGRESS: 115, + EINTR: 4, + EINVAL: 22, + EIO: 5, + EISCONN: 106, + EISDIR: 21, + ELOOP: 40, + EMFILE: 24, + EMLINK: 31, + EMSGSIZE: 90, + EMULTIHOP: 72, + ENAMETOOLONG: 36, + ENETDOWN: 100, + ENETRESET: 102, + ENETUNREACH: 101, + ENFILE: 23, + ENOBUFS: 105, + ENODATA: 61, + ENODEV: 19, + ENOENT: 2, + ENOEXEC: 8, + ENOLCK: 37, + ENOLINK: 67, + ENOMEM: 12, + ENOMSG: 42, + ENOPROTOOPT: 92, + ENOSPC: 28, + ENOSR: 63, + ENOSTR: 60, + ENOSYS: 38, + ENOTCONN: 107, + ENOTDIR: 20, + ENOTEMPTY: 39, + ENOTSOCK: 88, + ENOTSUP: 95, + ENOTTY: 25, + ENXIO: 6, + EOPNOTSUPP: 95, + EOVERFLOW: 75, + EPERM: 1, + EPIPE: 32, + EPROTO: 71, + EPROTONOSUPPORT: 93, + EPROTOTYPE: 91, + ERANGE: 34, + EROFS: 30, + ESPIPE: 29, + ESRCH: 3, + ESTALE: 116, + ETIME: 62, + ETIMEDOUT: 110, + ETXTBSY: 26, + EWOULDBLOCK: 11, + EXDEV: 18 +}; +export const signals = { + SIGHUP: 1, + SIGINT: 2, + SIGQUIT: 3, + SIGILL: 4, + SIGTRAP: 5, + SIGABRT: 6, + SIGIOT: 6, + SIGBUS: 7, + SIGFPE: 8, + SIGKILL: 9, + SIGUSR1: 10, + SIGSEGV: 11, + SIGUSR2: 12, + SIGPIPE: 13, + SIGALRM: 14, + SIGTERM: 15, + SIGCHLD: 17, + SIGSTKFLT: 16, + SIGCONT: 18, + SIGSTOP: 19, + SIGTSTP: 20, + SIGTTIN: 21, + SIGTTOU: 22, + SIGURG: 23, + SIGXCPU: 24, + SIGXFSZ: 25, + SIGVTALRM: 26, + SIGPROF: 27, + SIGWINCH: 28, + SIGIO: 29, + SIGPOLL: 29, + SIGPWR: 30, + SIGSYS: 31 +}; +export const priority = { + PRIORITY_LOW: 19, + PRIORITY_BELOW_NORMAL: 10, + PRIORITY_NORMAL: 0, + PRIORITY_ABOVE_NORMAL: -7, + PRIORITY_HIGH: -14, + PRIORITY_HIGHEST: -20 +}; diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/perf_hooks/constants.d.mts b/worker/node_modules/unenv/dist/runtime/node/internal/perf_hooks/constants.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..4396e245b931d26cc0b08c9aa17341c8a66cef4a --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/perf_hooks/constants.d.mts @@ -0,0 +1,24 @@ +export declare const NODE_PERFORMANCE_GC_MAJOR = 4; +export declare const NODE_PERFORMANCE_GC_MINOR = 1; +export declare const NODE_PERFORMANCE_GC_INCREMENTAL = 8; +export declare const NODE_PERFORMANCE_GC_WEAKCB = 16; +export declare const NODE_PERFORMANCE_GC_FLAGS_NO = 0; +export declare const NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED = 2; +export declare const NODE_PERFORMANCE_GC_FLAGS_FORCED = 4; +export declare const NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING = 8; +export declare const NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE = 16; +export declare const NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY = 32; +export declare const NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE = 64; +export declare const NODE_PERFORMANCE_ENTRY_TYPE_GC = 0; +export declare const NODE_PERFORMANCE_ENTRY_TYPE_HTTP = 1; +export declare const NODE_PERFORMANCE_ENTRY_TYPE_HTTP2 = 2; +export declare const NODE_PERFORMANCE_ENTRY_TYPE_NET = 3; +export declare const NODE_PERFORMANCE_ENTRY_TYPE_DNS = 4; +export declare const NODE_PERFORMANCE_MILESTONE_TIME_ORIGIN_TIMESTAMP = 0; +export declare const NODE_PERFORMANCE_MILESTONE_TIME_ORIGIN = 1; +export declare const NODE_PERFORMANCE_MILESTONE_ENVIRONMENT = 2; +export declare const NODE_PERFORMANCE_MILESTONE_NODE_START = 3; +export declare const NODE_PERFORMANCE_MILESTONE_V8_START = 4; +export declare const NODE_PERFORMANCE_MILESTONE_LOOP_START = 5; +export declare const NODE_PERFORMANCE_MILESTONE_LOOP_EXIT = 6; +export declare const NODE_PERFORMANCE_MILESTONE_BOOTSTRAP_COMPLETE = 7; diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/perf_hooks/constants.mjs b/worker/node_modules/unenv/dist/runtime/node/internal/perf_hooks/constants.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b6c75d1d8e65b1b4b50c61fb17a9556a0f14d7a0 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/perf_hooks/constants.mjs @@ -0,0 +1,24 @@ +export const NODE_PERFORMANCE_GC_MAJOR = 4; +export const NODE_PERFORMANCE_GC_MINOR = 1; +export const NODE_PERFORMANCE_GC_INCREMENTAL = 8; +export const NODE_PERFORMANCE_GC_WEAKCB = 16; +export const NODE_PERFORMANCE_GC_FLAGS_NO = 0; +export const NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED = 2; +export const NODE_PERFORMANCE_GC_FLAGS_FORCED = 4; +export const NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING = 8; +export const NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE = 16; +export const NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY = 32; +export const NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE = 64; +export const NODE_PERFORMANCE_ENTRY_TYPE_GC = 0; +export const NODE_PERFORMANCE_ENTRY_TYPE_HTTP = 1; +export const NODE_PERFORMANCE_ENTRY_TYPE_HTTP2 = 2; +export const NODE_PERFORMANCE_ENTRY_TYPE_NET = 3; +export const NODE_PERFORMANCE_ENTRY_TYPE_DNS = 4; +export const NODE_PERFORMANCE_MILESTONE_TIME_ORIGIN_TIMESTAMP = 0; +export const NODE_PERFORMANCE_MILESTONE_TIME_ORIGIN = 1; +export const NODE_PERFORMANCE_MILESTONE_ENVIRONMENT = 2; +export const NODE_PERFORMANCE_MILESTONE_NODE_START = 3; +export const NODE_PERFORMANCE_MILESTONE_V8_START = 4; +export const NODE_PERFORMANCE_MILESTONE_LOOP_START = 5; +export const NODE_PERFORMANCE_MILESTONE_LOOP_EXIT = 6; +export const NODE_PERFORMANCE_MILESTONE_BOOTSTRAP_COMPLETE = 7; diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/perf_hooks/histogram.d.mts b/worker/node_modules/unenv/dist/runtime/node/internal/perf_hooks/histogram.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..1ae2033c3d8b3d868bf1b67f6abad7290556b140 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/perf_hooks/histogram.d.mts @@ -0,0 +1,28 @@ +import type nodePerfHooks from "node:perf_hooks"; +declare class Histogram implements nodePerfHooks.Histogram { + min: number; + max: number; + mean; + exceeds: number; + stddev; + count: number; + countBigInt: bigint; + exceedsBigInt: bigint; + maxBigInt: number; + minBigInt: bigint; + percentiles: Map; + percentilesBigInt: Map; + percentileBigInt(_percentile: number): bigint; + percentile(percentile: number): number; + reset(): void; +} +export declare class IntervalHistogram extends Histogram implements nodePerfHooks.IntervalHistogram { + enable(): boolean; + disable(): boolean; +} +export declare class RecordableHistogram extends Histogram implements nodePerfHooks.RecordableHistogram { + record(val: number | bigint): void; + recordDelta(): void; + add(other: nodePerfHooks.RecordableHistogram): void; +} +export {}; diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/perf_hooks/histogram.mjs b/worker/node_modules/unenv/dist/runtime/node/internal/perf_hooks/histogram.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f1ae41d246702f68c688ec3b28ea12028b24a248 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/perf_hooks/histogram.mjs @@ -0,0 +1,43 @@ +import { createNotImplementedError } from "../../../_internal/utils.mjs"; +class Histogram { + min = 0x8000000000000000; + max = 0; + mean = Number.NaN; + exceeds = 0; + stddev = Number.NaN; + count = 0; + countBigInt = BigInt(0); + exceedsBigInt = BigInt(0); + maxBigInt = 0; + minBigInt = BigInt(9223372036854775807n); + percentiles = new Map(); + percentilesBigInt = new Map(); + percentileBigInt(_percentile) { + throw createNotImplementedError("Histogram.percentileBigInt"); + } + percentile(percentile) { + return this.percentiles.get(percentile) ?? Number.NaN; + } + reset() { + throw createNotImplementedError("Histogram.reset"); + } +} +export class IntervalHistogram extends Histogram { + enable() { + return true; + } + disable() { + return true; + } +} +export class RecordableHistogram extends Histogram { + record(val) { + throw createNotImplementedError("RecordableHistogram.record"); + } + recordDelta() { + throw createNotImplementedError("RecordableHistogram.recordDelta"); + } + add(other) { + throw createNotImplementedError("RecordableHistogram.add"); + } +} diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/process/env.d.mts b/worker/node_modules/unenv/dist/runtime/node/internal/process/env.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..06acedfb7ad8c09081eb750776ceadddf6f9e19e --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/process/env.d.mts @@ -0,0 +1 @@ +export declare const env: NodeJS.Process["env"]; diff --git a/worker/node_modules/unenv/dist/runtime/node/internal/process/env.mjs b/worker/node_modules/unenv/dist/runtime/node/internal/process/env.mjs new file mode 100644 index 0000000000000000000000000000000000000000..521e728254936f4633244a9ce33d3ebf86b0e154 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/internal/process/env.mjs @@ -0,0 +1,39 @@ +const _envShim = Object.create(null); +const originalProcess = globalThis["process"]; +const _getEnv = (useShim) => globalThis.__env__ || originalProcess?.env || (useShim ? _envShim : globalThis); +export const env = /*@__PURE__*/ new Proxy(_envShim, { + get(_, prop) { + const env = _getEnv(); + return env[prop] ?? _envShim[prop]; + }, + has(_, prop) { + const env = _getEnv(); + return prop in env || prop in _envShim; + }, + set(_, prop, value) { + const env = _getEnv(true); + env[prop] = value; + return true; + }, + deleteProperty(_, prop) { + const env = _getEnv(true); + delete env[prop]; + return true; + }, + ownKeys() { + const env = _getEnv(); + return Object.keys(env); + }, + getOwnPropertyDescriptor(_, prop) { + const env = _getEnv(); + if (prop in env) { + return { + value: env[prop], + writable: true, + enumerable: true, + configurable: true + }; + } + return undefined; + } +}); diff --git a/worker/node_modules/unenv/dist/runtime/node/module.d.mts b/worker/node_modules/unenv/dist/runtime/node/module.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..e07bb07edc2fa55f4fc219ee3c364aa9b783e78f --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/module.d.mts @@ -0,0 +1,35 @@ +import type nodeModule from "node:module"; +export declare const _cache: unknown; +export declare const _extensions: {}; +export declare const createRequire: unknown; +export declare const getCompileCacheDir: typeof nodeModule.getCompileCacheDir; +export declare const enableCompileCache: typeof nodeModule.enableCompileCache; +export declare const constants: typeof nodeModule.constants; +export declare const builtinModules: typeof nodeModule.builtinModules; +export declare const isBuiltin: typeof nodeModule.isBuiltin; +export declare const runMain: typeof nodeModule.runMain; +export declare const register: typeof nodeModule.register; +export declare const syncBuiltinESMExports: typeof nodeModule.syncBuiltinESMExports; +export declare const findSourceMap: typeof nodeModule.findSourceMap; +export declare const flushCompileCache: typeof nodeModule.flushCompileCache; +export declare const wrap: typeof nodeModule.wrap; +export declare const wrapper: unknown; +export declare const stripTypeScriptTypes: typeof nodeModule.stripTypeScriptTypes; +export declare const SourceMap: typeof nodeModule.SourceMap; +export declare const _debug: unknown; +export declare const _findPath: unknown; +export declare const _initPaths: unknown; +export declare const _load: unknown; +export declare const _nodeModulePaths: unknown; +export declare const _preloadModules: unknown; +export declare const _resolveFilename: unknown; +export declare const _resolveLookupPaths: unknown; +export declare const _stat: unknown; +export declare const _readPackage: unknown; +export declare const findPackageJSON: unknown; +export declare const getSourceMapsSupport: unknown; +export declare const setSourceMapsSupport: unknown; +export declare const _pathCache: unknown; +export declare const globalPaths: unknown; +export declare const Module: {}; +export default Module; diff --git a/worker/node_modules/unenv/dist/runtime/node/module.mjs b/worker/node_modules/unenv/dist/runtime/node/module.mjs new file mode 100644 index 0000000000000000000000000000000000000000..addf1e443af7bd6376b947180c582573ed71aa53 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/module.mjs @@ -0,0 +1,177 @@ +import { notImplemented, notImplementedClass } from "../_internal/utils.mjs"; +export const _cache = Object.create(null); +export const _extensions = { + ".js": /*@__PURE__*/ notImplemented("module.require.extensions['.js']"), + ".json": /*@__PURE__*/ notImplemented("module.require.extensions['.json']"), + ".node": /*@__PURE__*/ notImplemented("module.require.extensions['.node']") +}; +export const createRequire = function(_filename) { + return Object.assign( + /*@__PURE__*/ notImplemented("module.require"), + { + resolve: Object.assign( + /*@__PURE__*/ notImplemented("module.require.resolve"), + { paths: /*@__PURE__*/ notImplemented("module.require.resolve.paths") } +), + cache: Object.create(null), + extensions: _extensions, + main: undefined + } +); +}; +export const getCompileCacheDir = function() { + return undefined; +}; +export const enableCompileCache = function(_cacheDir) { + return { + status: 0, + message: "not implemented" + }; +}; +export const constants = Object.freeze({ compileCacheStatus: Object.freeze({ + FAILED: 0, + ENABLED: 1, + ALREADY_ENABLED: 2, + DISABLED: 3 +}) }); +export const builtinModules = [ + "_http_agent", + "_http_client", + "_http_common", + "_http_incoming", + "_http_outgoing", + "_http_server", + "_stream_duplex", + "_stream_passthrough", + "_stream_readable", + "_stream_transform", + "_stream_wrap", + "_stream_writable", + "_tls_common", + "_tls_wrap", + "assert", + "assert/strict", + "async_hooks", + "buffer", + "child_process", + "cluster", + "console", + "constants", + "crypto", + "dgram", + "diagnostics_channel", + "dns", + "dns/promises", + "domain", + "events", + "fs", + "fs/promises", + "http", + "http2", + "https", + "inspector", + "inspector/promises", + "module", + "net", + "os", + "path", + "path/posix", + "path/win32", + "perf_hooks", + "process", + "punycode", + "querystring", + "readline", + "readline/promises", + "repl", + "stream", + "stream/consumers", + "stream/promises", + "stream/web", + "string_decoder", + "sys", + "timers", + "timers/promises", + "tls", + "trace_events", + "tty", + "url", + "util", + "util/types", + "v8", + "vm", + "wasi", + "worker_threads", + "zlib" +]; +export const isBuiltin = function(id) { + return id.startsWith("node:") || builtinModules.includes(id); +}; +export const runMain = /*@__PURE__*/ notImplemented("module.runMain"); +export const register = /*@__PURE__*/ notImplemented("module.register"); +export const syncBuiltinESMExports = function() { + return []; +}; +export const findSourceMap = function(path, error) { + return undefined; +}; +export const flushCompileCache = function flushCompileCache() {}; +export const wrap = function(source) { + return `(function (exports, require, module, __filename, __dirname) { ${source}\n});`; +}; +export const wrapper = ["(function (exports, require, module, __filename, __dirname) { ", "\n});"]; +export const stripTypeScriptTypes = /*@__PURE__*/ notImplemented("module.stripTypeScriptTypes"); +export const SourceMap = /*@__PURE__*/ notImplementedClass("module.SourceMap"); +export const _debug = console.debug; +export const _findPath = /*@__PURE__*/ notImplemented("module._findPath"); +export const _initPaths = /*@__PURE__*/ notImplemented("module._initPaths"); +export const _load = /*@__PURE__*/ notImplemented("module._load"); +export const _nodeModulePaths = /*@__PURE__*/ notImplemented("module._nodeModulePaths"); +export const _preloadModules = /*@__PURE__*/ notImplemented("module._preloadModules"); +export const _resolveFilename = /*@__PURE__*/ notImplemented("module._resolveFilename"); +export const _resolveLookupPaths = /*@__PURE__*/ notImplemented("module._resolveLookupPaths"); +export const _stat = /*@__PURE__*/ notImplemented("module._stat"); +export const _readPackage = /*@__PURE__*/ notImplemented("module._readPackage"); +export const findPackageJSON = /*@__PURE__*/ notImplemented("module.findPackageJSON"); +export const getSourceMapsSupport = /*@__PURE__*/ notImplemented("module.getSourceMapsSupport"); +export const setSourceMapsSupport = /*@__PURE__*/ notImplemented("module.setSourceMapsSupport"); +export const _pathCache = Object.create(null); +export const globalPaths = ["node_modules"]; +export const Module = { + get Module() { + return Module; + }, + SourceMap, + _cache, + _extensions, + _debug, + _pathCache, + _findPath, + _initPaths, + _load, + _nodeModulePaths, + _preloadModules, + _resolveFilename, + _resolveLookupPaths, + _stat, + _readPackage, + builtinModules, + constants, + createRequire, + enableCompileCache, + findSourceMap, + getCompileCacheDir, + globalPaths, + isBuiltin, + register, + runMain, + syncBuiltinESMExports, + wrap, + wrapper, + flushCompileCache, + stripTypeScriptTypes, + findPackageJSON, + getSourceMapsSupport, + setSourceMapsSupport +}; +export default Module; diff --git a/worker/node_modules/unenv/dist/runtime/node/net.d.mts b/worker/node_modules/unenv/dist/runtime/node/net.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..6b46924d25336672770003944905b283f2799ff2 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/net.d.mts @@ -0,0 +1,19 @@ +import type nodeNet from "node:net"; +export { Server } from "./internal/net/server.mjs"; +export { Socket, SocketAddress, Socket as Stream } from "./internal/net/socket.mjs"; +export declare const createServer: typeof nodeNet.createServer; +export declare const BlockList: typeof nodeNet.BlockList; +export declare const connect: typeof nodeNet.connect; +export declare const createConnection: typeof nodeNet.createConnection; +export declare const getDefaultAutoSelectFamily: typeof nodeNet.getDefaultAutoSelectFamily; +export declare const setDefaultAutoSelectFamily: typeof nodeNet.setDefaultAutoSelectFamily; +export declare const getDefaultAutoSelectFamilyAttemptTimeout: typeof nodeNet.getDefaultAutoSelectFamilyAttemptTimeout; +export declare const setDefaultAutoSelectFamilyAttemptTimeout: typeof nodeNet.setDefaultAutoSelectFamilyAttemptTimeout; +export declare const isIPv4: typeof nodeNet.isIPv4; +export declare const isIPv6: typeof nodeNet.isIPv6; +export declare const isIP: typeof nodeNet.isIP; +export declare const _createServerHandle: unknown; +export declare const _normalizeArgs: unknown; +export declare const _setSimultaneousAccepts: unknown; +declare const exports: typeof nodeNet; +export default exports; diff --git a/worker/node_modules/unenv/dist/runtime/node/net.mjs b/worker/node_modules/unenv/dist/runtime/node/net.mjs new file mode 100644 index 0000000000000000000000000000000000000000..2a2af758b33586226344ae35f4c1e64161c55efb --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/net.mjs @@ -0,0 +1,50 @@ +import { notImplemented, notImplementedClass } from "../_internal/utils.mjs"; +import { Socket, SocketAddress } from "./internal/net/socket.mjs"; +import { Server } from "./internal/net/server.mjs"; +export { Server } from "./internal/net/server.mjs"; +export { Socket, SocketAddress, Socket as Stream } from "./internal/net/socket.mjs"; +export const createServer = /*@__PURE__*/ notImplemented("net.createServer"); +export const BlockList = /*@__PURE__*/ notImplementedClass("net.BlockList"); +export const connect = /*@__PURE__*/ notImplemented("net.connect"); +export const createConnection = /*@__PURE__*/ notImplemented("net.createConnection"); +export const getDefaultAutoSelectFamily = /*@__PURE__*/ notImplemented("net.getDefaultAutoSelectFamily"); +export const setDefaultAutoSelectFamily = /*@__PURE__*/ notImplemented("net.setDefaultAutoSelectFamily"); +export const getDefaultAutoSelectFamilyAttemptTimeout = /*@__PURE__*/ notImplemented("net.getDefaultAutoSelectFamilyAttemptTimeout"); +export const setDefaultAutoSelectFamilyAttemptTimeout = /*@__PURE__*/ notImplemented("net.setDefaultAutoSelectFamilyAttemptTimeout"); +const IPV4Regex = /^(?:\d{1,3}\.){3}\d{1,3}$/; +export const isIPv4 = (host) => IPV4Regex.test(host); +const IPV6Regex = /^([\dA-Fa-f]{1,4}:){7}[\dA-Fa-f]{1,4}$/; +export const isIPv6 = (host) => IPV6Regex.test(host); +export const isIP = (host) => { + if (isIPv4(host)) { + return 4; + } + if (isIPv6(host)) { + return 6; + } + return 0; +}; +export const _createServerHandle = /*@__PURE__*/ notImplemented("net._createServerHandle"); +export const _normalizeArgs = /*@__PURE__*/ notImplemented("net._normalizeArgs"); +export const _setSimultaneousAccepts = /*@__PURE__*/ notImplemented("net._setSimultaneousAccepts"); +const exports = { + Socket, + Stream: Socket, + Server, + BlockList, + SocketAddress, + createServer, + connect, + createConnection, + isIPv4, + isIPv6, + isIP, + getDefaultAutoSelectFamily, + getDefaultAutoSelectFamilyAttemptTimeout, + setDefaultAutoSelectFamily, + setDefaultAutoSelectFamilyAttemptTimeout, + _createServerHandle, + _normalizeArgs, + _setSimultaneousAccepts +}; +export default exports; diff --git a/worker/node_modules/unenv/dist/runtime/node/os.d.mts b/worker/node_modules/unenv/dist/runtime/node/os.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..ed4978702d54e3e72446aeca3bf22932081eca81 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/os.d.mts @@ -0,0 +1,26 @@ +import type nodeOs from "node:os"; +export declare const constants: typeof nodeOs.constants; +export declare const availableParallelism: typeof nodeOs.availableParallelism; +export declare const arch: typeof nodeOs.arch; +export declare const machine: typeof nodeOs.machine; +export declare const endianness: typeof nodeOs.endianness; +export declare const cpus: typeof nodeOs.cpus; +export declare const getPriority: typeof nodeOs.getPriority; +export declare const setPriority: typeof nodeOs.setPriority; +export declare const homedir: typeof nodeOs.homedir; +export declare const tmpdir: typeof nodeOs.tmpdir; +export declare const devNull: typeof nodeOs.devNull; +export declare const freemem: typeof nodeOs.freemem; +export declare const totalmem: typeof nodeOs.totalmem; +export declare const loadavg: typeof nodeOs.loadavg; +export declare const uptime: typeof nodeOs.uptime; +export declare const hostname: typeof nodeOs.hostname; +export declare const networkInterfaces: typeof nodeOs.networkInterfaces; +export declare const platform: typeof nodeOs.platform; +export declare const type: typeof nodeOs.type; +export declare const release: typeof nodeOs.release; +export declare const version: typeof nodeOs.version; +export declare const userInfo: typeof nodeOs.userInfo; +export declare const EOL: typeof nodeOs.EOL; +declare const _default: {}; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/os.mjs b/worker/node_modules/unenv/dist/runtime/node/os.mjs new file mode 100644 index 0000000000000000000000000000000000000000..924ed71b5177a2f23ae07ff2c62d9dc451ce20fc --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/os.mjs @@ -0,0 +1,118 @@ +import { notImplemented } from "../_internal/utils.mjs"; +import { UV_UDP_REUSEADDR, dlopen, errno, signals, priority } from "./internal/os/constants.mjs"; +export const constants = { + UV_UDP_REUSEADDR, + dlopen, + errno, + signals, + priority +}; +const NUM_CPUS = 8; +export const availableParallelism = () => NUM_CPUS; +export const arch = () => ""; +export const machine = () => ""; +export const endianness = () => "LE"; +export const cpus = () => { + const info = { + model: "", + speed: 0, + times: { + user: 0, + nice: 0, + sys: 0, + idle: 0, + irq: 0 + } + }; + return Array.from({ length: NUM_CPUS }, () => info); +}; +export const getPriority = () => 0; +export const setPriority = /*@__PURE__*/ notImplemented("os.setPriority"); +export const homedir = () => "/"; +export const tmpdir = () => "/tmp"; +export const devNull = "/dev/null"; +export const freemem = () => 0; +export const totalmem = () => 0; +export const loadavg = () => [ + 0, + 0, + 0 +]; +export const uptime = () => 0; +export const hostname = () => ""; +export const networkInterfaces = () => { + return { lo0: [ + { + address: "127.0.0.1", + netmask: "255.0.0.0", + family: "IPv4", + mac: "00:00:00:00:00:00", + internal: true, + cidr: "127.0.0.1/8" + }, + { + address: "::1", + netmask: "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", + family: "IPv6", + mac: "00:00:00:00:00:00", + internal: true, + cidr: "::1/128", + scopeid: 0 + }, + { + address: "fe80::1", + netmask: "ffff:ffff:ffff:ffff::", + family: "IPv6", + mac: "00:00:00:00:00:00", + internal: true, + cidr: "fe80::1/64", + scopeid: 1 + } + ] }; +}; +export const platform = () => "linux"; +export const type = () => "Linux"; +export const release = () => ""; +export const version = () => ""; +export const userInfo = (opts) => { + const encode = (str) => { + if (opts?.encoding) { + const buff = Buffer.from(str); + return opts.encoding === "buffer" ? buff : buff.toString(opts.encoding); + } + return str; + }; + return { + gid: 1e3, + uid: 1e3, + homedir: encode("/"), + shell: encode("/bin/sh"), + username: encode("root") + }; +}; +export const EOL = "\n"; +export default { + arch, + availableParallelism, + constants, + cpus, + EOL, + endianness, + devNull, + freemem, + getPriority, + homedir, + hostname, + loadavg, + machine, + networkInterfaces, + platform, + release, + setPriority, + tmpdir, + totalmem, + type, + uptime, + userInfo, + version +}; diff --git a/worker/node_modules/unenv/dist/runtime/node/path.d.mts b/worker/node_modules/unenv/dist/runtime/node/path.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..a2ac479e61b777bb17546aec0088f94b81450ff6 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/path.d.mts @@ -0,0 +1,10 @@ +import type nodePath from "node:path"; +export { basename, dirname, extname, format, isAbsolute, join, normalize, parse, relative, resolve, toNamespacedPath } from "pathe"; +export declare const sep: "/"; +export declare const delimiter: ":"; +export declare const posix: typeof nodePath.posix; +export declare const win32: typeof nodePath.posix; +export declare const _makeLong: unknown; +export declare const matchesGlob: unknown; +declare const _default; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/path.mjs b/worker/node_modules/unenv/dist/runtime/node/path.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5cb4453317737d12b7b6b7f98e38db9f05de1556 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/path.mjs @@ -0,0 +1,31 @@ +import { notImplemented } from "../_internal/utils.mjs"; +import { basename, dirname, extname, format, isAbsolute, join, normalize, parse, relative, resolve, toNamespacedPath } from "pathe"; +export { basename, dirname, extname, format, isAbsolute, join, normalize, parse, relative, resolve, toNamespacedPath } from "pathe"; +export const sep = "/"; +export const delimiter = ":"; +const _pathModule = { + sep, + delimiter, + basename, + dirname, + extname, + format, + isAbsolute, + join, + normalize, + parse, + relative, + resolve, + toNamespacedPath, + posix: undefined, + win32: undefined, + _makeLong: (path) => path, + matchesGlob: /*@__PURE__*/ notImplemented(`path.matchesGlob`) +}; +_pathModule.posix = _pathModule; +_pathModule.win32 = _pathModule; +export const posix = _pathModule; +export const win32 = _pathModule; +export const _makeLong = _pathModule._makeLong; +export const matchesGlob = _pathModule.matchesGlob; +export default _pathModule; diff --git a/worker/node_modules/unenv/dist/runtime/node/path/posix.d.mts b/worker/node_modules/unenv/dist/runtime/node/path/posix.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..b49bc88383bbc487b2cb530f5363b9682b311cef --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/path/posix.d.mts @@ -0,0 +1,2 @@ +export * from "../path.mjs"; +export { default } from "../path.mjs"; diff --git a/worker/node_modules/unenv/dist/runtime/node/path/posix.mjs b/worker/node_modules/unenv/dist/runtime/node/path/posix.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b49bc88383bbc487b2cb530f5363b9682b311cef --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/path/posix.mjs @@ -0,0 +1,2 @@ +export * from "../path.mjs"; +export { default } from "../path.mjs"; diff --git a/worker/node_modules/unenv/dist/runtime/node/path/win32.d.mts b/worker/node_modules/unenv/dist/runtime/node/path/win32.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..b49bc88383bbc487b2cb530f5363b9682b311cef --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/path/win32.d.mts @@ -0,0 +1,2 @@ +export * from "../path.mjs"; +export { default } from "../path.mjs"; diff --git a/worker/node_modules/unenv/dist/runtime/node/path/win32.mjs b/worker/node_modules/unenv/dist/runtime/node/path/win32.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b49bc88383bbc487b2cb530f5363b9682b311cef --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/path/win32.mjs @@ -0,0 +1,2 @@ +export * from "../path.mjs"; +export { default } from "../path.mjs"; diff --git a/worker/node_modules/unenv/dist/runtime/node/perf_hooks.d.mts b/worker/node_modules/unenv/dist/runtime/node/perf_hooks.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..6f83677e43c0253774d05377a6be626182f36d6e --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/perf_hooks.d.mts @@ -0,0 +1,7 @@ +import type nodePerfHooks from "node:perf_hooks"; +export * from "./internal/perf_hooks/performance.mjs"; +export declare const constants: typeof nodePerfHooks.constants; +export declare const monitorEventLoopDelay: typeof nodePerfHooks.monitorEventLoopDelay; +export declare const createHistogram: typeof nodePerfHooks.createHistogram; +declare const _default: {}; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/perf_hooks.mjs b/worker/node_modules/unenv/dist/runtime/node/perf_hooks.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7831ea28830e96a5a9c50265a57ca6025c13c366 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/perf_hooks.mjs @@ -0,0 +1,49 @@ +import { IntervalHistogram, RecordableHistogram } from "./internal/perf_hooks/histogram.mjs"; +import { performance, Performance, PerformanceEntry, PerformanceMark, PerformanceMeasure, PerformanceObserverEntryList, PerformanceObserver, PerformanceResourceTiming } from "./internal/perf_hooks/performance.mjs"; +export * from "./internal/perf_hooks/performance.mjs"; +import { NODE_PERFORMANCE_GC_MAJOR, NODE_PERFORMANCE_GC_MINOR, NODE_PERFORMANCE_GC_INCREMENTAL, NODE_PERFORMANCE_GC_WEAKCB, NODE_PERFORMANCE_GC_FLAGS_NO, NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED, NODE_PERFORMANCE_GC_FLAGS_FORCED, NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING, NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE, NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY, NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE, NODE_PERFORMANCE_ENTRY_TYPE_GC, NODE_PERFORMANCE_ENTRY_TYPE_HTTP, NODE_PERFORMANCE_ENTRY_TYPE_HTTP2, NODE_PERFORMANCE_ENTRY_TYPE_NET, NODE_PERFORMANCE_ENTRY_TYPE_DNS, NODE_PERFORMANCE_MILESTONE_TIME_ORIGIN_TIMESTAMP, NODE_PERFORMANCE_MILESTONE_TIME_ORIGIN, NODE_PERFORMANCE_MILESTONE_ENVIRONMENT, NODE_PERFORMANCE_MILESTONE_NODE_START, NODE_PERFORMANCE_MILESTONE_V8_START, NODE_PERFORMANCE_MILESTONE_LOOP_START, NODE_PERFORMANCE_MILESTONE_LOOP_EXIT, NODE_PERFORMANCE_MILESTONE_BOOTSTRAP_COMPLETE } from "./internal/perf_hooks/constants.mjs"; +export const constants = { + NODE_PERFORMANCE_GC_MAJOR, + NODE_PERFORMANCE_GC_MINOR, + NODE_PERFORMANCE_GC_INCREMENTAL, + NODE_PERFORMANCE_GC_WEAKCB, + NODE_PERFORMANCE_GC_FLAGS_NO, + NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED, + NODE_PERFORMANCE_GC_FLAGS_FORCED, + NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING, + NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE, + NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY, + NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE, + NODE_PERFORMANCE_ENTRY_TYPE_GC, + NODE_PERFORMANCE_ENTRY_TYPE_HTTP, + NODE_PERFORMANCE_ENTRY_TYPE_HTTP2, + NODE_PERFORMANCE_ENTRY_TYPE_NET, + NODE_PERFORMANCE_ENTRY_TYPE_DNS, + NODE_PERFORMANCE_MILESTONE_TIME_ORIGIN_TIMESTAMP, + NODE_PERFORMANCE_MILESTONE_TIME_ORIGIN, + NODE_PERFORMANCE_MILESTONE_ENVIRONMENT, + NODE_PERFORMANCE_MILESTONE_NODE_START, + NODE_PERFORMANCE_MILESTONE_V8_START, + NODE_PERFORMANCE_MILESTONE_LOOP_START, + NODE_PERFORMANCE_MILESTONE_LOOP_EXIT, + NODE_PERFORMANCE_MILESTONE_BOOTSTRAP_COMPLETE +}; +export const monitorEventLoopDelay = function(_options) { + return new IntervalHistogram(); +}; +export const createHistogram = function(_options) { + return new RecordableHistogram(); +}; +export default { + Performance, + PerformanceMark, + PerformanceEntry, + PerformanceMeasure, + PerformanceObserverEntryList, + PerformanceObserver, + PerformanceResourceTiming, + performance, + constants, + createHistogram, + monitorEventLoopDelay +}; diff --git a/worker/node_modules/unenv/dist/runtime/node/process.d.mts b/worker/node_modules/unenv/dist/runtime/node/process.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..e9c5c3c666a2da1b3aea1d034f3b42f2e649a0fc --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/process.d.mts @@ -0,0 +1,3 @@ +declare const _default; +export default _default; +export declare const; diff --git a/worker/node_modules/unenv/dist/runtime/node/process.mjs b/worker/node_modules/unenv/dist/runtime/node/process.mjs new file mode 100644 index 0000000000000000000000000000000000000000..802b2d78a99cc8c0d964824ed292b04bc55d5d6b --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/process.mjs @@ -0,0 +1,11 @@ +import { Process } from "./internal/process/process.mjs"; +import { env as UnenvEnv } from "./internal/process/env.mjs"; +import { hrtime as UnenvHrTime } from "./internal/process/hrtime.mjs"; +import { nextTick as UnenvNextTick } from "./internal/process/nexttick.mjs"; +const unenvProcess = new Process({ + env: UnenvEnv, + hrtime: UnenvHrTime, + nextTick: UnenvNextTick +}); +export default unenvProcess; +export const { abort, addListener, allowedNodeEnvironmentFlags, hasUncaughtExceptionCaptureCallback, setUncaughtExceptionCaptureCallback, loadEnvFile, sourceMapsEnabled, arch, argv, argv0, chdir, config, connected, constrainedMemory, availableMemory, cpuUsage, cwd, debugPort, dlopen, disconnect, emit, emitWarning, env, eventNames, execArgv, execPath, exit, finalization, features, getBuiltinModule, getActiveResourcesInfo, getMaxListeners, hrtime, kill, listeners, listenerCount, memoryUsage, nextTick, on, off, once, pid, platform, ppid, prependListener, prependOnceListener, rawListeners, release, removeAllListeners, removeListener, report, resourceUsage, setMaxListeners, setSourceMapsEnabled, stderr, stdin, stdout, title, umask, uptime, version, versions, domain, initgroups, moduleLoadList, reallyExit, openStdin, assert, binding, send, exitCode, channel, getegid, geteuid, getgid, getgroups, getuid, setegid, seteuid, setgid, setgroups, setuid, permission, mainModule, ref, unref, _events, _eventsCount, _exiting, _maxListeners, _debugEnd, _debugProcess, _fatalException, _getActiveHandles, _getActiveRequests, _kill, _preload_modules, _rawDebug, _startProfilerIdleNotifier, _stopProfilerIdleNotifier, _tickCallback, _disconnect, _handleQueue, _pendingMessage, _channel, _send, _linkedBinding } = unenvProcess; diff --git a/worker/node_modules/unenv/dist/runtime/node/punycode.d.mts b/worker/node_modules/unenv/dist/runtime/node/punycode.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..d93c7da63d5d0bcef0a276f9b7f41443834e78d2 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/punycode.d.mts @@ -0,0 +1,3 @@ +export * from "./internal/punycode/punycode.mjs"; +declare const _default; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/punycode.mjs b/worker/node_modules/unenv/dist/runtime/node/punycode.mjs new file mode 100644 index 0000000000000000000000000000000000000000..64abe0547d930701b612c9e01ce2c7623e051779 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/punycode.mjs @@ -0,0 +1,3 @@ +import _punycode from "./internal/punycode/punycode.mjs"; +export * from "./internal/punycode/punycode.mjs"; +export default _punycode; diff --git a/worker/node_modules/unenv/dist/runtime/node/querystring.d.mts b/worker/node_modules/unenv/dist/runtime/node/querystring.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..8409a00bf848daef092472836e81ff78538d4b55 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/querystring.d.mts @@ -0,0 +1,49 @@ +/** +* A safe fast alternative to decodeURIComponent +* @param {string} s +* @param {boolean} decodeSpaces +* @returns {string} +*/ +declare function unescapeBuffer(s: string, decodeSpaces?: boolean): string | Buffer; +/** +* @param {string} s +* @param {boolean} decodeSpaces +* @returns {string} +*/ +declare function qsUnescape(s: string, decodeSpaces?: boolean): string; +/** +* QueryString.escape() replaces encodeURIComponent() +* @see https://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3.4 +* @param {any} str +* @returns {string} +*/ +declare function qsEscape(str: string): string; +/** +* @param {Record | null>} obj +* @param {string} [sep] +* @param {string} [eq] +* @param {{ encodeURIComponent?: (v: string) => string }} [options] +* @returns {string} +*/ +declare function stringify(obj: Record | null>, sep: string, eq: string, options: { + encodeURIComponent?: (v: string) => string +}); +/** +* Parse a key/val string. +* @param {string} qs +* @param {string} sep +* @param {string} eq +* @param {{ +* maxKeys?: number; +* decodeURIComponent?(v: string): string; +* }} [options] +* @returns {Record} +*/ +declare function parse(qs: string, sep: string, eq: string, options: { + maxKeys?: number + decodeURIComponent?(v: string): string +}); +export { unescapeBuffer, qsUnescape as unescape, qsEscape as escape, stringify, stringify as encode, parse, parse as decode }; +declare const _default: {}; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/querystring.mjs b/worker/node_modules/unenv/dist/runtime/node/querystring.mjs new file mode 100644 index 0000000000000000000000000000000000000000..2deee5f51ec79eb932ea0eb578f184815ab2c3ef --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/querystring.mjs @@ -0,0 +1,711 @@ +import { encodeStr, hexTable, isHexTable } from "./internal/querystring/querystring.mjs"; +const unhexTable = new Int8Array([ + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + +0, + +1, + +2, + +3, + +4, + +5, + +6, + +7, + +8, + +9, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 10, + 11, + 12, + 13, + 14, + 15, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 10, + 11, + 12, + 13, + 14, + 15, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1 +]); +/** +* A safe fast alternative to decodeURIComponent +* @param {string} s +* @param {boolean} decodeSpaces +* @returns {string} +*/ +function unescapeBuffer(s, decodeSpaces) { + const out = globalThis.Buffer.allocUnsafe(s.length); + let index = 0; + let outIndex = 0; + let currentChar; + let nextChar; + let hexHigh; + let hexLow; + const maxLength = s.length - 2; + let hasHex = false; + while (index < s.length) { + currentChar = String.prototype.charCodeAt.call(s, index); + if (currentChar === 43 && decodeSpaces) { + out[outIndex++] = 32; + index++; + continue; + } + if (currentChar === 37 && index < maxLength) { + currentChar = String.prototype.charCodeAt.call(s, ++index); + hexHigh = unhexTable[currentChar]; + if (hexHigh >= 0) { + nextChar = String.prototype.charCodeAt.call(s, ++index); + hexLow = unhexTable[nextChar]; + if (hexLow >= 0) { + hasHex = true; + currentChar = hexHigh * 16 + hexLow; + } else { + out[outIndex++] = 37; + index--; + } + } else { + out[outIndex++] = 37; + continue; + } + } + out[outIndex++] = currentChar; + index++; + } + return hasHex ? out.slice(0, outIndex) : out; +} +/** +* @param {string} s +* @param {boolean} decodeSpaces +* @returns {string} +*/ +function qsUnescape(s, decodeSpaces) { + try { + return decodeURIComponent(s); + } catch { + return unescapeBuffer(s, decodeSpaces).toString(); + } +} +const noEscape = new Int8Array([ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 0, + 0, + 1, + 1, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 1, + 0 +]); +/** +* QueryString.escape() replaces encodeURIComponent() +* @see https://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3.4 +* @param {any} str +* @returns {string} +*/ +function qsEscape(str) { + if (typeof str !== "string") { + if (typeof str === "object") str = String(str); + else { + str += ""; + } + } + return encodeStr(str, noEscape, hexTable); +} +/** +* @param {string | number | bigint | boolean | symbol | undefined | null} v +* @returns {string} +*/ +function stringifyPrimitive(v) { + if (typeof v === "string") return v; + if (typeof v === "number" && Number.isFinite(v)) return "" + v; + if (typeof v === "bigint") return "" + v; + if (typeof v === "boolean") return v ? "true" : "false"; + return ""; +} +/** +* @param {string | number | bigint | boolean} v +* @param {(v: string) => string} encode +* @returns {string} +*/ +function encodeStringified(v, encode) { + if (typeof v === "string") return v.length > 0 ? encode(v) : ""; + if (typeof v === "number" && Number.isFinite(v)) { + return Math.abs(v) < 1e21 ? "" + v : encode("" + v); + } + if (typeof v === "bigint") return "" + v; + if (typeof v === "boolean") return v ? "true" : "false"; + return ""; +} +/** +* @param {string | number | boolean | null} v +* @param {(v: string) => string} encode +* @returns {string} +*/ +function encodeStringifiedCustom(v, encode) { + return encode(stringifyPrimitive(v)); +} +/** +* @param {Record | null>} obj +* @param {string} [sep] +* @param {string} [eq] +* @param {{ encodeURIComponent?: (v: string) => string }} [options] +* @returns {string} +*/ +function stringify(obj, sep, eq, options) { + sep = sep || "&"; + eq = eq || "="; + let encode = qsEscape; + if (options && typeof options.encodeURIComponent === "function") { + encode = options.encodeURIComponent; + } + const convert = encode === qsEscape ? encodeStringified : encodeStringifiedCustom; + if (obj !== null && typeof obj === "object") { + const keys = Object.keys(obj); + const len = keys.length; + let fields = ""; + for (let i = 0; i < len; ++i) { + const k = keys[i]; + const v = obj[k]; + let ks = convert(k, encode); + ks += eq; + if (Array.isArray(v)) { + const vlen = v.length; + if (vlen === 0) continue; + if (fields) fields += sep; + for (let j = 0; j < vlen; ++j) { + if (j) fields += sep; + fields += ks; + fields += convert(v[j], encode); + } + } else { + if (fields) fields += sep; + fields += ks; + fields += convert(v, encode); + } + } + return fields; + } + return ""; +} +/** +* @param {string} str +* @returns {number[]} +*/ +function charCodes(str) { + if (str.length === 0) return []; + if (str.length === 1) return [String.prototype.charCodeAt.call(str, 0)]; + const ret = Array.from({ length: str.length }); + for (let i = 0; i < str.length; ++i) ret[i] = String.prototype.charCodeAt.call(str, i); + return ret; +} +const defSepCodes = [38]; +const defEqCodes = [61]; +function addKeyVal(obj, key, value, keyEncoded, valEncoded, decode) { + if (key.length > 0 && keyEncoded) key = decodeStr(key, decode); + if (value.length > 0 && valEncoded) value = decodeStr(value, decode); + if (obj[key] === undefined) { + obj[key] = value; + } else { + const curValue = obj[key]; + if (curValue.pop) curValue[curValue.length] = value; + else obj[key] = [curValue, value]; + } +} +/** +* Parse a key/val string. +* @param {string} qs +* @param {string} sep +* @param {string} eq +* @param {{ +* maxKeys?: number; +* decodeURIComponent?(v: string): string; +* }} [options] +* @returns {Record} +*/ +function parse(qs, sep, eq, options) { + const obj = { __proto__: null }; + if (typeof qs !== "string" || qs.length === 0) { + return obj; + } + const sepCodes = sep ? charCodes(String(sep)) : defSepCodes; + const eqCodes = eq ? charCodes(String(eq)) : defEqCodes; + const sepLen = sepCodes.length; + const eqLen = eqCodes.length; + let pairs = 1e3; + if (options && typeof options.maxKeys === "number") { + pairs = options.maxKeys > 0 ? options.maxKeys : -1; + } + let decode = qsUnescape; + if (options && typeof options.decodeURIComponent === "function") { + decode = options.decodeURIComponent; + } + const customDecode = decode !== qsUnescape; + let lastPos = 0; + let sepIdx = 0; + let eqIdx = 0; + let key = ""; + let value = ""; + let keyEncoded = customDecode; + let valEncoded = customDecode; + const plusChar = customDecode ? "%20" : " "; + let encodeCheck = 0; + for (let i = 0; i < qs.length; ++i) { + const code = String.prototype.charCodeAt.call(qs, i); + if (code === sepCodes[sepIdx]) { + if (++sepIdx === sepLen) { + const end = i - sepIdx + 1; + if (eqIdx < eqLen) { + if (lastPos < end) { + key += String.prototype.slice.call(qs, lastPos, end); + } else if (key.length === 0) { + if (--pairs === 0) return obj; + lastPos = i + 1; + sepIdx = eqIdx = 0; + continue; + } + } else if (lastPos < end) { + value += String.prototype.slice.call(qs, lastPos, end); + } + addKeyVal(obj, key, value, keyEncoded, valEncoded, decode); + if (--pairs === 0) return obj; + keyEncoded = valEncoded = customDecode; + key = value = ""; + encodeCheck = 0; + lastPos = i + 1; + sepIdx = eqIdx = 0; + } + } else { + sepIdx = 0; + if (eqIdx < eqLen) { + if (code === eqCodes[eqIdx]) { + if (++eqIdx === eqLen) { + const end = i - eqIdx + 1; + if (lastPos < end) key += String.prototype.slice.call(qs, lastPos, end); + encodeCheck = 0; + lastPos = i + 1; + } + continue; + } else { + eqIdx = 0; + if (!keyEncoded) { + if (code === 37) { + encodeCheck = 1; + continue; + } else if (encodeCheck > 0) { + if (isHexTable[code] === 1) { + if (++encodeCheck === 3) keyEncoded = true; + continue; + } else { + encodeCheck = 0; + } + } + } + } + if (code === 43) { + if (lastPos < i) key += String.prototype.slice.call(qs, lastPos, i); + key += plusChar; + lastPos = i + 1; + continue; + } + } + if (code === 43) { + if (lastPos < i) value += String.prototype.slice.call(qs, lastPos, i); + value += plusChar; + lastPos = i + 1; + } else if (!valEncoded) { + if (code === 37) { + encodeCheck = 1; + } else if (encodeCheck > 0) { + if (isHexTable[code] === 1) { + if (++encodeCheck === 3) valEncoded = true; + } else { + encodeCheck = 0; + } + } + } + } + } + if (lastPos < qs.length) { + if (eqIdx < eqLen) key += String.prototype.slice.call(qs, lastPos); + else if (sepIdx < sepLen) value += String.prototype.slice.call(qs, lastPos); + } else if (eqIdx === 0 && key.length === 0) { + return obj; + } + addKeyVal(obj, key, value, keyEncoded, valEncoded, decode); + return obj; +} +/** +* V8 does not optimize functions with try-catch blocks, so we isolate them here +* to minimize the damage (Note: no longer true as of V8 5.4 -- but still will +* not be inlined). +* @param {string} s +* @param {(v: string) => string} decoder +* @returns {string} +*/ +function decodeStr(s, decoder) { + try { + return decoder(s); + } catch { + return qsUnescape(s, true); + } +} +export { unescapeBuffer, qsUnescape as unescape, qsEscape as escape, stringify, stringify as encode, parse, parse as decode }; +export default { + unescapeBuffer, + unescape: qsUnescape, + escape: qsEscape, + stringify, + encode: stringify, + parse, + decode: parse +}; diff --git a/worker/node_modules/unenv/dist/runtime/node/readline.d.mts b/worker/node_modules/unenv/dist/runtime/node/readline.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..d532b4473e3e0894d6edfb16d6d08e6e8920ddfb --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/readline.d.mts @@ -0,0 +1,12 @@ +import type nodeReadline from "node:readline"; +import promises from "node:readline/promises"; +export { promises }; +export { Interface } from "./internal/readline/interface.mjs"; +export declare const clearLine: typeof nodeReadline.clearLine; +export declare const clearScreenDown: typeof nodeReadline.clearScreenDown; +export declare const createInterface: typeof nodeReadline.createInterface; +export declare const cursorTo: typeof nodeReadline.cursorTo; +export declare const emitKeypressEvents: typeof nodeReadline.emitKeypressEvents; +export declare const moveCursor: typeof nodeReadline.moveCursor; +declare const _default: {}; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/readline.mjs b/worker/node_modules/unenv/dist/runtime/node/readline.mjs new file mode 100644 index 0000000000000000000000000000000000000000..df8d9321c695dd213fcc9987402e2c8ad3ee9c53 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/readline.mjs @@ -0,0 +1,21 @@ +import noop from "../mock/noop.mjs"; +import promises from "node:readline/promises"; +import { Interface } from "./internal/readline/interface.mjs"; +export { promises }; +export { Interface } from "./internal/readline/interface.mjs"; +export const clearLine = () => false; +export const clearScreenDown = () => false; +export const createInterface = () => new Interface(); +export const cursorTo = () => false; +export const emitKeypressEvents = noop; +export const moveCursor = () => false; +export default { + clearLine, + clearScreenDown, + createInterface, + cursorTo, + emitKeypressEvents, + moveCursor, + Interface, + promises +}; diff --git a/worker/node_modules/unenv/dist/runtime/node/readline/promises.d.mts b/worker/node_modules/unenv/dist/runtime/node/readline/promises.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..bed206c148b119dc77429d43675867033c05daeb --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/readline/promises.d.mts @@ -0,0 +1,6 @@ +import type nodeReadline from "node:readline/promises"; +export { Interface } from "../internal/readline/promises/interface.mjs"; +export { Readline } from "../internal/readline/promises/readline.mjs"; +export declare const createInterface: typeof nodeReadline.createInterface; +declare const _default: typeof nodeReadline; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/readline/promises.mjs b/worker/node_modules/unenv/dist/runtime/node/readline/promises.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7d47443ca923ffb20720693df72fd610a808d966 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/readline/promises.mjs @@ -0,0 +1,10 @@ +import { Interface } from "../internal/readline/promises/interface.mjs"; +import { Readline } from "../internal/readline/promises/readline.mjs"; +export { Interface } from "../internal/readline/promises/interface.mjs"; +export { Readline } from "../internal/readline/promises/readline.mjs"; +export const createInterface = () => new Interface(); +export default { + Interface, + Readline, + createInterface +}; diff --git a/worker/node_modules/unenv/dist/runtime/node/repl.d.mts b/worker/node_modules/unenv/dist/runtime/node/repl.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..934c3260516038f03a537335f459c7206d58d672 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/repl.d.mts @@ -0,0 +1,10 @@ +export declare const writer: unknown; +export declare const start: unknown; +export declare const Recoverable: unknown; +export declare const REPLServer: unknown; +export declare const REPL_MODE_SLOPPY: unique symbol; +export declare const REPL_MODE_STRICT: unique symbol; +export declare const builtinModules: unknown; +export declare const _builtinLibs: unknown; +declare const _default: {}; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/repl.mjs b/worker/node_modules/unenv/dist/runtime/node/repl.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c0feb013dbb26c7c90d521544b1b2cec31b4de11 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/repl.mjs @@ -0,0 +1,20 @@ +import { builtinModules as _builtinModules } from "node:module"; +import { notImplemented, notImplementedClass } from "../_internal/utils.mjs"; +export const writer = /*@__PURE__*/ notImplementedClass("repl.writer"); +export const start = /*@__PURE__*/ notImplemented("repl.start"); +export const Recoverable = /*@__PURE__*/ notImplementedClass("repl.Recoverable"); +export const REPLServer = /*@__PURE__*/ notImplementedClass("repl.REPLServer"); +export const REPL_MODE_SLOPPY = /*@__PURE__*/ Symbol("repl-sloppy"); +export const REPL_MODE_STRICT = /*@__PURE__*/ Symbol("repl-strict"); +export const builtinModules = /*@__PURE__*/ _builtinModules.filter((m) => m[0] !== "_"); +export const _builtinLibs = builtinModules; +export default { + writer, + start, + Recoverable, + REPLServer, + builtinModules, + _builtinLibs, + REPL_MODE_SLOPPY, + REPL_MODE_STRICT +}; diff --git a/worker/node_modules/unenv/dist/runtime/node/stream.d.mts b/worker/node_modules/unenv/dist/runtime/node/stream.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..134bf9dac8eb02ccddc7b2881ca4237164b74a5b --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/stream.d.mts @@ -0,0 +1,41 @@ +import type nodeStream from "node:stream"; +import promises from "node:stream/promises"; +export { promises }; +export { Readable } from "./internal/stream/readable.mjs"; +export { Writable } from "./internal/stream/writable.mjs"; +export { Duplex } from "./internal/stream/duplex.mjs"; +export { Transform } from "./internal/stream/transform.mjs"; +export declare const Stream: nodeStream.Stream; +export declare const PassThrough: nodeStream.PassThrough; +export declare const pipeline: any; +export declare const finished: any; +export declare const addAbortSignal: unknown; +export declare const isDisturbed: unknown; +export declare const isReadable: unknown; +export declare const compose: unknown; +export declare const isErrored: unknown; +export declare const destroy: unknown; +export declare const _isUint8Array: unknown; +export declare const _uint8ArrayToBuffer: unknown; +export declare const _isArrayBufferView: unknown; +export declare const duplexPair: unknown; +export declare const getDefaultHighWaterMark: unknown; +export declare const isDestroyed: unknown; +export declare const isWritable: unknown; +export declare const setDefaultHighWaterMark: unknown; +declare const _default: typeof nodeStream & { + isDisturbed: any + isReadable: any + compose: any + isErrored: any + destroy: any + _isUint8Array: any + _uint8ArrayToBuffer: any + _isArrayBufferView: any + duplexPair: any + getDefaultHighWaterMark: any + isDestroyed: any + isWritable: any + setDefaultHighWaterMark: any +}; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/stream.mjs b/worker/node_modules/unenv/dist/runtime/node/stream.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b67f1e2e6ecf9dc6dde795fdddc43d99ad5456cf --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/stream.mjs @@ -0,0 +1,54 @@ +import { notImplemented, notImplementedClass } from "../_internal/utils.mjs"; +import { Readable } from "./internal/stream/readable.mjs"; +import { Writable } from "./internal/stream/writable.mjs"; +import { Duplex } from "./internal/stream/duplex.mjs"; +import { Transform } from "./internal/stream/transform.mjs"; +import promises from "node:stream/promises"; +export { promises }; +export { Readable } from "./internal/stream/readable.mjs"; +export { Writable } from "./internal/stream/writable.mjs"; +export { Duplex } from "./internal/stream/duplex.mjs"; +export { Transform } from "./internal/stream/transform.mjs"; +export const Stream = /*@__PURE__*/ notImplementedClass("stream.Stream"); +export const PassThrough = /*@__PURE__*/ notImplementedClass("PassThrough"); +export const pipeline = /*@__PURE__*/ notImplemented("stream.pipeline"); +export const finished = /*@__PURE__*/ notImplemented("stream.finished"); +export const addAbortSignal = /*@__PURE__*/ notImplemented("stream.addAbortSignal"); +export const isDisturbed = /*@__PURE__*/ notImplemented("stream.isDisturbed"); +export const isReadable = /*@__PURE__*/ notImplemented("stream.isReadable"); +export const compose = /*@__PURE__*/ notImplemented("stream.compose"); +export const isErrored = /*@__PURE__*/ notImplemented("stream.isErrored"); +export const destroy = /*@__PURE__*/ notImplemented("stream.destroy"); +export const _isUint8Array = /*@__PURE__*/ notImplemented("stream._isUint8Array"); +export const _uint8ArrayToBuffer = /*@__PURE__*/ notImplemented("stream._uint8ArrayToBuffer"); +export const _isArrayBufferView = /*@__PURE__*/ notImplemented("stream._isArrayBufferView"); +export const duplexPair = /*@__PURE__*/ notImplemented("stream.duplexPair"); +export const getDefaultHighWaterMark = /*@__PURE__*/ notImplemented("stream.getDefaultHighWaterMark"); +export const isDestroyed = /*@__PURE__*/ notImplemented("stream.isDestroyed"); +export const isWritable = /*@__PURE__*/ notImplemented("stream.isWritable"); +export const setDefaultHighWaterMark = /*@__PURE__*/ notImplemented("stream.setDefaultHighWaterMark"); +export default { + Readable, + Writable, + Duplex, + Transform, + Stream, + PassThrough, + pipeline, + finished, + addAbortSignal, + promises, + isDisturbed, + isReadable, + compose, + _uint8ArrayToBuffer, + isErrored, + destroy, + _isUint8Array, + _isArrayBufferView, + duplexPair, + getDefaultHighWaterMark, + isDestroyed, + isWritable, + setDefaultHighWaterMark +}; diff --git a/worker/node_modules/unenv/dist/runtime/node/stream/consumers.d.mts b/worker/node_modules/unenv/dist/runtime/node/stream/consumers.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..a5fb85612c007b7b66c3a396013df270ed7b0018 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/stream/consumers.d.mts @@ -0,0 +1,7 @@ +export declare const arrayBuffer: unknown; +export declare const blob: unknown; +export declare const buffer: unknown; +export declare const text: unknown; +export declare const json: unknown; +declare const _default: {}; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/stream/consumers.mjs b/worker/node_modules/unenv/dist/runtime/node/stream/consumers.mjs new file mode 100644 index 0000000000000000000000000000000000000000..db4001be7c6ff405af53dd69f30d5232bebf8c1f --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/stream/consumers.mjs @@ -0,0 +1,13 @@ +import { notImplemented } from "../../_internal/utils.mjs"; +export const arrayBuffer = /*@__PURE__*/ notImplemented("stream.consumers.arrayBuffer"); +export const blob = /*@__PURE__*/ notImplemented("stream.consumers.blob"); +export const buffer = /*@__PURE__*/ notImplemented("stream.consumers.buffer"); +export const text = /*@__PURE__*/ notImplemented("stream.consumers.text"); +export const json = /*@__PURE__*/ notImplemented("stream.consumers.json"); +export default { + arrayBuffer, + blob, + buffer, + text, + json +}; diff --git a/worker/node_modules/unenv/dist/runtime/node/stream/promises.d.mts b/worker/node_modules/unenv/dist/runtime/node/stream/promises.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..f05e2400205f551dc02bab4b8195546b6d0f6681 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/stream/promises.d.mts @@ -0,0 +1,4 @@ +export declare const finished: unknown; +export declare const pipeline: unknown; +declare const _default: {}; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/stream/promises.mjs b/worker/node_modules/unenv/dist/runtime/node/stream/promises.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7cdc0cc60ef70deb6299c02cf5698fc1c67dc6f2 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/stream/promises.mjs @@ -0,0 +1,7 @@ +import { notImplemented } from "../../_internal/utils.mjs"; +export const finished = /*@__PURE__*/ notImplemented("stream.promises.finished"); +export const pipeline = /*@__PURE__*/ notImplemented("stream.promises.pipeline"); +export default { + finished, + pipeline +}; diff --git a/worker/node_modules/unenv/dist/runtime/node/stream/web.d.mts b/worker/node_modules/unenv/dist/runtime/node/stream/web.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..62868edc97dd14726d120ca3ae6a3d427b5176c5 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/stream/web.d.mts @@ -0,0 +1,20 @@ +import type nodeStreamWeb from "node:stream/web"; +export declare const ReadableStream: unknown; +export declare const ReadableStreamDefaultReader: unknown; +export declare const ReadableStreamBYOBReader: unknown; +export declare const ReadableStreamBYOBRequest: unknown; +export declare const ReadableByteStreamController: unknown; +export declare const ReadableStreamDefaultController: unknown; +export declare const TransformStream: unknown; +export declare const TransformStreamDefaultController: unknown; +export declare const WritableStream: unknown; +export declare const WritableStreamDefaultWriter: unknown; +export declare const WritableStreamDefaultController: unknown; +export declare const ByteLengthQueuingStrategy: unknown; +export declare const CountQueuingStrategy: unknown; +export declare const TextEncoderStream: unknown; +export declare const TextDecoderStream: unknown; +export declare const DecompressionStream: unknown; +export declare const CompressionStream: unknown; +declare const _default: typeof nodeStreamWeb; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/stream/web.mjs b/worker/node_modules/unenv/dist/runtime/node/stream/web.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b952f8db8044fbbd817e438402d7ef5e5fb3ee98 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/stream/web.mjs @@ -0,0 +1,37 @@ +import { notImplemented } from "../../_internal/utils.mjs"; +export const ReadableStream = globalThis.ReadableStream || /*@__PURE__*/ notImplemented("stream.web.ReadableStream"); +export const ReadableStreamDefaultReader = globalThis.ReadableStreamDefaultReader || /*@__PURE__*/ notImplemented("stream.web.ReadableStreamDefaultReader"); +export const ReadableStreamBYOBReader = globalThis.ReadableStreamBYOBReader || /*@__PURE__*/ notImplemented("stream.web.ReadableStreamBYOBReader"); +export const ReadableStreamBYOBRequest = globalThis.ReadableStreamBYOBRequest || /*@__PURE__*/ notImplemented("stream.web.ReadableStreamBYOBRequest"); +export const ReadableByteStreamController = globalThis.ReadableByteStreamController || /*@__PURE__*/ notImplemented("stream.web.ReadableByteStreamController"); +export const ReadableStreamDefaultController = globalThis.ReadableStreamDefaultController || /*@__PURE__*/ notImplemented("stream.web.ReadableStreamDefaultController"); +export const TransformStream = globalThis.TransformStream || /*@__PURE__*/ notImplemented("stream.web.TransformStream"); +export const TransformStreamDefaultController = globalThis.TransformStreamDefaultController || /*@__PURE__*/ notImplemented("stream.web.TransformStreamDefaultController"); +export const WritableStream = globalThis.WritableStream || /*@__PURE__*/ notImplemented("stream.web.WritableStream"); +export const WritableStreamDefaultWriter = globalThis.WritableStreamDefaultWriter || /*@__PURE__*/ notImplemented("stream.web.WritableStreamDefaultWriter"); +export const WritableStreamDefaultController = globalThis.WritableStreamDefaultController || /*@__PURE__*/ notImplemented("stream.web.WritableStreamDefaultController"); +export const ByteLengthQueuingStrategy = globalThis.ByteLengthQueuingStrategy || /*@__PURE__*/ notImplemented("stream.web.ByteLengthQueuingStrategy"); +export const CountQueuingStrategy = globalThis.CountQueuingStrategy || /*@__PURE__*/ notImplemented("stream.web.CountQueuingStrategy"); +export const TextEncoderStream = globalThis.TextEncoderStream || /*@__PURE__*/ notImplemented("stream.web.TextEncoderStream"); +export const TextDecoderStream = globalThis.TextDecoderStream || /*@__PURE__*/ notImplemented("stream.web.TextDecoderStream"); +export const DecompressionStream = globalThis.DecompressionStream || /*@__PURE__*/ notImplemented("stream.web.DecompressionStream"); +export const CompressionStream = globalThis.DecompressionStream || /*@__PURE__*/ notImplemented("stream.web.CompressionStream"); +export default { + ReadableStream, + ReadableStreamDefaultReader, + ReadableStreamBYOBReader, + ReadableStreamBYOBRequest, + ReadableByteStreamController, + ReadableStreamDefaultController, + TransformStream, + TransformStreamDefaultController, + WritableStream, + WritableStreamDefaultWriter, + WritableStreamDefaultController, + ByteLengthQueuingStrategy, + CountQueuingStrategy, + TextEncoderStream, + TextDecoderStream, + DecompressionStream, + CompressionStream +}; diff --git a/worker/node_modules/unenv/dist/runtime/node/string_decoder.d.mts b/worker/node_modules/unenv/dist/runtime/node/string_decoder.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..4d4770761b3bc5f2da649de3ed7c9c2e43b09ba5 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/string_decoder.d.mts @@ -0,0 +1,4 @@ +import type nodeStringDecoder from "node:string_decoder"; +export declare const StringDecoder: typeof nodeStringDecoder.StringDecoder; +declare const _default: {}; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/string_decoder.mjs b/worker/node_modules/unenv/dist/runtime/node/string_decoder.mjs new file mode 100644 index 0000000000000000000000000000000000000000..70f2590bc8ea08846410d2754f7a80fc766e9dda --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/string_decoder.mjs @@ -0,0 +1,3 @@ +import { notImplementedClass } from "../_internal/utils.mjs"; +export const StringDecoder = globalThis.StringDecoder || /*@__PURE__*/ notImplementedClass("string_decoder.StringDecoder"); +export default { StringDecoder }; diff --git a/worker/node_modules/unenv/dist/runtime/node/sys.d.mts b/worker/node_modules/unenv/dist/runtime/node/sys.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..a1097832fdabf27e25d8bb38ec2854e86fd6bd7b --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/sys.d.mts @@ -0,0 +1,2 @@ +export * from "./util.mjs"; +export { default } from "./util.mjs"; diff --git a/worker/node_modules/unenv/dist/runtime/node/sys.mjs b/worker/node_modules/unenv/dist/runtime/node/sys.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a1097832fdabf27e25d8bb38ec2854e86fd6bd7b --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/sys.mjs @@ -0,0 +1,2 @@ +export * from "./util.mjs"; +export { default } from "./util.mjs"; diff --git a/worker/node_modules/unenv/dist/runtime/node/timers.d.mts b/worker/node_modules/unenv/dist/runtime/node/timers.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..3cdc71989d83c070e521c2b81b67b06fe6553084 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/timers.d.mts @@ -0,0 +1,15 @@ +import type nodeTimers from "node:timers"; +import promises from "node:timers/promises"; +export { promises }; +export declare const clearImmediate: typeof nodeTimers.clearImmediate; +export declare const clearInterval: typeof nodeTimers.clearInterval; +export declare const clearTimeout: typeof nodeTimers.clearTimeout; +export declare const setImmediate: typeof nodeTimers.setImmediate; +export declare const setTimeout: typeof nodeTimers.setTimeout; +export declare const setInterval: typeof nodeTimers.setInterval; +export declare const active: unknown; +export declare const _unrefActive: unknown; +export declare const enroll: unknown; +export declare const unenroll: unknown; +declare const _default: {}; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/timers.mjs b/worker/node_modules/unenv/dist/runtime/node/timers.mjs new file mode 100644 index 0000000000000000000000000000000000000000..384af17719b15d2c85c1318b27d1aaa2ae96ad79 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/timers.mjs @@ -0,0 +1,32 @@ +import { notImplemented } from "../_internal/utils.mjs"; +import noop from "../mock/noop.mjs"; +import promises from "node:timers/promises"; +import { setTimeoutFallback } from "./internal/timers/set-timeout.mjs"; +import { setImmediateFallback, clearImmediateFallback } from "./internal/timers/set-immediate.mjs"; +import { setIntervalFallback } from "./internal/timers/set-interval.mjs"; +export { promises }; +export const clearImmediate = globalThis.clearImmediate?.bind(globalThis) || clearImmediateFallback; +export const clearInterval = globalThis.clearInterval?.bind(globalThis) || noop; +export const clearTimeout = globalThis.clearTimeout?.bind(globalThis) || noop; +export const setImmediate = globalThis.setImmediate?.bind(globalThis) || setImmediateFallback; +export const setTimeout = globalThis.setTimeout?.bind(globalThis) || setTimeoutFallback; +export const setInterval = globalThis.setInterval?.bind(globalThis) || setIntervalFallback; +export const active = function active(timeout) { + timeout?.refresh?.(); +}; +export const _unrefActive = active; +export const enroll = /*@__PURE__*/ notImplemented("timers.enroll"); +export const unenroll = /*@__PURE__*/ notImplemented("timers.unenroll"); +export default { + _unrefActive, + active, + clearImmediate, + clearInterval, + clearTimeout, + enroll, + promises, + setImmediate, + setInterval, + setTimeout, + unenroll +}; diff --git a/worker/node_modules/unenv/dist/runtime/node/timers/promises.d.mts b/worker/node_modules/unenv/dist/runtime/node/timers/promises.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..f5946cb58a278f26a9844f899f67f11ca0bb9453 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/timers/promises.d.mts @@ -0,0 +1,6 @@ +export { setTimeoutFallbackPromises as setTimeout } from "../internal/timers/set-timeout.mjs"; +export { setIntervalFallbackPromises as setInterval } from "../internal/timers/set-interval.mjs"; +export { setImmediateFallbackPromises as setImmediate } from "../internal/timers/set-immediate.mjs"; +export declare const scheduler: unknown; +declare const _default: {}; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/timers/promises.mjs b/worker/node_modules/unenv/dist/runtime/node/timers/promises.mjs new file mode 100644 index 0000000000000000000000000000000000000000..25d4606b2187dbb02235b67a29c028b8284ab1a4 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/timers/promises.mjs @@ -0,0 +1,14 @@ +import { Scheduler } from "../internal/timers/scheduler.mjs"; +import { setTimeoutFallbackPromises } from "../internal/timers/set-timeout.mjs"; +import { setIntervalFallbackPromises } from "../internal/timers/set-interval.mjs"; +import { setImmediateFallbackPromises } from "../internal/timers/set-immediate.mjs"; +export { setTimeoutFallbackPromises as setTimeout } from "../internal/timers/set-timeout.mjs"; +export { setIntervalFallbackPromises as setInterval } from "../internal/timers/set-interval.mjs"; +export { setImmediateFallbackPromises as setImmediate } from "../internal/timers/set-immediate.mjs"; +export const scheduler = new Scheduler(); +export default { + scheduler, + setImmediate: setImmediateFallbackPromises, + setInterval: setIntervalFallbackPromises, + setTimeout: setTimeoutFallbackPromises +}; diff --git a/worker/node_modules/unenv/dist/runtime/node/tls.d.mts b/worker/node_modules/unenv/dist/runtime/node/tls.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..54b7096ad5af058d6444fe8e259e1675b0a1d93d --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/tls.d.mts @@ -0,0 +1,15 @@ +import type nodeTls from "node:tls"; +export * from "./internal/tls/constants.mjs"; +export { TLSSocket } from "./internal/tls/tls-socket.mjs"; +export { Server } from "./internal/tls/server.mjs"; +export { SecureContext } from "./internal/tls/secure-context.mjs"; +export declare const connect: typeof nodeTls.connect; +export declare const createServer: typeof nodeTls.createServer; +export declare const checkServerIdentity: typeof nodeTls.checkServerIdentity; +export declare const convertALPNProtocols: unknown; +export declare const createSecureContext: typeof nodeTls.createSecureContext; +export declare const createSecurePair: typeof nodeTls.createSecurePair; +export declare const getCiphers: typeof nodeTls.getCiphers; +export declare const rootCertificates: typeof nodeTls.rootCertificates; +declare const _default: typeof nodeTls; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/tls.mjs b/worker/node_modules/unenv/dist/runtime/node/tls.mjs new file mode 100644 index 0000000000000000000000000000000000000000..635a83bb0f4cf43f8bbe1ce6155d53b7506bfc07 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/tls.mjs @@ -0,0 +1,40 @@ +import { notImplemented } from "../_internal/utils.mjs"; +import { TLSSocket } from "./internal/tls/tls-socket.mjs"; +import { Server } from "./internal/tls/server.mjs"; +import { SecureContext } from "./internal/tls/secure-context.mjs"; +import { CLIENT_RENEG_LIMIT, CLIENT_RENEG_WINDOW, DEFAULT_CIPHERS, DEFAULT_ECDH_CURVE, DEFAULT_MAX_VERSION, DEFAULT_MIN_VERSION } from "./internal/tls/constants.mjs"; +export * from "./internal/tls/constants.mjs"; +export { TLSSocket } from "./internal/tls/tls-socket.mjs"; +export { Server } from "./internal/tls/server.mjs"; +export { SecureContext } from "./internal/tls/secure-context.mjs"; +export const connect = function connect() { + return new TLSSocket(); +}; +export const createServer = function createServer() { + return new Server(); +}; +export const checkServerIdentity = /*@__PURE__*/ notImplemented("tls.checkServerIdentity"); +export const convertALPNProtocols = /*@__PURE__*/ notImplemented("tls.convertALPNProtocols"); +export const createSecureContext = /*@__PURE__*/ notImplemented("tls.createSecureContext"); +export const createSecurePair = /*@__PURE__*/ notImplemented("tls.createSecurePair"); +export const getCiphers = /*@__PURE__*/ notImplemented("tls.getCiphers"); +export const rootCertificates = []; +export default { + CLIENT_RENEG_LIMIT, + CLIENT_RENEG_WINDOW, + DEFAULT_CIPHERS, + DEFAULT_ECDH_CURVE, + DEFAULT_MAX_VERSION, + DEFAULT_MIN_VERSION, + SecureContext, + Server, + TLSSocket, + checkServerIdentity, + connect, + convertALPNProtocols, + createSecureContext, + createSecurePair, + createServer, + getCiphers, + rootCertificates +}; diff --git a/worker/node_modules/unenv/dist/runtime/node/trace_events.d.mts b/worker/node_modules/unenv/dist/runtime/node/trace_events.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..ef33222322d77b8ca913be1f80932df75a64db6a --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/trace_events.d.mts @@ -0,0 +1,5 @@ +import type nodeTraceEvents from "node:trace_events"; +export declare const createTracing: typeof nodeTraceEvents.createTracing; +export declare const getEnabledCategories: typeof nodeTraceEvents.getEnabledCategories; +declare const _default: {}; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/trace_events.mjs b/worker/node_modules/unenv/dist/runtime/node/trace_events.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a132abb9898a3a7b541dda21af935176d124689e --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/trace_events.mjs @@ -0,0 +1,9 @@ +import { Tracing } from "./internal/trace_events/tracing.mjs"; +export const createTracing = function() { + return new Tracing(); +}; +export const getEnabledCategories = () => ""; +export default { + createTracing, + getEnabledCategories +}; diff --git a/worker/node_modules/unenv/dist/runtime/node/tty.d.mts b/worker/node_modules/unenv/dist/runtime/node/tty.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..5026149f3be1b1af2cbebaf988b049942e48cc38 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/tty.d.mts @@ -0,0 +1,6 @@ +import type nodeTty from "node:tty"; +export { ReadStream } from "./internal/tty/read-stream.mjs"; +export { WriteStream } from "./internal/tty/write-stream.mjs"; +export declare const isatty: typeof nodeTty.isatty; +declare const _default: {}; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/tty.mjs b/worker/node_modules/unenv/dist/runtime/node/tty.mjs new file mode 100644 index 0000000000000000000000000000000000000000..cebfed5a999dce392a9ffbe28882dfd8350305ed --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/tty.mjs @@ -0,0 +1,12 @@ +import { ReadStream } from "./internal/tty/read-stream.mjs"; +import { WriteStream } from "./internal/tty/write-stream.mjs"; +export { ReadStream } from "./internal/tty/read-stream.mjs"; +export { WriteStream } from "./internal/tty/write-stream.mjs"; +export const isatty = function() { + return false; +}; +export default { + ReadStream, + WriteStream, + isatty +}; diff --git a/worker/node_modules/unenv/dist/runtime/node/url.d.mts b/worker/node_modules/unenv/dist/runtime/node/url.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..796e67f359aa65b897f03b9dfadde173581d8dc9 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/url.d.mts @@ -0,0 +1,36 @@ +import type nodeUrl from "node:url"; +import * as querystring from "node:querystring"; +import { fileURLToPath, urlToHttpOptions } from "./internal/url/url.mjs"; +declare class Url implements nodeUrl.Url { + auth: string | null; + hash: string | null; + host: string | null; + hostname: string | null; + href: string; + path: string | null; + pathname: string | null; + protocol: string | null; + search: string | null; + slashes: boolean | null; + port: string | null; + query: string | querystring.ParsedUrlQuery | null; + parse(url: string, parseQueryString?: boolean, slashesDenoteHost?: boolean); + format(); + resolve(relative: string); + resolveObject(relative: nodeUrl.Url); + parseHost(); +} +declare function urlParse(url: string | Url, parseQueryString?: boolean, slashesDenoteHost?: boolean): Url; +declare function urlFormat(urlObject: string | Url, options: nodeUrl.URLFormatOptions); +declare function urlResolve(source: string, relative: string); +declare function urlResolveObject(source: string, relative: nodeUrl.Url); +declare function pathToFileURL(path: string, options?: { + windows?: boolean +}); +declare const URL: unknown; +declare const URLSearchParams: unknown; +declare const domainToASCII: unknown; +declare const domainToUnicode: unknown; +export { Url, urlParse as parse, urlResolve as resolve, urlResolveObject as resolveObject, urlFormat as format, URL, URLSearchParams, domainToASCII, domainToUnicode, pathToFileURL, fileURLToPath, urlToHttpOptions }; +declare const _default: {}; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/url.mjs b/worker/node_modules/unenv/dist/runtime/node/url.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1de87c797f7e4fce58d9797a8473741e0519d00e --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/url.mjs @@ -0,0 +1,884 @@ +import * as querystring from "node:querystring"; +import * as punnycode from "./punycode.mjs"; +import { encodeStr, hexTable } from "./internal/querystring/querystring.mjs"; +import { spliceOne } from "./internal/url/util.mjs"; +import { ERR_INVALID_ARG_TYPE, ERR_INVALID_URL } from "./internal/url/errors.mjs"; +import { pathToFileURL as _pathToFileURL, fileURLToPath, unsafeProtocol, hostlessProtocol, slashedProtocol, urlToHttpOptions } from "./internal/url/url.mjs"; +import { CHAR_SPACE, CHAR_TAB, CHAR_CARRIAGE_RETURN, CHAR_LINE_FEED, CHAR_NO_BREAK_SPACE, CHAR_ZERO_WIDTH_NOBREAK_SPACE, CHAR_HASH, CHAR_FORWARD_SLASH, CHAR_LEFT_SQUARE_BRACKET, CHAR_RIGHT_SQUARE_BRACKET, CHAR_LEFT_ANGLE_BRACKET, CHAR_RIGHT_ANGLE_BRACKET, CHAR_LEFT_CURLY_BRACKET, CHAR_RIGHT_CURLY_BRACKET, CHAR_QUESTION_MARK, CHAR_DOUBLE_QUOTE, CHAR_SINGLE_QUOTE, CHAR_PERCENT, CHAR_SEMICOLON, CHAR_BACKWARD_SLASH, CHAR_CIRCUMFLEX_ACCENT, CHAR_GRAVE_ACCENT, CHAR_VERTICAL_LINE, CHAR_AT, CHAR_COLON } from "./internal/url/constants.mjs"; +class Url { + auth = null; + hash = null; + host = null; + hostname = null; + href = null; + path = null; + pathname = null; + protocol = null; + search = null; + slashes = null; + port = null; + query = null; + parse(url, parseQueryString, slashesDenoteHost) { + if (typeof url !== "string") { + throw new ERR_INVALID_ARG_TYPE("url", "string", url); + } + let hasHash = false; + let hasAt = false; + let start = -1; + let end = -1; + let rest = ""; + let lastPos = 0; + for (let i = 0, inWs = false, split = false; i < url.length; ++i) { + const code = url.charCodeAt(i); + const isWs = code < 33 || code === CHAR_NO_BREAK_SPACE || code === CHAR_ZERO_WIDTH_NOBREAK_SPACE; + if (start === -1) { + if (isWs) continue; + lastPos = start = i; + } else if (inWs) { + if (!isWs) { + end = -1; + inWs = false; + } + } else if (isWs) { + end = i; + inWs = true; + } + if (!split) { + switch (code) { + case CHAR_AT: + hasAt = true; + break; + case CHAR_HASH: hasHash = true; + case CHAR_QUESTION_MARK: + split = true; + break; + case CHAR_BACKWARD_SLASH: + if (i - lastPos > 0) rest += url.slice(lastPos, i); + rest += "/"; + lastPos = i + 1; + break; + } + } else if (!hasHash && code === CHAR_HASH) { + hasHash = true; + } + } + if (start !== -1) { + if (lastPos === start) { + if (end === -1) { + if (start === 0) rest = url; + else rest = url.slice(start); + } else { + rest = url.slice(start, end); + } + } else if (end === -1 && lastPos < url.length) { + rest += url.slice(lastPos); + } else if (end !== -1 && lastPos < end) { + rest += url.slice(lastPos, end); + } + } + if (!slashesDenoteHost && !hasHash && !hasAt) { + const simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.path = rest; + this.href = rest; + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + if (parseQueryString) { + this.query = querystring.parse(this.search.slice(1)); + } else { + this.query = this.search.slice(1); + } + } else if (parseQueryString) { + this.search = null; + this.query = { __proto__: null }; + } + return this; + } + } + const protoMatch = protocolPattern.exec(rest); + let proto, lowerProto; + if (protoMatch) { + proto = protoMatch[0]; + lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.slice(proto.length); + } + let slashes; + if (slashesDenoteHost || proto || hostPattern.test(rest)) { + slashes = rest.charCodeAt(0) === CHAR_FORWARD_SLASH && rest.charCodeAt(1) === CHAR_FORWARD_SLASH; + if (slashes && !(proto && hostlessProtocol.has(lowerProto))) { + rest = rest.slice(2); + this.slashes = true; + } + } + if (!hostlessProtocol.has(lowerProto) && (slashes || proto && !slashedProtocol.has(proto))) { + let hostEnd = -1; + let atSign = -1; + let nonHost = -1; + for (let i = 0; i < rest.length; ++i) { + switch (rest.charCodeAt(i)) { + case CHAR_TAB: + case CHAR_LINE_FEED: + case CHAR_CARRIAGE_RETURN: + rest = rest.slice(0, i) + rest.slice(i + 1); + i -= 1; + break; + case CHAR_SPACE: + case CHAR_DOUBLE_QUOTE: + case CHAR_PERCENT: + case CHAR_SINGLE_QUOTE: + case CHAR_SEMICOLON: + case CHAR_LEFT_ANGLE_BRACKET: + case CHAR_RIGHT_ANGLE_BRACKET: + case CHAR_BACKWARD_SLASH: + case CHAR_CIRCUMFLEX_ACCENT: + case CHAR_GRAVE_ACCENT: + case CHAR_LEFT_CURLY_BRACKET: + case CHAR_VERTICAL_LINE: + case CHAR_RIGHT_CURLY_BRACKET: + if (nonHost === -1) nonHost = i; + break; + case CHAR_HASH: + case CHAR_FORWARD_SLASH: + case CHAR_QUESTION_MARK: + if (nonHost === -1) nonHost = i; + hostEnd = i; + break; + case CHAR_AT: + atSign = i; + nonHost = -1; + break; + } + if (hostEnd !== -1) break; + } + start = 0; + if (atSign !== -1) { + this.auth = decodeURIComponent(rest.slice(0, atSign)); + start = atSign + 1; + } + if (nonHost === -1) { + this.host = rest.slice(start); + rest = ""; + } else { + this.host = rest.slice(start, nonHost); + rest = rest.slice(nonHost); + } + this.parseHost(); + if (typeof this.hostname !== "string") this.hostname = ""; + const hostname = this.hostname; + const ipv6Hostname = isIpv6Hostname(hostname); + if (!ipv6Hostname) { + rest = getHostname(this, rest, hostname, url); + } + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ""; + } else { + this.hostname = this.hostname.toLowerCase(); + } + if (this.hostname !== "") { + if (ipv6Hostname) { + if (forbiddenHostCharsIpv6.test(this.hostname)) { + throw new ERR_INVALID_URL(url); + } + } else { + this.hostname = punnycode.toASCII(this.hostname); + if (this.hostname === "" || forbiddenHostChars.test(this.hostname)) { + throw new ERR_INVALID_URL(url); + } + } + } + const p = this.port ? ":" + this.port : ""; + const h = this.hostname || ""; + this.host = h + p; + if (ipv6Hostname) { + this.hostname = this.hostname.slice(1, -1); + if (rest[0] !== "/") { + rest = "/" + rest; + } + } + } + if (!unsafeProtocol.has(lowerProto)) { + rest = autoEscapeStr(rest); + } + let questionIdx = -1; + let hashIdx = -1; + for (let i = 0; i < rest.length; ++i) { + const code = rest.charCodeAt(i); + if (code === CHAR_HASH) { + this.hash = rest.slice(i); + hashIdx = i; + break; + } else if (code === CHAR_QUESTION_MARK && questionIdx === -1) { + questionIdx = i; + } + } + if (questionIdx !== -1) { + if (hashIdx === -1) { + this.search = rest.slice(questionIdx); + this.query = rest.slice(questionIdx + 1); + } else { + this.search = rest.slice(questionIdx, hashIdx); + this.query = rest.slice(questionIdx + 1, hashIdx); + } + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + } else if (parseQueryString) { + this.search = null; + this.query = { __proto__: null }; + } + const useQuestionIdx = questionIdx !== -1 && (hashIdx === -1 || questionIdx < hashIdx); + const firstIdx = useQuestionIdx ? questionIdx : hashIdx; + if (firstIdx === -1) { + if (rest.length > 0) this.pathname = rest; + } else if (firstIdx > 0) { + this.pathname = rest.slice(0, firstIdx); + } + if (slashedProtocol.has(lowerProto) && this.hostname && !this.pathname) { + this.pathname = "/"; + } + if (this.pathname || this.search) { + const p = this.pathname || ""; + const s = this.search || ""; + this.path = p + s; + } + this.href = this.format(); + return this; + } + format() { + let auth = this.auth || ""; + if (auth) { + auth = encodeStr(auth, noEscapeAuth, hexTable); + auth += "@"; + } + let protocol = this.protocol || ""; + let pathname = this.pathname || ""; + let hash = this.hash || ""; + let host = ""; + let query = ""; + if (this.host) { + host = auth + this.host; + } else if (this.hostname) { + host = auth + (this.hostname.includes(":") && !isIpv6Hostname(this.hostname) ? "[" + this.hostname + "]" : this.hostname); + if (this.port) { + host += ":" + this.port; + } + } + if (this.query !== null && typeof this.query === "object") { + query = querystring.stringify(this.query); + } + let search = this.search || query && "?" + query || ""; + if (protocol && protocol.charCodeAt(protocol.length - 1) !== 58) protocol += ":"; + let newPathname = ""; + let lastPos = 0; + for (let i = 0; i < pathname.length; ++i) { + switch (pathname.charCodeAt(i)) { + case CHAR_HASH: + if (i - lastPos > 0) newPathname += pathname.slice(lastPos, i); + newPathname += "%23"; + lastPos = i + 1; + break; + case CHAR_QUESTION_MARK: + if (i - lastPos > 0) newPathname += pathname.slice(lastPos, i); + newPathname += "%3F"; + lastPos = i + 1; + break; + } + } + if (lastPos > 0) { + if (lastPos === pathname.length) { + pathname = newPathname; + } else { + pathname = newPathname + pathname.slice(lastPos); + } + } + if (this.slashes || slashedProtocol.has(protocol)) { + if (this.slashes || host) { + if (pathname && pathname.charCodeAt(0) !== CHAR_FORWARD_SLASH) pathname = "/" + pathname; + host = "//" + host; + } else if (protocol.length >= 4 && protocol.charCodeAt(0) === 102 && protocol.charCodeAt(1) === 105 && protocol.charCodeAt(2) === 108 && protocol.charCodeAt(3) === 101) { + host = "//"; + } + } + search = search.replace(/#/g, "%23"); + if (hash && hash.charCodeAt(0) !== CHAR_HASH) hash = "#" + hash; + if (search && search.charCodeAt(0) !== CHAR_QUESTION_MARK) search = "?" + search; + return protocol + host + pathname + search + hash; + } + resolve(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); + } + resolveObject(relative) { + if (typeof relative === "string") { + const rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + const result = new Url(); + Object.assign(result, this); + result.hash = relative.hash; + if (relative.href === "") { + result.href = result.format(); + return result; + } + if (relative.slashes && !relative.protocol) { + const relativeWithoutProtocol = Object.keys(relative).reduce((acc, key) => { + if (key !== "protocol") { + acc[key] = relative[key]; + } + return acc; + }, {}); + Object.assign(result, relativeWithoutProtocol); + if (slashedProtocol.has(result.protocol) && result.hostname && !result.pathname) { + result.path = result.pathname = "/"; + } + result.href = result.format(); + return result; + } + if (relative.protocol && relative.protocol !== result.protocol) { + if (!slashedProtocol.has(relative.protocol)) { + Object.assign(result, relative); + result.href = result.format(); + return result; + } + result.protocol = relative.protocol; + if (!relative.host && !/^file:?$/.test(relative.protocol) && !hostlessProtocol.has(relative.protocol)) { + const relPath = (relative.pathname || "").split("/"); + while (relPath.length > 0 && !(relative.host = relPath.shift())); + if (!relative.host) relative.host = ""; + if (!relative.hostname) relative.hostname = ""; + if (relPath[0] !== "") relPath.unshift(""); + if (relPath.length < 2) relPath.unshift(""); + result.pathname = relPath.join("/"); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ""; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + if (result.pathname || result.search) { + const p = result.pathname || ""; + const s = result.search || ""; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + const isSourceAbs = result.pathname && result.pathname.charAt(0) === "/"; + const isRelAbs = relative.host || relative.pathname && relative.pathname.charAt(0) === "/"; + let mustEndAbs = isRelAbs || isSourceAbs || result.host && relative.pathname; + const removeAllDots = mustEndAbs; + let srcPath = result.pathname && result.pathname.split("/") || []; + const relPath = relative.pathname && relative.pathname.split("/") || []; + const noLeadingSlashes = result.protocol && !slashedProtocol.has(result.protocol); + if (noLeadingSlashes) { + result.hostname = ""; + result.port = null; + if (result.host) { + if (srcPath[0] === "") srcPath[0] = result.host; + else srcPath.unshift(result.host); + } + result.host = ""; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + result.auth = null; + if (relative.host) { + if (relPath[0] === "") relPath[0] = relative.host; + else relPath.unshift(relative.host); + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === "" || srcPath[0] === ""); + } + if (isRelAbs) { + if (relative.host || relative.host === "") { + if (result.host !== relative.host) result.auth = null; + result.host = relative.host; + result.port = relative.port; + } + if (relative.hostname || relative.hostname === "") { + if (result.hostname !== relative.hostname) result.auth = null; + result.hostname = relative.hostname; + } + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + } else if (relPath.length > 0) { + if (!srcPath) srcPath = []; + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (relative.search !== null && relative.search !== undefined) { + if (noLeadingSlashes) { + result.hostname = result.host = srcPath.shift(); + const authInHost = result.host && result.host.indexOf("@") > 0 && result.host.split("@"); + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result.query = relative.query; + if (result.pathname !== null || result.search !== null) { + result.path = (result.pathname ? result.pathname : "") + (result.search ? result.search : ""); + } + result.href = result.format(); + return result; + } + if (srcPath.length === 0) { + result.pathname = null; + if (result.search) { + result.path = "/" + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + let last = srcPath.at(-1); + const hasTrailingSlash = (result.host || relative.host || srcPath.length > 1) && (last === "." || last === "..") || last === ""; + let up = 0; + for (let i = srcPath.length - 1; i >= 0; i--) { + last = srcPath[i]; + if (last === ".") { + spliceOne(srcPath, i); + } else if (last === "..") { + spliceOne(srcPath, i); + up++; + } else if (up) { + spliceOne(srcPath, i); + up--; + } + } + if (!mustEndAbs && !removeAllDots) { + while (up--) { + srcPath.unshift(".."); + } + } + if (mustEndAbs && srcPath[0] !== "" && (!srcPath[0] || srcPath[0].charAt(0) !== "/")) { + srcPath.unshift(""); + } + if (hasTrailingSlash && srcPath.join("/").slice(-1) !== "/") { + srcPath.push(""); + } + const isAbsolute = srcPath[0] === "" || srcPath[0] && srcPath[0].charAt(0) === "/"; + if (noLeadingSlashes) { + result.hostname = result.host = isAbsolute ? "" : srcPath.length > 0 ? srcPath.shift() : ""; + const authInHost = result.host && result.host.indexOf("@") > 0 ? result.host.split("@") : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + mustEndAbs = mustEndAbs || result.host && srcPath.length; + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(""); + } + if (srcPath.length === 0) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join("/"); + } + if (result.pathname !== null || result.search !== null) { + result.path = (result.pathname ? result.pathname : "") + (result.search ? result.search : ""); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + parseHost() { + let host = this.host; + const portMatch = portPattern.exec(host); + if (portMatch) { + const port = portMatch[0]; + if (port !== ":") { + this.port = port.slice(1); + } + host = host.slice(0, host.length - port.length); + } + if (host) this.hostname = host; + } +} +const protocolPattern = /^[\d+.a-z-]+:/i; +const portPattern = /:\d*$/; +const hostPattern = /^\/\/[^/@]+@[^/@]+/; +const simplePathPattern = /^(\/\/?(?!\/)[^\s?]*)(\?\S*)?$/; +const forbiddenHostChars = /[\0\t\n\r #%/:<>?@[\\\]^|]/; +const forbiddenHostCharsIpv6 = /[\0\t\n\r #%/<>?@\\^|]/; +const noEscapeAuth = new Int8Array([ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 0, + 0, + 1, + 1, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 1, + 0 +]); +const escapedCodes = [ + "", + "", + "", + "", + "", + "", + "", + "", + "", + "%09", + "%0A", + "", + "", + "%0D", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "%20", + "", + "%22", + "", + "", + "", + "", + "%27", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "%3C", + "", + "%3E", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "%5C", + "", + "%5E", + "", + "%60", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "%7B", + "%7C", + "%7D" +]; +const hostnameMaxLen = 255; +let urlParseWarned = false; +function urlParse(url, parseQueryString, slashesDenoteHost) { + if (!urlParseWarned) { + urlParseWarned = true; + console.warn("[DeprecationWarning] [unenv] [node:url] DEP0169: `url.parse()` behavior is not standardized and prone to " + "errors that have security implications. Use the WHATWG URL API " + "instead. CVEs are not issued for `url.parse()` vulnerabilities."); + } + if (url instanceof Url) return url; + const urlObject = new Url(); + urlObject.parse(url, parseQueryString, slashesDenoteHost); + return urlObject; +} +function isIpv6Hostname(hostname) { + return String.prototype.charCodeAt.call(hostname, 0) === CHAR_LEFT_SQUARE_BRACKET && String.prototype.charCodeAt.call(hostname, hostname.length - 1) === CHAR_RIGHT_SQUARE_BRACKET; +} +let warnInvalidPort = true; +function getHostname(self, rest, hostname, url) { + for (let i = 0; i < hostname.length; ++i) { + const code = hostname.charCodeAt(i); + const isValid = code !== CHAR_FORWARD_SLASH && code !== CHAR_BACKWARD_SLASH && code !== CHAR_HASH && code !== CHAR_QUESTION_MARK && code !== CHAR_COLON; + if (!isValid) { + if (warnInvalidPort && code === CHAR_COLON) { + console.warn(`[DeprecationWarning] [unenv] [node:url] DEP0170: The URL ${url} is invalid. Future versions of Node.js will throw an error.`); + warnInvalidPort = false; + } + self.hostname = hostname.slice(0, i); + return `/${hostname.slice(i)}${rest}`; + } + } + return rest; +} +function autoEscapeStr(rest) { + let escaped = ""; + let lastEscapedPos = 0; + for (let i = 0; i < rest.length; ++i) { + const escapedChar = escapedCodes[rest.charCodeAt(i)]; + if (escapedChar) { + if (i > lastEscapedPos) escaped += rest.slice(lastEscapedPos, i); + escaped += escapedChar; + lastEscapedPos = i + 1; + } + } + if (lastEscapedPos === 0) return rest; + if (lastEscapedPos < rest.length) escaped += rest.slice(lastEscapedPos); + return escaped; +} +function urlFormat(urlObject, options) { + if (typeof urlObject === "string") { + urlObject = urlParse(urlObject); + } else if (typeof urlObject !== "object" || urlObject === null) { + throw new ERR_INVALID_ARG_TYPE("urlObject", ["Object", "string"], urlObject); + } else if (urlObject instanceof URL) { + let fragment = true; + let unicode = false; + let search = true; + let auth = true; + if (options) { + if (options.fragment != null) { + fragment = Boolean(options.fragment); + } + if (options.unicode != null) { + unicode = Boolean(options.unicode); + } + if (options.search != null) { + search = Boolean(options.search); + } + if (options.auth != null) { + auth = Boolean(options.auth); + } + } + const _url = new URL(urlObject.href); + if (!fragment) _url.hash = ""; + if (!search) _url.search = ""; + if (!auth) _url.username = _url.password = ""; + if (unicode) { + return Url.prototype.format.call(_url); + } + return _url.href; + } + return Url.prototype.format.call(urlObject); +} +function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); +} +function urlResolveObject(source, relative) { + if (!source) return relative; + return urlParse(source, false, true).resolveObject(relative); +} +function pathToFileURL(path, options) { + return _pathToFileURL(path, options); +} +const URL = globalThis.URL; +const URLSearchParams = globalThis.URLSearchParams; +const domainToASCII = punnycode.toASCII; +const domainToUnicode = punnycode.toUnicode; +export { Url, urlParse as parse, urlResolve as resolve, urlResolveObject as resolveObject, urlFormat as format, URL, URLSearchParams, domainToASCII, domainToUnicode, pathToFileURL, fileURLToPath, urlToHttpOptions }; +export default { + Url, + parse: urlParse, + resolve: urlResolve, + resolveObject: urlResolveObject, + format: urlFormat, + URL, + URLSearchParams, + domainToASCII, + domainToUnicode, + pathToFileURL, + fileURLToPath, + urlToHttpOptions +}; diff --git a/worker/node_modules/unenv/dist/runtime/node/util.d.mts b/worker/node_modules/unenv/dist/runtime/node/util.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..a0bd16eb4cdafbdd70df95d5eca7f0c67f3bdd14 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/util.d.mts @@ -0,0 +1,30 @@ +import type nodeUtil from "node:util"; +export { MIMEParams, MIMEType } from "./internal/util/mime.mjs"; +export * from "./internal/util/legacy-types.mjs"; +export * from "./internal/util/log.mjs"; +export { inherits } from "./internal/util/inherits.mjs"; +export { promisify } from "./internal/util/promisify.mjs"; +export { default as types } from "node:util/types"; +export declare const TextDecoder: typeof nodeUtil.TextDecoder; +export declare const TextEncoder: typeof nodeUtil.TextEncoder; +export declare const deprecate: typeof nodeUtil.deprecate; +export declare const _errnoException: unknown; +export declare const _exceptionWithHostPort: unknown; +export declare const _extend: unknown; +export declare const aborted: unknown; +export declare const callbackify: unknown; +export declare const getSystemErrorMap: unknown; +export declare const getSystemErrorName: unknown; +export declare const toUSVString: unknown; +export declare const stripVTControlCharacters: unknown; +export declare const transferableAbortController: unknown; +export declare const transferableAbortSignal: unknown; +export declare const parseArgs: unknown; +export declare const parseEnv: unknown; +export declare const styleText: unknown; +/** @deprecated */ +export declare const getCallSite: unknown; +export declare const getCallSites: unknown; +export declare const getSystemErrorMessage: unknown; +declare const _default: {}; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/util/types.d.mts b/worker/node_modules/unenv/dist/runtime/node/util/types.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..28934e616856313a21dbd7cd58d6e89e62c0cf38 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/util/types.d.mts @@ -0,0 +1,3 @@ +export * from "../internal/util/types.mjs"; +declare const _default; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/node/util/types.mjs b/worker/node_modules/unenv/dist/runtime/node/util/types.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ffa438eafada5554d9da2ae0b6d56c7d43c56a1a --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/util/types.mjs @@ -0,0 +1,3 @@ +import * as types from "../internal/util/types.mjs"; +export * from "../internal/util/types.mjs"; +export default types; diff --git a/worker/node_modules/unenv/dist/runtime/node/v8.d.mts b/worker/node_modules/unenv/dist/runtime/node/v8.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..e8a9ee6282b52d39da4fe78e536da1231bfd3429 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/node/v8.d.mts @@ -0,0 +1,28 @@ +import type nodeV8 from "node:v8"; +export { Deserializer, DefaultDeserializer } from "./internal/v8/deserializer.mjs"; +export { Serializer, DefaultSerializer } from "./internal/v8/serializer.mjs"; +export { GCProfiler } from "./internal/v8/profiler.mjs"; +export declare const cachedDataVersionTag: typeof nodeV8.cachedDataVersionTag; +export declare const deserialize: typeof nodeV8.deserialize; +export declare const getHeapCodeStatistics: typeof nodeV8.getHeapCodeStatistics; +export declare const getHeapSpaceStatistics: typeof nodeV8.getHeapSpaceStatistics; +export declare const getHeapStatistics: typeof nodeV8.getHeapStatistics; +export declare const getHeapSnapshot: typeof nodeV8.getHeapSnapshot; +export declare const promiseHooks: typeof nodeV8.promiseHooks; +export declare const serialize: typeof nodeV8.serialize; +export declare const setFlagsFromString: typeof nodeV8.setFlagsFromString; +export declare const setHeapSnapshotNearHeapLimit: typeof nodeV8.setHeapSnapshotNearHeapLimit; +export declare const startupSnapshot: typeof nodeV8.startupSnapshot; +export declare const stopCoverage: typeof nodeV8.stopCoverage; +export declare const takeCoverage: typeof nodeV8.takeCoverage; +export declare const writeHeapSnapshot: typeof nodeV8.writeHeapSnapshot; +type _Function = Function; +export declare function queryObjects(ctor: _Function): number | string[]; +export declare function queryObjects(ctor: _Function, options: { + format: "count" +}): number; +export declare function queryObjects(ctor: _Function, options: { + format: "summary" +}): string[]; +declare const _default: {}; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/polyfill/globalthis.mjs b/worker/node_modules/unenv/dist/runtime/polyfill/globalthis.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a91bc1e367fa118cc8a35ced7834b79439d0b28f --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/polyfill/globalthis.mjs @@ -0,0 +1 @@ +export default globalThis; diff --git a/worker/node_modules/unenv/dist/runtime/polyfill/performance.mjs b/worker/node_modules/unenv/dist/runtime/polyfill/performance.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c2a3ecd87d9f88c8e30627b7caf216488b1d409e --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/polyfill/performance.mjs @@ -0,0 +1,10 @@ +import { performance, Performance, PerformanceEntry, PerformanceMark, PerformanceMeasure, PerformanceObserver, PerformanceObserverEntryList, PerformanceResourceTiming } from "../web/performance/index.mjs"; +globalThis.performance ||= performance; +globalThis.Performance ||= Performance; +globalThis.PerformanceEntry ||= PerformanceEntry; +globalThis.PerformanceMark ||= PerformanceMark; +globalThis.PerformanceMeasure ||= PerformanceMeasure; +globalThis.PerformanceObserver ||= PerformanceObserver; +globalThis.PerformanceObserverEntryList ||= PerformanceObserverEntryList; +globalThis.PerformanceResourceTiming ||= PerformanceResourceTiming; +export default globalThis.performance; diff --git a/worker/node_modules/unenv/dist/runtime/polyfill/process.d.mts b/worker/node_modules/unenv/dist/runtime/polyfill/process.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..e89f93708579ddfd1194491115ef9005403aa6d9 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/polyfill/process.d.mts @@ -0,0 +1,2 @@ +declare const _default; +export default _default; diff --git a/worker/node_modules/unenv/dist/runtime/polyfill/process.mjs b/worker/node_modules/unenv/dist/runtime/polyfill/process.mjs new file mode 100644 index 0000000000000000000000000000000000000000..95074e15b6928e9fae9537df9cc49a28190fade4 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/polyfill/process.mjs @@ -0,0 +1,9 @@ +import processModule from "node:process"; +const originalProcess = globalThis["process"]; +globalThis.process = originalProcess ? new Proxy(originalProcess, { get(target, prop, receiver) { + if (Reflect.has(target, prop)) { + return Reflect.get(target, prop, receiver); + } + return Reflect.get(processModule, prop, receiver); +} }) : processModule; +export default globalThis.process; diff --git a/worker/node_modules/unenv/dist/runtime/polyfill/timers.d.mts b/worker/node_modules/unenv/dist/runtime/polyfill/timers.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..cb0ff5c3b541f646105198ee23ac0fc3d805023e --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/polyfill/timers.d.mts @@ -0,0 +1 @@ +export {}; diff --git a/worker/node_modules/unenv/dist/runtime/polyfill/timers.mjs b/worker/node_modules/unenv/dist/runtime/polyfill/timers.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b879507fa7eb5ef6e5a0a8ca916e342ff3174d5f --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/polyfill/timers.mjs @@ -0,0 +1,7 @@ +import { setImmediate, clearImmediate } from "node:timers"; +if (!globalThis.setImmediate) { + globalThis.setImmediate = setImmediate; +} +if (!globalThis.clearImmediate) { + globalThis.clearImmediate = clearImmediate; +} diff --git a/worker/node_modules/unenv/dist/runtime/web/performance/_polyfills.d.mts b/worker/node_modules/unenv/dist/runtime/web/performance/_polyfills.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..9aa1520d5f70050e1923f58ef8046e0fe3641e3a --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/web/performance/_polyfills.d.mts @@ -0,0 +1,83 @@ +export type _PerformanceEntryType = "mark" | "measure" | "resource" | "event"; +export declare const _supportedEntryTypes: _PerformanceEntryType[]; +export declare class _PerformanceEntry implements globalThis.PerformanceEntry { + readonly __unenv__: true; + detail: any | undefined; + entryType: _PerformanceEntryType; + name: string; + startTime: number; + constructor(name: string, options?: PerformanceMarkOptions); + get duration(): number; + toJSON(): {}; +} +export declare class _PerformanceMark extends _PerformanceEntry implements globalThis.PerformanceMark { + entryType: "mark"; +} +export declare class _PerformanceMeasure extends _PerformanceEntry implements globalThis.PerformanceMeasure { + entryType: "measure"; +} +export declare class _PerformanceResourceTiming extends _PerformanceEntry implements globalThis.PerformanceResourceTiming { + entryType: "resource"; + serverTiming: readonly PerformanceServerTiming[]; + connectEnd: number; + connectStart: number; + decodedBodySize: number; + domainLookupEnd: number; + domainLookupStart: number; + encodedBodySize: number; + fetchStart: number; + initiatorType: string; + name: string; + nextHopProtocol: string; + redirectEnd: number; + redirectStart: number; + requestStart: number; + responseEnd: number; + responseStart: number; + secureConnectionStart: number; + startTime: number; + transferSize: number; + workerStart: number; + responseStatus: number; +} +export declare class _PerformanceObserver implements globalThis.PerformanceObserver { + readonly __unenv__: true; + static supportedEntryTypes: ReadonlyArray; + _callback: PerformanceObserverCallback | null; + constructor(callback: PerformanceObserverCallback); + takeRecords(): unknown; + disconnect(): void; + observe(options: PerformanceObserverInit): void; +} +export declare class _PerformanceObserverEntryList implements globalThis.PerformanceObserverEntryList { + readonly __unenv__: true; + getEntries(): PerformanceEntryList; + getEntriesByName(_name: string, _type?: string | undefined): PerformanceEntryList; + getEntriesByType(type: string): PerformanceEntryList; +} +export declare class _Performance implements globalThis.Performance { + readonly __unenv__: true; + timeOrigin: number; + eventCounts: EventCounts; + _entries: PerformanceEntry[]; + _resourceTimingBufferSize: number; + navigation: any; + timing: any; + onresourcetimingbufferfull: ((this: Performance, ev: Event) => any) | null; + now(): number; + clearMarks(markName?: string | undefined): void; + clearMeasures(measureName?: string | undefined): void; + clearResourceTimings(): void; + getEntries(): PerformanceEntryT[]; + getEntriesByName(name: string, type?: string | undefined): PerformanceEntryT[]; + getEntriesByType(type: string): PerformanceEntryT[]; + mark(name: string, options?: PerformanceMarkOptions | undefined): PerformanceMark; + measure(measureName: string, startOrMeasureOptions?: string | PerformanceMeasureOptions, endMark?: string): PerformanceMeasure; + setResourceTimingBufferSize(maxSize: number): void; + toJSON(); + addEventListener(type: K, listener: (this: Performance, ev: PerformanceEventMap[K]) => any, options?: boolean | AddEventListenerOptions | undefined): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions | undefined): void; + removeEventListener(type: K, listener: (this: Performance, ev: PerformanceEventMap[K]) => any, options?: boolean | EventListenerOptions | undefined): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions | undefined): void; + dispatchEvent(event: Event): boolean; +} diff --git a/worker/node_modules/unenv/dist/runtime/web/performance/_polyfills.mjs b/worker/node_modules/unenv/dist/runtime/web/performance/_polyfills.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4b23339827f318f3a4cf18a4ae32a3c706eda27e --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/web/performance/_polyfills.mjs @@ -0,0 +1,166 @@ +import { createNotImplementedError } from "../../_internal/utils.mjs"; +const _timeOrigin = globalThis.performance?.timeOrigin ?? Date.now(); +const _performanceNow = globalThis.performance?.now ? globalThis.performance.now.bind(globalThis.performance) : () => Date.now() - _timeOrigin; +export const _supportedEntryTypes = [ + "event", + "mark", + "measure", + "resource" +]; +export class _PerformanceEntry { + __unenv__ = true; + detail; + entryType = "event"; + name; + startTime; + constructor(name, options) { + this.name = name; + this.startTime = options?.startTime || _performanceNow(); + this.detail = options?.detail; + } + get duration() { + return _performanceNow() - this.startTime; + } + toJSON() { + return { + name: this.name, + entryType: this.entryType, + startTime: this.startTime, + duration: this.duration, + detail: this.detail + }; + } +} +export class _PerformanceMark extends _PerformanceEntry { + entryType = "mark"; +} +export class _PerformanceMeasure extends _PerformanceEntry { + entryType = "measure"; +} +export class _PerformanceResourceTiming extends _PerformanceEntry { + entryType = "resource"; + serverTiming = []; + connectEnd = 0; + connectStart = 0; + decodedBodySize = 0; + domainLookupEnd = 0; + domainLookupStart = 0; + encodedBodySize = 0; + fetchStart = 0; + initiatorType = ""; + name = ""; + nextHopProtocol = ""; + redirectEnd = 0; + redirectStart = 0; + requestStart = 0; + responseEnd = 0; + responseStart = 0; + secureConnectionStart = 0; + startTime = 0; + transferSize = 0; + workerStart = 0; + responseStatus = 0; +} +export class _PerformanceObserver { + __unenv__ = true; + static supportedEntryTypes = _supportedEntryTypes; + _callback = null; + constructor(callback) { + this._callback = callback; + } + takeRecords() { + return []; + } + disconnect() { + throw createNotImplementedError("PerformanceObserver.disconnect"); + } + observe(options) { + throw createNotImplementedError("PerformanceObserver.observe"); + } +} +export class _PerformanceObserverEntryList { + __unenv__ = true; + getEntries() { + return []; + } + getEntriesByName(_name, _type) { + return []; + } + getEntriesByType(type) { + return []; + } +} +export class _Performance { + __unenv__ = true; + timeOrigin = _timeOrigin; + eventCounts = new Map(); + _entries = []; + _resourceTimingBufferSize = 0; + navigation = undefined; + timing = undefined; + onresourcetimingbufferfull = null; + now() { + if (this.timeOrigin === _timeOrigin) { + return _performanceNow(); + } + return Date.now() - this.timeOrigin; + } + clearMarks(markName) { + this._entries = markName ? this._entries.filter((e) => e.name !== markName) : this._entries.filter((e) => e.entryType !== "mark"); + } + clearMeasures(measureName) { + this._entries = measureName ? this._entries.filter((e) => e.name !== measureName) : this._entries.filter((e) => e.entryType !== "measure"); + } + clearResourceTimings() { + this._entries = this._entries.filter((e) => e.entryType !== "resource" || e.entryType !== "navigation"); + } + getEntries() { + return this._entries; + } + getEntriesByName(name, type) { + return this._entries.filter((e) => e.name === name && (!type || e.entryType === type)); + } + getEntriesByType(type) { + return this._entries.filter((e) => e.entryType === type); + } + mark(name, options) { + const entry = new _PerformanceMark(name, options); + this._entries.push(entry); + return entry; + } + measure(measureName, startOrMeasureOptions, endMark) { + let start; + let end; + if (typeof startOrMeasureOptions === "string") { + start = this.getEntriesByName(startOrMeasureOptions, "mark")[0]?.startTime; + end = this.getEntriesByName(endMark, "mark")[0]?.startTime; + } else { + start = Number.parseFloat(startOrMeasureOptions?.start) || this.now(); + end = Number.parseFloat(startOrMeasureOptions?.end) || this.now(); + } + const entry = new _PerformanceMeasure(measureName, { + startTime: start, + detail: { + start, + end + } + }); + this._entries.push(entry); + return entry; + } + setResourceTimingBufferSize(maxSize) { + this._resourceTimingBufferSize = maxSize; + } + toJSON() { + return this; + } + addEventListener(type, listener, options) { + throw createNotImplementedError("Performance.addEventListener"); + } + removeEventListener(type, listener, options) { + throw createNotImplementedError("Performance.removeEventListener"); + } + dispatchEvent(event) { + throw createNotImplementedError("Performance.dispatchEvent"); + } +} diff --git a/worker/node_modules/unenv/dist/runtime/web/performance/index.d.mts b/worker/node_modules/unenv/dist/runtime/web/performance/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..38dcaf77e5b8aefaececa0412af5bd0f1ed23974 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/web/performance/index.d.mts @@ -0,0 +1,9 @@ +export { type _PerformanceEntryType, _PerformanceEntry, _PerformanceMark, _PerformanceMeasure, _PerformanceResourceTiming, _Performance, _PerformanceObserver, _PerformanceObserverEntryList } from "./_polyfills.mjs"; +export declare const PerformanceEntry: typeof globalThis.PerformanceEntry; +export declare const PerformanceMark: typeof globalThis.PerformanceMark; +export declare const PerformanceMeasure: typeof globalThis.PerformanceMeasure; +export declare const PerformanceResourceTiming: typeof globalThis.PerformanceResourceTiming; +export declare const PerformanceObserver: typeof globalThis.PerformanceObserver; +export declare const Performance: typeof globalThis.Performance; +export declare const PerformanceObserverEntryList: typeof globalThis.PerformanceObserverEntryList; +export declare const performance: unknown; diff --git a/worker/node_modules/unenv/dist/runtime/web/performance/index.mjs b/worker/node_modules/unenv/dist/runtime/web/performance/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..fe15446f530cde6c48342d83042f64cbd398e013 --- /dev/null +++ b/worker/node_modules/unenv/dist/runtime/web/performance/index.mjs @@ -0,0 +1,10 @@ +import { _PerformanceEntry, _PerformanceMark, _PerformanceMeasure, _PerformanceResourceTiming, _Performance, _PerformanceObserver, _PerformanceObserverEntryList } from "./_polyfills.mjs"; +export { _PerformanceEntry, _PerformanceMark, _PerformanceMeasure, _PerformanceResourceTiming, _Performance, _PerformanceObserver, _PerformanceObserverEntryList } from "./_polyfills.mjs"; +export const PerformanceEntry = globalThis.PerformanceEntry || _PerformanceEntry; +export const PerformanceMark = globalThis.PerformanceMark || _PerformanceMark; +export const PerformanceMeasure = globalThis.PerformanceMeasure || _PerformanceMeasure; +export const PerformanceResourceTiming = globalThis.PerformanceResourceTiming || _PerformanceResourceTiming; +export const PerformanceObserver = globalThis.PerformanceObserver || _PerformanceObserver; +export const Performance = globalThis.Performance || _Performance; +export const PerformanceObserverEntryList = globalThis.PerformanceObserverEntryList || _PerformanceObserverEntryList; +export const performance = globalThis.performance && "addEventListener" in globalThis.performance ? globalThis.performance : new _Performance(); diff --git a/worker/node_modules/unenv/lib/index.d.mts b/worker/node_modules/unenv/lib/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..e47f38137a2f7258c3839f2c65e5d3dbd94c2ce0 --- /dev/null +++ b/worker/node_modules/unenv/lib/index.d.mts @@ -0,0 +1,89 @@ +/** + * Configure a target environment. + */ +export declare function defineEnv(opts?: CreateEnvOptions): { + env: ResolvedEnvironment; + presets: Preset[]; +}; + +export interface CreateEnvOptions { + /** + * Node.js compatibility. + * + * - Add `alias` entries for Node.js builtins as `` and `node:`. + * - Add `inject` entries for Node.js globals `global`, `Buffer`, and `process`. + * + * Default: `true` + */ + nodeCompat?: boolean; + + /** + * Add `alias` entries to replace npm packages like `node-fetch` with lighter shims. + * + * Default: `false` + */ + npmShims?: boolean; + + /** + * Additional presets. + */ + presets?: Preset[]; + + /** + * Additional overrides. + */ + overrides?: Partial; + + /** + * Resolve paths in the environment to absolute paths. + * + * Default: `false` + */ + resolve?: boolean | EnvResolveOptions; +} + +export interface EnvResolveOptions { + /** + * Paths to resolve imports from. + * + * Always unenv path is appended. + */ + paths?: (string | URL)[]; +} + +/** + * Environment defined by presets. + */ +export interface Environment { + alias: Readonly>; + // A `false` value is used to drop an inject entry from a parent Environment. + inject: Readonly>; + polyfill: readonly string[]; + external: readonly string[]; +} + +/** + * Environment returned by `defineEnv`. + * + * It differs from the preset's Environment as the `inject` map nevers contains a `false` value. + */ +export interface ResolvedEnvironment extends Environment { + inject: Readonly>; +} + +export interface Preset extends Partial { + meta?: { + /** + * Preset name. + */ + readonly name?: string; + /** + * Preset version. + */ + readonly version?: string; + /** + * Path or URL to preset entry (used for resolving absolute paths). + */ + readonly url?: string | URL; + }; +} diff --git a/worker/node_modules/unenv/lib/mock.cjs b/worker/node_modules/unenv/lib/mock.cjs new file mode 100644 index 0000000000000000000000000000000000000000..c2af86f1131ba99e9b78b0b727d8986f9271cfac --- /dev/null +++ b/worker/node_modules/unenv/lib/mock.cjs @@ -0,0 +1,47 @@ +Object.defineProperty(exports, "__esModule", { + value: true +}); + +function createMock(name, overrides = {}) { + const proxyFn = function () { /* noop */ }; + proxyFn.prototype.name = name; + const props = {}; + const proxy = new Proxy(proxyFn, { + get(_target, prop) { + if (prop === "caller") { + return null; + } + if (prop === "__createMock__") { + return createMock; + } + if (prop === "__unenv__") { + return true; + } + if (prop in overrides) { + return overrides[prop]; + } + if (prop === "then") { + return (fn) => Promise.resolve(fn()); + } + if (prop === "catch") { + return (fn) => Promise.resolve(); + } + if (prop === "finally") { + return (fn) => Promise.resolve(fn()); + } + return props[prop] = props[prop] || createMock(`${name}.${prop.toString()}`); + }, + apply(_target, _this, _args) { + return createMock(`${name}()`); + }, + construct(_target, _args, _newT) { + return createMock(`[${name}]`); + }, + enumerate() { + return []; + } + }); + return proxy; +} + +module.exports = createMock("mock"); diff --git a/worker/node_modules/unenv/lib/mock.d.cts b/worker/node_modules/unenv/lib/mock.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..1fbe65534ebe9eb8021a7ea6f2c036fb892a7fd2 --- /dev/null +++ b/worker/node_modules/unenv/lib/mock.d.cts @@ -0,0 +1 @@ +export = unknown; diff --git a/worker/node_modules/workerd/bin/workerd b/worker/node_modules/workerd/bin/workerd new file mode 100644 index 0000000000000000000000000000000000000000..e5b11b0eff132d9ef004377ee32558f372f4cb04 --- /dev/null +++ b/worker/node_modules/workerd/bin/workerd @@ -0,0 +1,141 @@ +#!/usr/bin/env node +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); + +// npm/lib/node-platform.ts +var import_fs = __toESM(require("fs")); +var import_os = __toESM(require("os")); +var import_path = __toESM(require("path")); +var knownPackages = { + "darwin arm64 LE": "@cloudflare/workerd-darwin-arm64", + "darwin x64 LE": "@cloudflare/workerd-darwin-64", + "linux arm64 LE": "@cloudflare/workerd-linux-arm64", + "linux x64 LE": "@cloudflare/workerd-linux-64", + "win32 x64 LE": "@cloudflare/workerd-windows-64" +}; +var maybeExeExtension = process.platform === "win32" ? ".exe" : ""; +function pkgAndSubpathForCurrentPlatform() { + let pkg; + let subpath; + let platformKey = `${process.platform} ${import_os.default.arch()} ${import_os.default.endianness()}`; + if (platformKey in knownPackages) { + pkg = knownPackages[platformKey]; + subpath = `bin/workerd${maybeExeExtension}`; + } else { + throw new Error(`Unsupported platform: ${platformKey}`); + } + return { pkg, subpath }; +} +function pkgForSomeOtherPlatform() { + const libMain = require.resolve("workerd"); + const nodeModulesDirectory = import_path.default.dirname( + import_path.default.dirname(import_path.default.dirname(libMain)) + ); + if (import_path.default.basename(nodeModulesDirectory) === "node_modules") { + for (const unixKey in knownPackages) { + try { + const pkg = knownPackages[unixKey]; + if (import_fs.default.existsSync(import_path.default.join(nodeModulesDirectory, pkg))) return pkg; + } catch { + } + } + } + return null; +} +function downloadedBinPath(pkg, subpath) { + const libDir = import_path.default.dirname(require.resolve("workerd")); + return import_path.default.join(libDir, `downloaded-${pkg.replace("/", "-")}-${import_path.default.basename(subpath)}${maybeExeExtension}`); +} +function generateBinPath() { + const { pkg, subpath } = pkgAndSubpathForCurrentPlatform(); + let binPath2; + try { + binPath2 = require.resolve(`${pkg}/${subpath}`); + } catch (e) { + binPath2 = downloadedBinPath(pkg, subpath); + if (!import_fs.default.existsSync(binPath2)) { + try { + require.resolve(pkg); + } catch { + const otherPkg = pkgForSomeOtherPlatform(); + if (otherPkg) { + throw new Error(` +You installed workerd on another platform than the one you're currently using. +This won't work because workerd is written with native code and needs to +install a platform-specific binary executable. + +Specifically the "${otherPkg}" package is present but this platform +needs the "${pkg}" package instead. People often get into this +situation by installing workerd on macOS and copying "node_modules" +into a Docker image that runs Linux. + +If you are installing with npm, you can try not copying the "node_modules" +directory when you copy the files over, and running "npm ci" or "npm install" +on the destination platform after the copy. Or you could consider using yarn +instead which has built-in support for installing a package on multiple +platforms simultaneously. + +If you are installing with yarn, you can try listing both this platform and the +other platform in your ".yarnrc.yml" file using the "supportedArchitectures" +feature: https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures +Keep in mind that this means multiple copies of workerd will be present. +`); + } + throw new Error(`The package "${pkg}" could not be found, and is needed by workerd. + +If you are installing workerd with npm, make sure that you don't specify the +"--no-optional" flag. The "optionalDependencies" package.json feature is used +by workerd to install the correct binary executable for your current platform.`); + } + throw e; + } + } + let pnpapi; + try { + pnpapi = require("pnpapi"); + } catch (e) { + } + if (pnpapi) { + const root = pnpapi.getPackageInformation(pnpapi.topLevel).packageLocation; + const binTargetPath = import_path.default.join( + root, + "node_modules", + ".cache", + "workerd", + `pnpapi-${pkg.replace("/", "-")}-${"1.20250718.0"}-${import_path.default.basename(subpath)}` + ); + if (!import_fs.default.existsSync(binTargetPath)) { + import_fs.default.mkdirSync(import_path.default.dirname(binTargetPath), { recursive: true }); + import_fs.default.copyFileSync(binPath2, binTargetPath); + import_fs.default.chmodSync(binTargetPath, 493); + } + return { binPath: binTargetPath }; + } + return { binPath: binPath2 }; +} + +// npm/lib/node-shim.ts +var { binPath } = generateBinPath(); +require("child_process").execFileSync(binPath, process.argv.slice(2), { + stdio: "inherit" +}); diff --git a/worker/node_modules/workerd/lib/main.js b/worker/node_modules/workerd/lib/main.js new file mode 100644 index 0000000000000000000000000000000000000000..a75b9894d690dd4f3ef302f9d204785765836d9b --- /dev/null +++ b/worker/node_modules/workerd/lib/main.js @@ -0,0 +1,160 @@ +#!/usr/bin/env node +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// npm/lib/node-path.ts +var node_path_exports = {}; +__export(node_path_exports, { + compatibilityDate: () => compatibilityDate, + default: () => node_path_default, + version: () => version +}); +module.exports = __toCommonJS(node_path_exports); + +// npm/lib/node-platform.ts +var import_fs = __toESM(require("fs")); +var import_os = __toESM(require("os")); +var import_path = __toESM(require("path")); +var knownPackages = { + "darwin arm64 LE": "@cloudflare/workerd-darwin-arm64", + "darwin x64 LE": "@cloudflare/workerd-darwin-64", + "linux arm64 LE": "@cloudflare/workerd-linux-arm64", + "linux x64 LE": "@cloudflare/workerd-linux-64", + "win32 x64 LE": "@cloudflare/workerd-windows-64" +}; +var maybeExeExtension = process.platform === "win32" ? ".exe" : ""; +function pkgAndSubpathForCurrentPlatform() { + let pkg; + let subpath; + let platformKey = `${process.platform} ${import_os.default.arch()} ${import_os.default.endianness()}`; + if (platformKey in knownPackages) { + pkg = knownPackages[platformKey]; + subpath = `bin/workerd${maybeExeExtension}`; + } else { + throw new Error(`Unsupported platform: ${platformKey}`); + } + return { pkg, subpath }; +} +function pkgForSomeOtherPlatform() { + const libMain = require.resolve("workerd"); + const nodeModulesDirectory = import_path.default.dirname( + import_path.default.dirname(import_path.default.dirname(libMain)) + ); + if (import_path.default.basename(nodeModulesDirectory) === "node_modules") { + for (const unixKey in knownPackages) { + try { + const pkg = knownPackages[unixKey]; + if (import_fs.default.existsSync(import_path.default.join(nodeModulesDirectory, pkg))) return pkg; + } catch { + } + } + } + return null; +} +function downloadedBinPath(pkg, subpath) { + const libDir = import_path.default.dirname(require.resolve("workerd")); + return import_path.default.join(libDir, `downloaded-${pkg.replace("/", "-")}-${import_path.default.basename(subpath)}${maybeExeExtension}`); +} +function generateBinPath() { + const { pkg, subpath } = pkgAndSubpathForCurrentPlatform(); + let binPath2; + try { + binPath2 = require.resolve(`${pkg}/${subpath}`); + } catch (e) { + binPath2 = downloadedBinPath(pkg, subpath); + if (!import_fs.default.existsSync(binPath2)) { + try { + require.resolve(pkg); + } catch { + const otherPkg = pkgForSomeOtherPlatform(); + if (otherPkg) { + throw new Error(` +You installed workerd on another platform than the one you're currently using. +This won't work because workerd is written with native code and needs to +install a platform-specific binary executable. + +Specifically the "${otherPkg}" package is present but this platform +needs the "${pkg}" package instead. People often get into this +situation by installing workerd on macOS and copying "node_modules" +into a Docker image that runs Linux. + +If you are installing with npm, you can try not copying the "node_modules" +directory when you copy the files over, and running "npm ci" or "npm install" +on the destination platform after the copy. Or you could consider using yarn +instead which has built-in support for installing a package on multiple +platforms simultaneously. + +If you are installing with yarn, you can try listing both this platform and the +other platform in your ".yarnrc.yml" file using the "supportedArchitectures" +feature: https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures +Keep in mind that this means multiple copies of workerd will be present. +`); + } + throw new Error(`The package "${pkg}" could not be found, and is needed by workerd. + +If you are installing workerd with npm, make sure that you don't specify the +"--no-optional" flag. The "optionalDependencies" package.json feature is used +by workerd to install the correct binary executable for your current platform.`); + } + throw e; + } + } + let pnpapi; + try { + pnpapi = require("pnpapi"); + } catch (e) { + } + if (pnpapi) { + const root = pnpapi.getPackageInformation(pnpapi.topLevel).packageLocation; + const binTargetPath = import_path.default.join( + root, + "node_modules", + ".cache", + "workerd", + `pnpapi-${pkg.replace("/", "-")}-${"1.20250718.0"}-${import_path.default.basename(subpath)}` + ); + if (!import_fs.default.existsSync(binTargetPath)) { + import_fs.default.mkdirSync(import_path.default.dirname(binTargetPath), { recursive: true }); + import_fs.default.copyFileSync(binPath2, binTargetPath); + import_fs.default.chmodSync(binTargetPath, 493); + } + return { binPath: binTargetPath }; + } + return { binPath: binPath2 }; +} + +// npm/lib/node-path.ts +var { binPath } = generateBinPath(); +var node_path_default = binPath; +var compatibilityDate = "2025-07-18"; +var version = "1.20250718.0"; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + compatibilityDate, + version +}); diff --git a/worker/node_modules/wrangler/templates/__tests__/pages-dev-util.test.ts b/worker/node_modules/wrangler/templates/__tests__/pages-dev-util.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..3dea566a66eb675f487e5443d248a77ea5891f78 --- /dev/null +++ b/worker/node_modules/wrangler/templates/__tests__/pages-dev-util.test.ts @@ -0,0 +1,128 @@ +import { isRoutingRuleMatch } from "../pages-dev-util"; + +describe("isRoutingRuleMatch", () => { + it("should match rules referencing root level correctly", () => { + const routingRule = "/"; + + expect(isRoutingRuleMatch("/", routingRule)).toBeTruthy(); + expect(isRoutingRuleMatch("/foo", routingRule)).toBeFalsy(); + expect(isRoutingRuleMatch("/foo/", routingRule)).toBeFalsy(); + expect(isRoutingRuleMatch("/foo/bar", routingRule)).toBeFalsy(); + }); + + it("should match include-all rules correctly", () => { + const routingRule = "/*"; + + expect(isRoutingRuleMatch("/", routingRule)).toBeTruthy(); + expect(isRoutingRuleMatch("/foo", routingRule)).toBeTruthy(); + expect(isRoutingRuleMatch("/foo/", routingRule)).toBeTruthy(); + expect(isRoutingRuleMatch("/foo/bar", routingRule)).toBeTruthy(); + expect(isRoutingRuleMatch("/foo/bar/", routingRule)).toBeTruthy(); + expect(isRoutingRuleMatch("/foo/bar/baz", routingRule)).toBeTruthy(); + expect(isRoutingRuleMatch("/foo/bar/baz/", routingRule)).toBeTruthy(); + }); + + it("should match `/*` suffix-ed rules correctly", () => { + let routingRule = "/foo/*"; + + expect(isRoutingRuleMatch("/foo", routingRule)).toBeTruthy(); + expect(isRoutingRuleMatch("/foo/", routingRule)).toBeTruthy(); + expect(isRoutingRuleMatch("/foobar", routingRule)).toBeFalsy(); + expect(isRoutingRuleMatch("/foo/bar", routingRule)).toBeTruthy(); + expect(isRoutingRuleMatch("/foo/bar/baz", routingRule)).toBeTruthy(); + expect(isRoutingRuleMatch("/bar/foo", routingRule)).toBeFalsy(); + expect(isRoutingRuleMatch("/bar/foo/baz", routingRule)).toBeFalsy(); + + routingRule = "/foo/bar/*"; + + expect(isRoutingRuleMatch("/foo", routingRule)).toBeFalsy(); + expect(isRoutingRuleMatch("/foo/", routingRule)).toBeFalsy(); + expect(isRoutingRuleMatch("/foo/bar", routingRule)).toBeTruthy(); + expect(isRoutingRuleMatch("/foo/bar/baz", routingRule)).toBeTruthy(); + expect(isRoutingRuleMatch("/foo/barfoo", routingRule)).toBeFalsy(); + expect(isRoutingRuleMatch("baz/foo/bar", routingRule)).toBeFalsy(); + expect(isRoutingRuleMatch("baz/foo/bar/", routingRule)).toBeFalsy(); + }); + + it("should match `/` suffix-ed rules correctly", () => { + let routingRule = "/foo/"; + expect(isRoutingRuleMatch("/foo/", routingRule)).toBeTruthy(); + expect(isRoutingRuleMatch("/foo", routingRule)).toBeTruthy(); + + routingRule = "/foo/bar/"; + expect(isRoutingRuleMatch("/foo/bar/", routingRule)).toBeTruthy(); + expect(isRoutingRuleMatch("/foo/bar", routingRule)).toBeTruthy(); + }); + + it("should match `*` suffix-ed rules correctly", () => { + let routingRule = "/foo*"; + expect(isRoutingRuleMatch("/foo", routingRule)).toBeTruthy(); + expect(isRoutingRuleMatch("/foo/", routingRule)).toBeTruthy(); + expect(isRoutingRuleMatch("/foobar", routingRule)).toBeTruthy(); + expect(isRoutingRuleMatch("/barfoo", routingRule)).toBeFalsy(); + expect(isRoutingRuleMatch("/foo/bar", routingRule)).toBeTruthy(); + expect(isRoutingRuleMatch("/bar/foo", routingRule)).toBeFalsy(); + expect(isRoutingRuleMatch("/bar/foobar", routingRule)).toBeFalsy(); + expect(isRoutingRuleMatch("/foo/bar/baz", routingRule)).toBeTruthy(); + expect(isRoutingRuleMatch("/bar/foo/baz", routingRule)).toBeFalsy(); + + routingRule = "/foo/bar*"; + expect(isRoutingRuleMatch("/foo/bar", routingRule)).toBeTruthy(); + expect(isRoutingRuleMatch("/foo/bar/", routingRule)).toBeTruthy(); + expect(isRoutingRuleMatch("/foo/barfoo", routingRule)).toBeTruthy(); + expect(isRoutingRuleMatch("/bar/foo/barfoo", routingRule)).toBeFalsy(); + expect(isRoutingRuleMatch("/foo/bar/baz", routingRule)).toBeTruthy(); + expect(isRoutingRuleMatch("/bar/foo/bar/baz", routingRule)).toBeFalsy(); + }); + + it("should match rules without wildcards correctly", () => { + let routingRule = "/foo"; + + expect(isRoutingRuleMatch("/foo", routingRule)).toBeTruthy(); + expect(isRoutingRuleMatch("/foo/", routingRule)).toBeTruthy(); + expect(isRoutingRuleMatch("/foo/bar", routingRule)).toBeFalsy(); + expect(isRoutingRuleMatch("/bar/foo", routingRule)).toBeFalsy(); + + routingRule = "/foo/bar"; + expect(isRoutingRuleMatch("/foo/bar", routingRule)).toBeTruthy(); + expect(isRoutingRuleMatch("/foo/bar/", routingRule)).toBeTruthy(); + expect(isRoutingRuleMatch("/foo/bar/baz", routingRule)).toBeFalsy(); + expect(isRoutingRuleMatch("/baz/foo/bar", routingRule)).toBeFalsy(); + }); + + it("should throw an error if pathname or routing rule params are missing", () => { + // MISSING PATHNAME + expect(() => + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore: sanity check + isRoutingRuleMatch(undefined, "/*") + ).toThrow("Pathname is undefined."); + + expect(() => + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore: sanity check + isRoutingRuleMatch(null, "/*") + ).toThrow("Pathname is undefined."); + + expect(() => isRoutingRuleMatch("", "/*")).toThrow( + "Pathname is undefined." + ); + + // MISSING ROUTING RULE + expect(() => + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore: sanity check + isRoutingRuleMatch("/foo", undefined) + ).toThrow("Routing rule is undefined."); + + expect(() => + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore: sanity check + isRoutingRuleMatch("/foo", null) + ).toThrow("Routing rule is undefined."); + + expect(() => isRoutingRuleMatch("/foo", "")).toThrow( + "Routing rule is undefined." + ); + }); +}); diff --git a/worker/node_modules/wrangler/templates/__tests__/tsconfig-sanity.ts b/worker/node_modules/wrangler/templates/__tests__/tsconfig-sanity.ts new file mode 100644 index 0000000000000000000000000000000000000000..c9f2bcd1ab0b069ab4c2fdd07cdde7aa95cc85d8 --- /dev/null +++ b/worker/node_modules/wrangler/templates/__tests__/tsconfig-sanity.ts @@ -0,0 +1,12 @@ +// `@types/node` should be included +Buffer.from("test"); + +// `@types/jest` should be included +test("test"); + +// @ts-expect-error `@cloudflare/workers-types` should NOT be included +const _handler: ExportedHandler = {}; +// @ts-expect-error `@cloudflare/workers-types` should NOT be included +new HTMLRewriter(); + +export {}; diff --git a/worker/node_modules/wrangler/templates/__tests__/tsconfig.json b/worker/node_modules/wrangler/templates/__tests__/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..683b6d24e12ed4cf4f6fd90d9804076f2a5fdeaf --- /dev/null +++ b/worker/node_modules/wrangler/templates/__tests__/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "@cloudflare/workers-tsconfig/tsconfig.json", + "compilerOptions": { + "types": ["node", "jest"] + }, + "include": ["**/*.ts"], + "exclude": [] +} diff --git a/worker/node_modules/wrangler/templates/middleware/middleware-patch-console-prefix.d.ts b/worker/node_modules/wrangler/templates/middleware/middleware-patch-console-prefix.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8de1efb550924133c0c794868b199cbd078ff488 --- /dev/null +++ b/worker/node_modules/wrangler/templates/middleware/middleware-patch-console-prefix.d.ts @@ -0,0 +1,3 @@ +declare module "config:middleware/patch-console-prefix" { + export const prefix: string; +} diff --git a/worker/node_modules/wrangler/templates/middleware/middleware-patch-console-prefix.ts b/worker/node_modules/wrangler/templates/middleware/middleware-patch-console-prefix.ts new file mode 100644 index 0000000000000000000000000000000000000000..5d1451f1cba041b508f0fb1e25103a39601b1489 --- /dev/null +++ b/worker/node_modules/wrangler/templates/middleware/middleware-patch-console-prefix.ts @@ -0,0 +1,21 @@ +/// + +import { prefix } from "config:middleware/patch-console-prefix"; +import type { Middleware } from "./common"; + +// @ts-expect-error globalThis.console _does_ exist +globalThis.console = new Proxy(globalThis.console, { + get(target, p, receiver) { + if (p === "log" || p === "debug" || p === "info") { + return (...args: unknown[]) => + Reflect.get(target, p, receiver)(prefix, ...args); + } + return Reflect.get(target, p, receiver); + }, +}); + +const passthrough: Middleware = (request, env, _ctx, middlewareCtx) => { + return middlewareCtx.next(request, env); +}; + +export default passthrough; diff --git a/worker/node_modules/wrangler/templates/middleware/middleware-pretty-error.ts b/worker/node_modules/wrangler/templates/middleware/middleware-pretty-error.ts new file mode 100644 index 0000000000000000000000000000000000000000..29dc6d0c82a110382b55b0eae41bbf7848a8a099 --- /dev/null +++ b/worker/node_modules/wrangler/templates/middleware/middleware-pretty-error.ts @@ -0,0 +1,40 @@ +import type { Middleware } from "./common"; + +// A middleware has to be a function of type Middleware +const prettyError: Middleware = async (request, env, _ctx, middlewareCtx) => { + try { + const response = await middlewareCtx.next(request, env); + return response; + } catch (e: any) { + const html = ` + + + + + + + Error 🚨 + + + +
${e.stack}
+ + + `; + + return new Response(html, { + status: 500, + headers: { "Content-Type": "text/html;charset=utf-8" }, + }); + } +}; + +export default prettyError; diff --git a/worker/node_modules/wrangler/templates/middleware/middleware-scheduled.ts b/worker/node_modules/wrangler/templates/middleware/middleware-scheduled.ts new file mode 100644 index 0000000000000000000000000000000000000000..79e6f4db58b936ca5d5170f12ec2691d4b243920 --- /dev/null +++ b/worker/node_modules/wrangler/templates/middleware/middleware-scheduled.ts @@ -0,0 +1,29 @@ +import type { Middleware } from "./common"; + +// A middleware has to be a function of type Middleware +const scheduled: Middleware = async (request, env, _ctx, middlewareCtx) => { + const url = new URL(request.url); + if (url.pathname === "/__scheduled") { + const cron = url.searchParams.get("cron") ?? ""; + await middlewareCtx.dispatch("scheduled", { cron }); + + return new Response("Ran scheduled event"); + } + + const resp = await middlewareCtx.next(request, env); + + // If you open the `/__scheduled` page in a browser, the browser will automatically make a request to `/favicon.ico`. + // For scheduled Workers _without_ a fetch handler, this will result in a 500 response that clutters the log with unhelpful error messages. + // To avoid this, inject a 404 response to favicon.ico loads on the `/__scheduled` page + if ( + request.headers.get("referer")?.endsWith("/__scheduled") && + url.pathname === "/favicon.ico" && + resp.status === 500 + ) { + return new Response(null, { status: 404 }); + } + + return resp; +}; + +export default scheduled; diff --git a/worker/node_modules/wrangler/templates/middleware/middleware-serve-static-assets.d.ts b/worker/node_modules/wrangler/templates/middleware/middleware-serve-static-assets.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..88ff1733e12d61b5d9b761333e895ef78aaf1dbc --- /dev/null +++ b/worker/node_modules/wrangler/templates/middleware/middleware-serve-static-assets.d.ts @@ -0,0 +1,6 @@ +declare module "config:middleware/serve-static-assets" { + import type { CacheControl } from "@cloudflare/kv-asset-handler"; + + export const spaMode: boolean; + export const cacheControl: Partial; +} diff --git a/worker/node_modules/wrangler/templates/middleware/middleware-serve-static-assets.ts b/worker/node_modules/wrangler/templates/middleware/middleware-serve-static-assets.ts new file mode 100644 index 0000000000000000000000000000000000000000..76964b14f7a5659c4b7c46735ac68d677a677a6a --- /dev/null +++ b/worker/node_modules/wrangler/templates/middleware/middleware-serve-static-assets.ts @@ -0,0 +1,56 @@ +/// + +import manifest from "__STATIC_CONTENT_MANIFEST"; +import { + getAssetFromKV, + MethodNotAllowedError, + NotFoundError, + serveSinglePageApp, +} from "@cloudflare/kv-asset-handler"; +import { cacheControl, spaMode } from "config:middleware/serve-static-assets"; +import type { Middleware } from "./common"; +import type { Options } from "@cloudflare/kv-asset-handler"; +import type * as kvAssetHandler from "@cloudflare/kv-asset-handler"; + +const ASSET_MANIFEST = JSON.parse(manifest); + +const staticAssets: Middleware = async (request, env, ctx, middlewareCtx) => { + let options: Partial = { + ASSET_MANIFEST, + ASSET_NAMESPACE: env.__STATIC_CONTENT, + cacheControl: cacheControl, + mapRequestToAsset: spaMode ? serveSinglePageApp : undefined, + }; + + try { + const page = await (getAssetFromKV as typeof kvAssetHandler.getAssetFromKV)( + { + request, + waitUntil(promise) { + return ctx.waitUntil(promise); + }, + }, + options + ); + + // allow headers to be altered + const response = new Response(page.body, page); + + response.headers.set("X-XSS-Protection", "1; mode=block"); + response.headers.set("X-Content-Type-Options", "nosniff"); + response.headers.set("X-Frame-Options", "DENY"); + response.headers.set("Referrer-Policy", "unsafe-url"); + response.headers.set("Feature-Policy", "none"); + + return response; + } catch (e) { + if (e instanceof NotFoundError || e instanceof MethodNotAllowedError) { + // if a known error is thrown then serve from actual worker + return await middlewareCtx.next(request, env); + } + // otherwise it's a real error, so throw it + throw e; + } +}; + +export default staticAssets; diff --git a/worker/node_modules/wrangler/templates/startDevWorker/InspectorProxyWorker.ts b/worker/node_modules/wrangler/templates/startDevWorker/InspectorProxyWorker.ts new file mode 100644 index 0000000000000000000000000000000000000000..602e686106f8ca0155d9b20883f688fa660aeaf3 --- /dev/null +++ b/worker/node_modules/wrangler/templates/startDevWorker/InspectorProxyWorker.ts @@ -0,0 +1,664 @@ +import assert from "node:assert"; +import { + DevToolsCommandRequest, + DevToolsCommandRequests, + DevToolsCommandResponses, + DevToolsEvent, + DevToolsEvents, + serialiseError, +} from "../../src/api/startDevWorker/events"; +import { + assertNever, + createDeferred, + DeferredPromise, + MaybePromise, + urlFromParts, +} from "../../src/api/startDevWorker/utils"; +import type { + InspectorProxyWorkerIncomingWebSocketMessage, + InspectorProxyWorkerOutgoingRequestBody, + InspectorProxyWorkerOutgoingWebsocketMessage, + ProxyData, +} from "../../src/api/startDevWorker/events"; + +const ALLOWED_HOST_HOSTNAMES = ["127.0.0.1", "[::1]", "localhost"]; +const ALLOWED_ORIGIN_HOSTNAMES = [ + "devtools.devprod.cloudflare.dev", + "cloudflare-devtools.pages.dev", + /^[a-z0-9]+\.cloudflare-devtools\.pages\.dev$/, + "127.0.0.1", + "[::1]", + "localhost", +]; + +interface Env { + PROXY_CONTROLLER: Fetcher; + PROXY_CONTROLLER_AUTH_SECRET: string; + WRANGLER_VERSION: string; + DURABLE_OBJECT: DurableObjectNamespace; +} + +export default { + fetch(req, env) { + const singleton = env.DURABLE_OBJECT.idFromName(""); + const inspectorProxy = env.DURABLE_OBJECT.get(singleton); + + return inspectorProxy.fetch(req); + }, +} as ExportedHandler; + +function isDevToolsEvent( + event: unknown, + name: Method +): event is DevToolsEvent { + return ( + typeof event === "object" && + event !== null && + "method" in event && + event.method === name + ); +} + +export class InspectorProxyWorker implements DurableObject { + constructor( + _state: DurableObjectState, + readonly env: Env + ) {} + + websockets: { + proxyController?: WebSocket; + runtime?: WebSocket; + devtools?: WebSocket; + + // Browser DevTools cannot read the filesystem, + // instead they fetch via `Network.loadNetworkResource` messages. + // IDE DevTools can read the filesystem and expect absolute paths. + devtoolsHasFileSystemAccess?: boolean; + + // We want to be able to delay devtools connection response + // until we've connected to the runtime inspector server + // so this deferred holds a promise to websockets.runtime + runtimeDeferred: DeferredPromise; + } = { + runtimeDeferred: createDeferred(), + }; + proxyData?: ProxyData; + runtimeMessageBuffer: (DevToolsCommandResponses | DevToolsEvents)[] = []; + + async fetch(req: Request) { + if ( + req.headers.get("Authorization") === this.env.PROXY_CONTROLLER_AUTH_SECRET + ) { + return this.handleProxyControllerRequest(req); + } + + if (req.headers.get("Upgrade") === "websocket") { + return this.handleDevToolsWebSocketUpgradeRequest(req); + } + + return this.handleDevToolsJsonRequest(req); + } + + // ************************ + // ** PROXY CONTROLLER ** + // ************************ + + handleProxyControllerRequest(req: Request) { + assert( + req.headers.get("Upgrade") === "websocket", + "Expected proxy controller data request to be WebSocket upgrade" + ); + + const { 0: response, 1: proxyController } = new WebSocketPair(); + proxyController.accept(); + proxyController.addEventListener("close", (event) => { + // don't reconnect the proxyController websocket + // ProxyController can detect this event and reconnect itself + + this.sendDebugLog( + "PROXY CONTROLLER WEBSOCKET CLOSED", + event.code, + event.reason + ); + + if (this.websockets.proxyController === proxyController) { + this.websockets.proxyController = undefined; + } + }); + proxyController.addEventListener("error", (event) => { + // don't reconnect the proxyController websocket + // ProxyController can detect this event and reconnect itself + + const error = serialiseError(event.error); + this.sendDebugLog("PROXY CONTROLLER WEBSOCKET ERROR", error); + + if (this.websockets.proxyController === proxyController) { + this.websockets.proxyController = undefined; + } + }); + proxyController.addEventListener( + "message", + this.handleProxyControllerIncomingMessage + ); + + this.websockets.proxyController = proxyController; + + return new Response(null, { + status: 101, + webSocket: response, + }); + } + + handleProxyControllerIncomingMessage = (event: MessageEvent) => { + assert( + typeof event.data === "string", + "Expected event.data from proxy controller to be string" + ); + + const message: InspectorProxyWorkerIncomingWebSocketMessage = JSON.parse( + event.data + ); + + this.sendDebugLog("handleProxyControllerIncomingMessage", event.data); + + switch (message.type) { + case "reloadStart": { + this.sendRuntimeDiscardConsoleEntries(); + + break; + } + case "reloadComplete": { + this.proxyData = message.proxyData; + + this.reconnectRuntimeWebSocket(); + + break; + } + default: { + assertNever(message); + } + } + }; + + sendProxyControllerMessage( + message: string | InspectorProxyWorkerOutgoingWebsocketMessage + ) { + message = typeof message === "string" ? message : JSON.stringify(message); + + // if the proxyController websocket is disconnected, throw away the message + this.websockets.proxyController?.send(message); + } + + async sendProxyControllerRequest( + message: InspectorProxyWorkerOutgoingRequestBody + ) { + try { + const res = await this.env.PROXY_CONTROLLER.fetch("http://dummy", { + method: "POST", + body: JSON.stringify(message), + }); + return res.ok ? await res.text() : undefined; + } catch (e) { + this.sendDebugLog( + "FAILED TO SEND PROXY CONTROLLER REQUEST", + serialiseError(e) + ); + return undefined; + } + } + + sendDebugLog: typeof console.debug = (...args) => { + this.sendProxyControllerRequest({ type: "debug-log", args }); + }; + + // *************** + // ** RUNTIME ** + // *************** + + handleRuntimeIncomingMessage = (event: MessageEvent) => { + assert(typeof event.data === "string"); + + const msg = JSON.parse(event.data) as + | DevToolsCommandResponses + | DevToolsEvents; + this.sendDebugLog("RUNTIME INCOMING MESSAGE", msg); + + if (isDevToolsEvent(msg, "Runtime.exceptionThrown")) { + this.sendProxyControllerMessage(event.data); + } + if ( + this.proxyData?.proxyLogsToController && + isDevToolsEvent(msg, "Runtime.consoleAPICalled") + ) { + this.sendProxyControllerMessage(event.data); + } + + this.runtimeMessageBuffer.push(msg); + this.tryDrainRuntimeMessageBuffer(); + }; + + handleRuntimeScriptParsed(msg: DevToolsEvent<"Debugger.scriptParsed">) { + // If the devtools does not have filesystem access, + // rewrite the sourceMapURL to use a special scheme. + // This special scheme is used to indicate whether + // to intercept each loadNetworkResource message. + + if ( + !this.websockets.devtoolsHasFileSystemAccess && + msg.params.sourceMapURL !== undefined && + // Don't try to find a sourcemap for e.g. node-internal: scripts + msg.params.url.startsWith("file:") + ) { + const url = new URL(msg.params.sourceMapURL, msg.params.url); + // Check for file: in case msg.params.sourceMapURL has a different + // protocol (e.g. data). In that case we should ignore this file + if (url.protocol === "file:") { + msg.params.sourceMapURL = url.href.replace("file:", "wrangler-file:"); + } + } + + void this.sendDevToolsMessage(msg); + } + + tryDrainRuntimeMessageBuffer = () => { + // If we don't have a DevTools WebSocket, try again later + if (this.websockets.devtools === undefined) return; + + // clear the buffer and replay each message to devtools + for (const msg of this.runtimeMessageBuffer.splice(0)) { + if (isDevToolsEvent(msg, "Debugger.scriptParsed")) { + this.handleRuntimeScriptParsed(msg); + } else { + void this.sendDevToolsMessage(msg); + } + } + }; + + runtimeAbortController = new AbortController(); // will abort the in-flight websocket upgrade request to the remote runtime + runtimeKeepAliveInterval: number | null = null; + async reconnectRuntimeWebSocket() { + assert(this.proxyData, "Expected this.proxyData to be defined"); + + this.sendDebugLog("reconnectRuntimeWebSocket"); + + this.websockets.runtime?.close(); + this.websockets.runtime = undefined; + this.runtimeAbortController.abort(); + this.runtimeAbortController = new AbortController(); + this.websockets.runtimeDeferred = createDeferred( + this.websockets.runtimeDeferred + ); + + const runtimeWebSocketUrl = urlFromParts( + this.proxyData.userWorkerInspectorUrl + ); + runtimeWebSocketUrl.protocol = this.proxyData.userWorkerUrl.protocol; // http: or https: + + this.sendDebugLog("NEW RUNTIME WEBSOCKET", runtimeWebSocketUrl); + + // Make sure DevTools re-fetches script contents, + // and uses the newly created execution context + this.sendDevToolsMessage({ + method: "Runtime.executionContextsCleared", + params: undefined, + }); + + const upgrade = await fetch(runtimeWebSocketUrl, { + headers: { + ...this.proxyData.headers, + Upgrade: "websocket", + }, + signal: this.runtimeAbortController.signal, + }); + + const runtime = upgrade.webSocket; + if (!runtime) { + const error = new Error( + `Failed to establish the WebSocket connection: expected server to reply with HTTP status code 101 (switching protocols), but received ${upgrade.status} instead.` + ); + + this.websockets.runtimeDeferred.reject(error); + this.sendProxyControllerRequest({ + type: "runtime-websocket-error", + error: serialiseError(error), + }); + + return; + } + + this.websockets.runtime = runtime; + + runtime.addEventListener("message", this.handleRuntimeIncomingMessage); + + runtime.addEventListener("close", (event) => { + this.sendDebugLog("RUNTIME WEBSOCKET CLOSED", event.code, event.reason); + + clearInterval(this.runtimeKeepAliveInterval); + + if (this.websockets.runtime === runtime) { + this.websockets.runtime = undefined; + } + + // don't reconnect the runtime websocket + // if it closes unexpectedly (very rare or a case where reconnecting won't succeed anyway) + // wait for a new proxy-data message or manual restart + }); + + runtime.addEventListener("error", (event) => { + const error = serialiseError(event.error); + this.sendDebugLog("RUNTIME WEBSOCKET ERROR", error); + + clearInterval(this.runtimeKeepAliveInterval); + + if (this.websockets.runtime === runtime) { + this.websockets.runtime = undefined; + } + + this.sendProxyControllerRequest({ + type: "runtime-websocket-error", + error, + }); + + // don't reconnect the runtime websocket + // if it closes unexpectedly (very rare or a case where reconnecting won't succeed anyway) + // wait for a new proxy-data message or manual restart + }); + + runtime.accept(); + + // fetch(Upgrade: websocket) resolves when the websocket is open + // therefore the open event will not fire, so just trigger the handler + this.handleRuntimeWebSocketOpen(runtime); + } + + #runtimeMessageCounter = 1e8; + nextCounter() { + return ++this.#runtimeMessageCounter; + } + handleRuntimeWebSocketOpen(runtime: WebSocket) { + this.sendDebugLog("RUNTIME WEBSOCKET OPENED"); + + this.sendRuntimeMessage( + { method: "Runtime.enable", id: this.nextCounter() }, + runtime + ); + this.sendRuntimeMessage( + { method: "Debugger.enable", id: this.nextCounter() }, + runtime + ); + this.sendRuntimeMessage( + { method: "Network.enable", id: this.nextCounter() }, + runtime + ); + + clearInterval(this.runtimeKeepAliveInterval); + this.runtimeKeepAliveInterval = setInterval(() => { + this.sendRuntimeMessage( + { method: "Runtime.getIsolateId", id: this.nextCounter() }, + runtime + ); + }, 10_000) as any; + + this.websockets.runtimeDeferred.resolve(runtime); + } + + sendRuntimeDiscardConsoleEntries() { + // by default, sendRuntimeMessage waits for the runtime websocket to connect + // but we only want to send this message now or never + // if we schedule it to send later (like waiting for the websocket, by default) + // then we risk clearing logs that have occured since we scheduled it too + // which is worse than leaving logs from the previous version on screen + if (this.websockets.runtime) { + this.sendRuntimeMessage( + { + method: "Runtime.discardConsoleEntries", + id: this.nextCounter(), + }, + this.websockets.runtime + ); + } + } + + async sendRuntimeMessage( + message: string | DevToolsCommandRequests, + runtime: MaybePromise = this.websockets.runtimeDeferred.promise + ) { + runtime = await runtime; + message = typeof message === "string" ? message : JSON.stringify(message); + + this.sendDebugLog("SEND TO RUNTIME", message); + + runtime.send(message); + } + + // **************** + // ** DEVTOOLS ** + // **************** + + #inspectorId = crypto.randomUUID(); + async handleDevToolsJsonRequest(req: Request) { + const url = new URL(req.url); + + if (url.pathname === "/json/version") { + return Response.json({ + Browser: `wrangler/v${this.env.WRANGLER_VERSION}`, + // TODO: (someday): The DevTools protocol should match that of workerd. + // This could be exposed by the preview API. + "Protocol-Version": "1.3", + }); + } + + if (url.pathname === "/json" || url.pathname === "/json/list") { + // TODO: can we remove the `/ws` here if we only have a single worker? + const localHost = `${url.host}/ws`; + const devtoolsFrontendUrl = `https://devtools.devprod.cloudflare.dev/js_app?theme=systemPreferred&debugger=true&ws=${localHost}`; + + return Response.json([ + { + id: this.#inspectorId, + type: "node", // TODO: can we specify different type? + description: "workers", + webSocketDebuggerUrl: `ws://${localHost}`, + devtoolsFrontendUrl, + devtoolsFrontendUrlCompat: devtoolsFrontendUrl, + // Below are fields that are visible in the DevTools UI. + title: "Cloudflare Worker", + faviconUrl: "https://workers.cloudflare.com/favicon.ico", + // url: "http://" + localHost, // looks unnecessary + }, + ]); + } + + return new Response(null, { status: 404 }); + } + + async handleDevToolsWebSocketUpgradeRequest(req: Request) { + // Validate `Host` header + let hostHeader = req.headers.get("Host"); + if (hostHeader == null) return new Response(null, { status: 400 }); + try { + const host = new URL(`http://${hostHeader}`); + if (!ALLOWED_HOST_HOSTNAMES.includes(host.hostname)) { + return new Response("Disallowed `Host` header", { status: 401 }); + } + } catch { + return new Response("Expected `Host` header", { status: 400 }); + } + // Validate `Origin` header + let originHeader = req.headers.get("Origin"); + if (originHeader === null && !req.headers.has("User-Agent")) { + // VSCode doesn't send an `Origin` header, but also doesn't send a + // `User-Agent` header, so allow an empty origin in this case. + originHeader = "http://localhost"; + } + if (originHeader === null) { + return new Response("Expected `Origin` header", { status: 400 }); + } + try { + const origin = new URL(originHeader); + const allowed = ALLOWED_ORIGIN_HOSTNAMES.some((rule) => { + if (typeof rule === "string") return origin.hostname === rule; + else return rule.test(origin.hostname); + }); + if (!allowed) { + return new Response("Disallowed `Origin` header", { status: 401 }); + } + } catch { + return new Response("Expected `Origin` header", { status: 400 }); + } + + // DevTools attempting to connect + this.sendDebugLog("DEVTOOLS WEBSOCKET TRYING TO CONNECT"); + + // Delay devtools connection response until we've connected to the runtime inspector server + await this.websockets.runtimeDeferred.promise; + + this.sendDebugLog("DEVTOOLS WEBSOCKET CAN NOW CONNECT"); + + assert( + req.headers.get("Upgrade") === "websocket", + "Expected DevTools connection to be WebSocket upgrade" + ); + const { 0: response, 1: devtools } = new WebSocketPair(); + devtools.accept(); + + if (this.websockets.devtools !== undefined) { + /** We only want to have one active Devtools instance at a time. */ + // TODO(consider): prioritise new websocket over previous + devtools.close( + 1013, + "Too many clients; only one can be connected at a time" + ); + } else { + devtools.addEventListener("message", this.handleDevToolsIncomingMessage); + devtools.addEventListener("close", (event) => { + this.sendDebugLog( + "DEVTOOLS WEBSOCKET CLOSED", + event.code, + event.reason + ); + + if (this.websockets.devtools === devtools) { + this.websockets.devtools = undefined; + } + }); + devtools.addEventListener("error", (event) => { + const error = serialiseError(event.error); + this.sendDebugLog("DEVTOOLS WEBSOCKET ERROR", error); + + if (this.websockets.devtools === devtools) { + this.websockets.devtools = undefined; + } + }); + + // Since Wrangler proxies the inspector, reloading Chrome DevTools won't trigger debugger initialisation events (because it's connecting to an extant session). + // This sends a `Debugger.disable` message to the remote when a new WebSocket connection is initialised, + // with the assumption that the new connection will shortly send a `Debugger.enable` event and trigger re-initialisation. + // The key initialisation messages that are needed are the `Debugger.scriptParsed events`. + this.sendRuntimeMessage({ + id: this.nextCounter(), + method: "Debugger.disable", + }); + + this.sendDebugLog("DEVTOOLS WEBSOCKET CONNECTED"); + + // Our patched DevTools are hosted on a `https://` URL. These cannot + // access `file://` URLs, meaning local source maps cannot be fetched. + // To get around this, we can rewrite `Debugger.scriptParsed` events to + // include a special `worker:` scheme for source maps, and respond to + // `Network.loadNetworkResource` commands for these. Unfortunately, this + // breaks IDE's built-in debuggers (e.g. VSCode and WebStorm), so we only + // want to enable this transformation when we detect hosted DevTools has + // connected. We do this by looking at the WebSocket handshake headers: + // + // DevTools + // + // Upgrade: websocket + // Host: localhost:9229 + // (from Chrome) User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 + // (from Firefox) User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:109.0) Gecko/20100101 Firefox/116.0 + // Origin: https://devtools.devprod.cloudflare.dev + // ... + // + // VSCode + // + // Upgrade: websocket + // Host: localhost + // ... + // + // WebStorm + // + // Upgrade: websocket + // Host: localhost:9229 + // Origin: http://localhost:9229 + // ... + // + // From this, we could just use the presence of a `User-Agent` header to + // determine if DevTools connected, but VSCode/WebStorm could very well + // add this in future versions. We could also look for an `Origin` header + // matching the hosted DevTools URL, but this would prevent preview/local + // versions working. Instead, we look for a browser-like `User-Agent`. + const userAgent = req.headers.get("User-Agent") ?? ""; + const hasFileSystemAccess = !/mozilla/i.test(userAgent); + + this.websockets.devtools = devtools; + this.websockets.devtoolsHasFileSystemAccess = hasFileSystemAccess; + + this.tryDrainRuntimeMessageBuffer(); + } + + return new Response(null, { status: 101, webSocket: response }); + } + + handleDevToolsIncomingMessage = (event: MessageEvent) => { + assert( + typeof event.data === "string", + "Expected devtools incoming message to be of type string" + ); + + const message = JSON.parse(event.data) as DevToolsCommandRequests; + this.sendDebugLog("DEVTOOLS INCOMING MESSAGE", message); + + if (message.method === "Network.loadNetworkResource") { + return void this.handleDevToolsLoadNetworkResource(message); + } + + this.sendRuntimeMessage(JSON.stringify(message)); + }; + + async handleDevToolsLoadNetworkResource( + message: DevToolsCommandRequest<"Network.loadNetworkResource"> + ) { + const response = await this.sendProxyControllerRequest({ + type: "load-network-resource", + url: message.params.url, + }); + if (response === undefined) { + this.sendDebugLog( + `ProxyController could not resolve Network.loadNetworkResource for "${message.params.url}"` + ); + + // When the ProxyController cannot resolve a resource, let the runtime handle the request + this.sendRuntimeMessage(JSON.stringify(message)); + } else { + // this.websockets.devtools can be undefined here + // the incoming message implies we have a devtools connection, but after + // the await it could've dropped in which case we can safely not respond + this.sendDevToolsMessage({ + id: message.id, + // @ts-expect-error DevTools Protocol type does not match our patched devtools -- result.resource.text was added + result: { resource: { success: true, text: response } }, + }); + } + } + + sendDevToolsMessage( + message: string | DevToolsCommandResponses | DevToolsEvents + ) { + message = typeof message === "string" ? message : JSON.stringify(message); + + this.sendDebugLog("SEND TO DEVTOOLS", message); + + this.websockets.devtools?.send(message); + } +} diff --git a/worker/node_modules/wrangler/templates/startDevWorker/ProxyWorker.ts b/worker/node_modules/wrangler/templates/startDevWorker/ProxyWorker.ts new file mode 100644 index 0000000000000000000000000000000000000000..39731d3f6755146b34103cb5554a10d034e9072c --- /dev/null +++ b/worker/node_modules/wrangler/templates/startDevWorker/ProxyWorker.ts @@ -0,0 +1,336 @@ +import { + createDeferred, + DeferredPromise, + urlFromParts, +} from "../../src/api/startDevWorker/utils"; +import type { + ProxyData, + ProxyWorkerIncomingRequestBody, + ProxyWorkerOutgoingRequestBody, +} from "../../src/api/startDevWorker/events"; + +interface Env { + PROXY_CONTROLLER: Fetcher; + PROXY_CONTROLLER_AUTH_SECRET: string; + DURABLE_OBJECT: DurableObjectNamespace; +} + +// request.cf.hostMetadata is verbose to type using the workers-types Request -- this allows us to have Request correctly typed in this scope +type Request = Parameters< + NonNullable< + ExportedHandler["fetch"] + > +>[0]; + +const LIVE_RELOAD_PROTOCOL = "WRANGLER_PROXYWORKER_LIVE_RELOAD_PROTOCOL"; +export default { + fetch(req, env) { + const singleton = env.DURABLE_OBJECT.idFromName(""); + const inspectorProxy = env.DURABLE_OBJECT.get(singleton); + + return inspectorProxy.fetch(req); + }, +} as ExportedHandler; + +export class ProxyWorker implements DurableObject { + constructor( + readonly state: DurableObjectState, + readonly env: Env + ) {} + + proxyData?: ProxyData; + requestQueue = new Map>(); + requestRetryQueue = new Map>(); + + fetch(request: Request) { + if (isRequestForLiveReloadWebsocket(request)) { + // requests for live-reload websocket + + return this.handleLiveReloadWebSocket(request); + } + + if (isRequestFromProxyController(request, this.env)) { + // requests from ProxyController + + return this.processProxyControllerRequest(request); + } + + // regular requests to be proxied + const deferred = createDeferred(); + + this.requestQueue.set(request, deferred); + this.processQueue(); + + return deferred.promise; + } + + handleLiveReloadWebSocket(request: Request) { + const { 0: response, 1: liveReload } = new WebSocketPair(); + const websocketProtocol = + request.headers.get("Sec-WebSocket-Protocol") ?? ""; + + this.state.acceptWebSocket(liveReload, ["live-reload"]); + + return new Response(null, { + status: 101, + webSocket: response, + headers: { "Sec-WebSocket-Protocol": websocketProtocol }, + }); + } + + processProxyControllerRequest(request: Request) { + const event = request.cf?.hostMetadata; + switch (event?.type) { + case "pause": + this.proxyData = undefined; + break; + + case "play": + this.proxyData = event.proxyData; + this.processQueue(); + this.state + .getWebSockets("live-reload") + .forEach((ws) => ws.send("reload")); + + break; + } + + return new Response(null, { status: 204 }); + } + + /** + * Process requests that are being retried first, then process newer requests. + * Requests that are being retried are, by definition, older than requests which haven't been processed yet. + * We don't need to be more accurate than this re ordering, since the requests are being fired off synchronously. + */ + *getOrderedQueue() { + yield* this.requestRetryQueue; + yield* this.requestQueue; + } + + processQueue() { + const { proxyData } = this; // store proxyData at the moment this function was called + if (proxyData === undefined) return; + + for (const [request, deferredResponse] of this.getOrderedQueue()) { + this.requestRetryQueue.delete(request); + this.requestQueue.delete(request); + + const outerUrl = new URL(request.url); + const headers = new Headers(request.headers); + + // override url parts for proxying + const userWorkerUrl = new URL(request.url); + Object.assign(userWorkerUrl, proxyData.userWorkerUrl); + + // set request.url in the UserWorker + const innerUrl = urlFromParts( + proxyData.userWorkerInnerUrlOverrides ?? {}, + request.url + ); + headers.set("MF-Original-URL", innerUrl.href); + headers.set("MF-Disable-Pretty-Error", "true"); // disables the UserWorker miniflare instance from rendering the pretty error -- instead the ProxyWorker miniflare instance will intercept the json error response and render the pretty error page + + // Preserve client `Accept-Encoding`, rather than using Worker's default + // of `Accept-Encoding: br, gzip` + const encoding = request.cf?.clientAcceptEncoding; + if (encoding !== undefined) headers.set("Accept-Encoding", encoding); + + rewriteUrlRelatedHeaders(headers, outerUrl, innerUrl); + + // merge proxyData headers with the request headers + for (const [key, value] of Object.entries(proxyData.headers ?? {})) { + if (value === undefined) continue; + + if (key.toLowerCase() === "cookie") { + const existing = request.headers.get("cookie") ?? ""; + headers.set("cookie", `${existing};${value}`); + } else { + headers.set(key, value); + } + } + + // explicitly NOT await-ing this promise, we are in a loop and want to process the whole queue quickly + synchronously + void fetch(userWorkerUrl, new Request(request, { headers })) + .then((res) => { + res = new Response(res.body, res); + rewriteUrlRelatedHeaders(res.headers, innerUrl, outerUrl); + + if (isHtmlResponse(res)) { + res = insertLiveReloadScript(request, res, this.env, proxyData); + } + + deferredResponse.resolve(res); + }) + .catch((error: Error) => { + // errors here are network errors or from response post-processing + // to catch only network errors, use the 2nd param of the fetch.then() + + // we have crossed an async boundary, so proxyData may have changed + // if proxyData.userWorkerUrl has changed, it means there is a new downstream UserWorker + // and that this error is stale since it was for a request to the old UserWorker + // so here we construct a newUserWorkerUrl so we can compare it to the (old) userWorkerUrl + const newUserWorkerUrl = + this.proxyData && urlFromParts(this.proxyData.userWorkerUrl); + + // only report errors if the downstream proxy has NOT changed + if (userWorkerUrl.href === newUserWorkerUrl?.href) { + void sendMessageToProxyController(this.env, { + type: "error", + error: { + name: error.name, + message: error.message, + stack: error.stack, + cause: error.cause, + }, + }); + + deferredResponse.reject(error); + } + + // if the request can be retried (subset of idempotent requests which have no body), requeue it + else if (request.method === "GET" || request.method === "HEAD") { + this.requestRetryQueue.set(request, deferredResponse); + // we would only end up here if the downstream UserWorker is chang*ing* + // i.e. we are in a `pause`d state and expecting a `play` message soon + // this request will be processed (retried) when the `play` message arrives + // for that reason, we do not need to call `this.processQueue` here + // (but, also, it can't hurt to call it since it bails when + // in a `pause`d state i.e. `this.proxyData` is undefined) + } + + // if the request cannot be retried, respond with 503 Service Unavailable + // important to note, this is not an (unexpected) error -- it is an acceptable flow of local development + // it would be incorrect to retry non-idempotent requests + // and would require cloning all body streams to avoid stream reuse (which is inefficient but not out of the question in the future) + // this is a good enough UX for now since it solves the most common GET use-case + else { + deferredResponse.resolve( + new Response( + "Your worker restarted mid-request. Please try sending the request again. Only GET or HEAD requests are retried automatically.", + { + status: 503, + headers: { "Retry-After": "0" }, + } + ) + ); + } + }); + } + } +} + +function isRequestFromProxyController(req: Request, env: Env): boolean { + return req.headers.get("Authorization") === env.PROXY_CONTROLLER_AUTH_SECRET; +} +function isHtmlResponse(res: Response): boolean { + return res.headers.get("content-type")?.startsWith("text/html") ?? false; +} +function isRequestForLiveReloadWebsocket(req: Request): boolean { + const websocketProtocol = req.headers.get("Sec-WebSocket-Protocol"); + const isWebSocketUpgrade = req.headers.get("Upgrade") === "websocket"; + + return isWebSocketUpgrade && websocketProtocol === LIVE_RELOAD_PROTOCOL; +} + +function sendMessageToProxyController( + env: Env, + message: ProxyWorkerOutgoingRequestBody +) { + return env.PROXY_CONTROLLER.fetch("http://dummy", { + method: "POST", + body: JSON.stringify(message), + }); +} + +function insertLiveReloadScript( + request: Request, + response: Response, + env: Env, + proxyData: ProxyData +) { + const htmlRewriter = new HTMLRewriter(); + + // if preview-token-expired response, errorDetails will contain "Invalid Workers Preview configuration" + let errorDetails = ""; + htmlRewriter.on("#cf-error-details", { + text(element) { + errorDetails += element.text; + }, + }); + + htmlRewriter.onDocument({ + end(end) { + if ( + response.status === 400 && + errorDetails.includes("Invalid Workers Preview configuration") + ) { + void sendMessageToProxyController(env, { + type: "previewTokenExpired", + proxyData, + }); + } + + // if liveReload enabled, append a script tag + // TODO: compare to existing nodejs implementation + if (proxyData.liveReload) { + const websocketUrl = new URL(request.url); + websocketUrl.protocol = + websocketUrl.protocol === "http:" ? "ws:" : "wss:"; + + end.append(liveReloadScript, { html: true }); + } + }, + }); + + return htmlRewriter.transform(response); +} + +const liveReloadScript = ` + +`; + +/** + * Rewrite references to URLs in request/response headers. + * + * This function is used to map the URLs in headers like Origin and Access-Control-Allow-Origin + * so that this proxy is transparent to the Client Browser and User Worker. + */ +function rewriteUrlRelatedHeaders(headers: Headers, from: URL, to: URL) { + const setCookie = headers.getAll("Set-Cookie"); + headers.delete("Set-Cookie"); + headers.forEach((value, key) => { + if (typeof value === "string" && value.includes(from.host)) { + headers.set( + key, + value.replaceAll(from.origin, to.origin).replaceAll(from.host, to.host) + ); + } + }); + for (const cookie of setCookie) { + headers.append( + "Set-Cookie", + cookie.replace( + new RegExp(`Domain=${from.hostname}($|;|,)`), + `Domain=${to.hostname}$1` + ) + ); + } +} diff --git a/worker/node_modules/wrangler/wrangler-dist/InspectorProxyWorker.js b/worker/node_modules/wrangler/wrangler-dist/InspectorProxyWorker.js new file mode 100644 index 0000000000000000000000000000000000000000..5c8be395fea9bb5a5f7e221ca896928a42226e4e --- /dev/null +++ b/worker/node_modules/wrangler/wrangler-dist/InspectorProxyWorker.js @@ -0,0 +1,464 @@ +// templates/startDevWorker/InspectorProxyWorker.ts +import assert2 from "node:assert"; + +// src/api/startDevWorker/events.ts +function serialiseError(e) { + if (e instanceof Error) { + return { + message: e.message, + name: e.name, + stack: e.stack, + cause: e.cause && serialiseError(e.cause) + }; + } else { + return { message: String(e) }; + } +} + +// src/api/startDevWorker/utils.ts +import assert from "node:assert"; +function createDeferred(previousDeferred) { + let resolve, reject; + const newPromise = new Promise((_resolve, _reject) => { + resolve = _resolve; + reject = _reject; + }); + assert(resolve); + assert(reject); + previousDeferred?.resolve(newPromise); + return { + promise: newPromise, + resolve, + reject + }; +} +function assertNever(_value) { +} +function urlFromParts(parts, base = "http://localhost") { + const url = new URL(base); + Object.assign(url, parts); + return url; +} + +// templates/startDevWorker/InspectorProxyWorker.ts +var ALLOWED_HOST_HOSTNAMES = ["127.0.0.1", "[::1]", "localhost"]; +var ALLOWED_ORIGIN_HOSTNAMES = [ + "devtools.devprod.cloudflare.dev", + "cloudflare-devtools.pages.dev", + /^[a-z0-9]+\.cloudflare-devtools\.pages\.dev$/, + "127.0.0.1", + "[::1]", + "localhost" +]; +var InspectorProxyWorker_default = { + fetch(req, env) { + const singleton = env.DURABLE_OBJECT.idFromName(""); + const inspectorProxy = env.DURABLE_OBJECT.get(singleton); + return inspectorProxy.fetch(req); + } +}; +function isDevToolsEvent(event, name) { + return typeof event === "object" && event !== null && "method" in event && event.method === name; +} +var InspectorProxyWorker = class { + constructor(_state, env) { + this.env = env; + } + websockets = { + runtimeDeferred: createDeferred() + }; + proxyData; + runtimeMessageBuffer = []; + async fetch(req) { + if (req.headers.get("Authorization") === this.env.PROXY_CONTROLLER_AUTH_SECRET) { + return this.handleProxyControllerRequest(req); + } + if (req.headers.get("Upgrade") === "websocket") { + return this.handleDevToolsWebSocketUpgradeRequest(req); + } + return this.handleDevToolsJsonRequest(req); + } + // ************************ + // ** PROXY CONTROLLER ** + // ************************ + handleProxyControllerRequest(req) { + assert2( + req.headers.get("Upgrade") === "websocket", + "Expected proxy controller data request to be WebSocket upgrade" + ); + const { 0: response, 1: proxyController } = new WebSocketPair(); + proxyController.accept(); + proxyController.addEventListener("close", (event) => { + this.sendDebugLog( + "PROXY CONTROLLER WEBSOCKET CLOSED", + event.code, + event.reason + ); + if (this.websockets.proxyController === proxyController) { + this.websockets.proxyController = void 0; + } + }); + proxyController.addEventListener("error", (event) => { + const error = serialiseError(event.error); + this.sendDebugLog("PROXY CONTROLLER WEBSOCKET ERROR", error); + if (this.websockets.proxyController === proxyController) { + this.websockets.proxyController = void 0; + } + }); + proxyController.addEventListener( + "message", + this.handleProxyControllerIncomingMessage + ); + this.websockets.proxyController = proxyController; + return new Response(null, { + status: 101, + webSocket: response + }); + } + handleProxyControllerIncomingMessage = (event) => { + assert2( + typeof event.data === "string", + "Expected event.data from proxy controller to be string" + ); + const message = JSON.parse( + event.data + ); + this.sendDebugLog("handleProxyControllerIncomingMessage", event.data); + switch (message.type) { + case "reloadStart": { + this.sendRuntimeDiscardConsoleEntries(); + break; + } + case "reloadComplete": { + this.proxyData = message.proxyData; + this.reconnectRuntimeWebSocket(); + break; + } + default: { + assertNever(message); + } + } + }; + sendProxyControllerMessage(message) { + message = typeof message === "string" ? message : JSON.stringify(message); + this.websockets.proxyController?.send(message); + } + async sendProxyControllerRequest(message) { + try { + const res = await this.env.PROXY_CONTROLLER.fetch("http://dummy", { + method: "POST", + body: JSON.stringify(message) + }); + return res.ok ? await res.text() : void 0; + } catch (e) { + this.sendDebugLog( + "FAILED TO SEND PROXY CONTROLLER REQUEST", + serialiseError(e) + ); + return void 0; + } + } + sendDebugLog = (...args) => { + this.sendProxyControllerRequest({ type: "debug-log", args }); + }; + // *************** + // ** RUNTIME ** + // *************** + handleRuntimeIncomingMessage = (event) => { + assert2(typeof event.data === "string"); + const msg = JSON.parse(event.data); + this.sendDebugLog("RUNTIME INCOMING MESSAGE", msg); + if (isDevToolsEvent(msg, "Runtime.exceptionThrown")) { + this.sendProxyControllerMessage(event.data); + } + if (this.proxyData?.proxyLogsToController && isDevToolsEvent(msg, "Runtime.consoleAPICalled")) { + this.sendProxyControllerMessage(event.data); + } + this.runtimeMessageBuffer.push(msg); + this.tryDrainRuntimeMessageBuffer(); + }; + handleRuntimeScriptParsed(msg) { + if (!this.websockets.devtoolsHasFileSystemAccess && msg.params.sourceMapURL !== void 0 && // Don't try to find a sourcemap for e.g. node-internal: scripts + msg.params.url.startsWith("file:")) { + const url = new URL(msg.params.sourceMapURL, msg.params.url); + if (url.protocol === "file:") { + msg.params.sourceMapURL = url.href.replace("file:", "wrangler-file:"); + } + } + void this.sendDevToolsMessage(msg); + } + tryDrainRuntimeMessageBuffer = () => { + if (this.websockets.devtools === void 0) + return; + for (const msg of this.runtimeMessageBuffer.splice(0)) { + if (isDevToolsEvent(msg, "Debugger.scriptParsed")) { + this.handleRuntimeScriptParsed(msg); + } else { + void this.sendDevToolsMessage(msg); + } + } + }; + runtimeAbortController = new AbortController(); + // will abort the in-flight websocket upgrade request to the remote runtime + runtimeKeepAliveInterval = null; + async reconnectRuntimeWebSocket() { + assert2(this.proxyData, "Expected this.proxyData to be defined"); + this.sendDebugLog("reconnectRuntimeWebSocket"); + this.websockets.runtime?.close(); + this.websockets.runtime = void 0; + this.runtimeAbortController.abort(); + this.runtimeAbortController = new AbortController(); + this.websockets.runtimeDeferred = createDeferred( + this.websockets.runtimeDeferred + ); + const runtimeWebSocketUrl = urlFromParts( + this.proxyData.userWorkerInspectorUrl + ); + runtimeWebSocketUrl.protocol = this.proxyData.userWorkerUrl.protocol; + this.sendDebugLog("NEW RUNTIME WEBSOCKET", runtimeWebSocketUrl); + this.sendDevToolsMessage({ + method: "Runtime.executionContextsCleared", + params: void 0 + }); + const upgrade = await fetch(runtimeWebSocketUrl, { + headers: { + ...this.proxyData.headers, + Upgrade: "websocket" + }, + signal: this.runtimeAbortController.signal + }); + const runtime = upgrade.webSocket; + if (!runtime) { + const error = new Error( + `Failed to establish the WebSocket connection: expected server to reply with HTTP status code 101 (switching protocols), but received ${upgrade.status} instead.` + ); + this.websockets.runtimeDeferred.reject(error); + this.sendProxyControllerRequest({ + type: "runtime-websocket-error", + error: serialiseError(error) + }); + return; + } + this.websockets.runtime = runtime; + runtime.addEventListener("message", this.handleRuntimeIncomingMessage); + runtime.addEventListener("close", (event) => { + this.sendDebugLog("RUNTIME WEBSOCKET CLOSED", event.code, event.reason); + clearInterval(this.runtimeKeepAliveInterval); + if (this.websockets.runtime === runtime) { + this.websockets.runtime = void 0; + } + }); + runtime.addEventListener("error", (event) => { + const error = serialiseError(event.error); + this.sendDebugLog("RUNTIME WEBSOCKET ERROR", error); + clearInterval(this.runtimeKeepAliveInterval); + if (this.websockets.runtime === runtime) { + this.websockets.runtime = void 0; + } + this.sendProxyControllerRequest({ + type: "runtime-websocket-error", + error + }); + }); + runtime.accept(); + this.handleRuntimeWebSocketOpen(runtime); + } + #runtimeMessageCounter = 1e8; + nextCounter() { + return ++this.#runtimeMessageCounter; + } + handleRuntimeWebSocketOpen(runtime) { + this.sendDebugLog("RUNTIME WEBSOCKET OPENED"); + this.sendRuntimeMessage( + { method: "Runtime.enable", id: this.nextCounter() }, + runtime + ); + this.sendRuntimeMessage( + { method: "Debugger.enable", id: this.nextCounter() }, + runtime + ); + this.sendRuntimeMessage( + { method: "Network.enable", id: this.nextCounter() }, + runtime + ); + clearInterval(this.runtimeKeepAliveInterval); + this.runtimeKeepAliveInterval = setInterval(() => { + this.sendRuntimeMessage( + { method: "Runtime.getIsolateId", id: this.nextCounter() }, + runtime + ); + }, 1e4); + this.websockets.runtimeDeferred.resolve(runtime); + } + sendRuntimeDiscardConsoleEntries() { + if (this.websockets.runtime) { + this.sendRuntimeMessage( + { + method: "Runtime.discardConsoleEntries", + id: this.nextCounter() + }, + this.websockets.runtime + ); + } + } + async sendRuntimeMessage(message, runtime = this.websockets.runtimeDeferred.promise) { + runtime = await runtime; + message = typeof message === "string" ? message : JSON.stringify(message); + this.sendDebugLog("SEND TO RUNTIME", message); + runtime.send(message); + } + // **************** + // ** DEVTOOLS ** + // **************** + #inspectorId = crypto.randomUUID(); + async handleDevToolsJsonRequest(req) { + const url = new URL(req.url); + if (url.pathname === "/json/version") { + return Response.json({ + Browser: `wrangler/v${this.env.WRANGLER_VERSION}`, + // TODO: (someday): The DevTools protocol should match that of workerd. + // This could be exposed by the preview API. + "Protocol-Version": "1.3" + }); + } + if (url.pathname === "/json" || url.pathname === "/json/list") { + const localHost = `${url.host}/ws`; + const devtoolsFrontendUrl = `https://devtools.devprod.cloudflare.dev/js_app?theme=systemPreferred&debugger=true&ws=${localHost}`; + return Response.json([ + { + id: this.#inspectorId, + type: "node", + // TODO: can we specify different type? + description: "workers", + webSocketDebuggerUrl: `ws://${localHost}`, + devtoolsFrontendUrl, + devtoolsFrontendUrlCompat: devtoolsFrontendUrl, + // Below are fields that are visible in the DevTools UI. + title: "Cloudflare Worker", + faviconUrl: "https://workers.cloudflare.com/favicon.ico" + // url: "http://" + localHost, // looks unnecessary + } + ]); + } + return new Response(null, { status: 404 }); + } + async handleDevToolsWebSocketUpgradeRequest(req) { + let hostHeader = req.headers.get("Host"); + if (hostHeader == null) + return new Response(null, { status: 400 }); + try { + const host = new URL(`http://${hostHeader}`); + if (!ALLOWED_HOST_HOSTNAMES.includes(host.hostname)) { + return new Response("Disallowed `Host` header", { status: 401 }); + } + } catch { + return new Response("Expected `Host` header", { status: 400 }); + } + let originHeader = req.headers.get("Origin"); + if (originHeader === null && !req.headers.has("User-Agent")) { + originHeader = "http://localhost"; + } + if (originHeader === null) { + return new Response("Expected `Origin` header", { status: 400 }); + } + try { + const origin = new URL(originHeader); + const allowed = ALLOWED_ORIGIN_HOSTNAMES.some((rule) => { + if (typeof rule === "string") + return origin.hostname === rule; + else + return rule.test(origin.hostname); + }); + if (!allowed) { + return new Response("Disallowed `Origin` header", { status: 401 }); + } + } catch { + return new Response("Expected `Origin` header", { status: 400 }); + } + this.sendDebugLog("DEVTOOLS WEBSOCKET TRYING TO CONNECT"); + await this.websockets.runtimeDeferred.promise; + this.sendDebugLog("DEVTOOLS WEBSOCKET CAN NOW CONNECT"); + assert2( + req.headers.get("Upgrade") === "websocket", + "Expected DevTools connection to be WebSocket upgrade" + ); + const { 0: response, 1: devtools } = new WebSocketPair(); + devtools.accept(); + if (this.websockets.devtools !== void 0) { + devtools.close( + 1013, + "Too many clients; only one can be connected at a time" + ); + } else { + devtools.addEventListener("message", this.handleDevToolsIncomingMessage); + devtools.addEventListener("close", (event) => { + this.sendDebugLog( + "DEVTOOLS WEBSOCKET CLOSED", + event.code, + event.reason + ); + if (this.websockets.devtools === devtools) { + this.websockets.devtools = void 0; + } + }); + devtools.addEventListener("error", (event) => { + const error = serialiseError(event.error); + this.sendDebugLog("DEVTOOLS WEBSOCKET ERROR", error); + if (this.websockets.devtools === devtools) { + this.websockets.devtools = void 0; + } + }); + this.sendRuntimeMessage({ + id: this.nextCounter(), + method: "Debugger.disable" + }); + this.sendDebugLog("DEVTOOLS WEBSOCKET CONNECTED"); + const userAgent = req.headers.get("User-Agent") ?? ""; + const hasFileSystemAccess = !/mozilla/i.test(userAgent); + this.websockets.devtools = devtools; + this.websockets.devtoolsHasFileSystemAccess = hasFileSystemAccess; + this.tryDrainRuntimeMessageBuffer(); + } + return new Response(null, { status: 101, webSocket: response }); + } + handleDevToolsIncomingMessage = (event) => { + assert2( + typeof event.data === "string", + "Expected devtools incoming message to be of type string" + ); + const message = JSON.parse(event.data); + this.sendDebugLog("DEVTOOLS INCOMING MESSAGE", message); + if (message.method === "Network.loadNetworkResource") { + return void this.handleDevToolsLoadNetworkResource(message); + } + this.sendRuntimeMessage(JSON.stringify(message)); + }; + async handleDevToolsLoadNetworkResource(message) { + const response = await this.sendProxyControllerRequest({ + type: "load-network-resource", + url: message.params.url + }); + if (response === void 0) { + this.sendDebugLog( + `ProxyController could not resolve Network.loadNetworkResource for "${message.params.url}"` + ); + this.sendRuntimeMessage(JSON.stringify(message)); + } else { + this.sendDevToolsMessage({ + id: message.id, + // @ts-expect-error DevTools Protocol type does not match our patched devtools -- result.resource.text was added + result: { resource: { success: true, text: response } } + }); + } + } + sendDevToolsMessage(message) { + message = typeof message === "string" ? message : JSON.stringify(message); + this.sendDebugLog("SEND TO DEVTOOLS", message); + this.websockets.devtools?.send(message); + } +}; +export { + InspectorProxyWorker, + InspectorProxyWorker_default as default +}; +//# sourceMappingURL=InspectorProxyWorker.js.map diff --git a/worker/node_modules/wrangler/wrangler-dist/ProxyWorker.js b/worker/node_modules/wrangler/wrangler-dist/ProxyWorker.js new file mode 100644 index 0000000000000000000000000000000000000000..ec71e8fdb6ffc650055ffd21bdb762c48f758db7 --- /dev/null +++ b/worker/node_modules/wrangler/wrangler-dist/ProxyWorker.js @@ -0,0 +1,241 @@ +// src/api/startDevWorker/utils.ts +import assert from "node:assert"; +function createDeferred(previousDeferred) { + let resolve, reject; + const newPromise = new Promise((_resolve, _reject) => { + resolve = _resolve; + reject = _reject; + }); + assert(resolve); + assert(reject); + previousDeferred?.resolve(newPromise); + return { + promise: newPromise, + resolve, + reject + }; +} +function urlFromParts(parts, base = "http://localhost") { + const url = new URL(base); + Object.assign(url, parts); + return url; +} + +// templates/startDevWorker/ProxyWorker.ts +var LIVE_RELOAD_PROTOCOL = "WRANGLER_PROXYWORKER_LIVE_RELOAD_PROTOCOL"; +var ProxyWorker_default = { + fetch(req, env) { + const singleton = env.DURABLE_OBJECT.idFromName(""); + const inspectorProxy = env.DURABLE_OBJECT.get(singleton); + return inspectorProxy.fetch(req); + } +}; +var ProxyWorker = class { + constructor(state, env) { + this.state = state; + this.env = env; + } + proxyData; + requestQueue = /* @__PURE__ */ new Map(); + requestRetryQueue = /* @__PURE__ */ new Map(); + fetch(request) { + if (isRequestForLiveReloadWebsocket(request)) { + return this.handleLiveReloadWebSocket(request); + } + if (isRequestFromProxyController(request, this.env)) { + return this.processProxyControllerRequest(request); + } + const deferred = createDeferred(); + this.requestQueue.set(request, deferred); + this.processQueue(); + return deferred.promise; + } + handleLiveReloadWebSocket(request) { + const { 0: response, 1: liveReload } = new WebSocketPair(); + const websocketProtocol = request.headers.get("Sec-WebSocket-Protocol") ?? ""; + this.state.acceptWebSocket(liveReload, ["live-reload"]); + return new Response(null, { + status: 101, + webSocket: response, + headers: { "Sec-WebSocket-Protocol": websocketProtocol } + }); + } + processProxyControllerRequest(request) { + const event = request.cf?.hostMetadata; + switch (event?.type) { + case "pause": + this.proxyData = void 0; + break; + case "play": + this.proxyData = event.proxyData; + this.processQueue(); + this.state.getWebSockets("live-reload").forEach((ws) => ws.send("reload")); + break; + } + return new Response(null, { status: 204 }); + } + /** + * Process requests that are being retried first, then process newer requests. + * Requests that are being retried are, by definition, older than requests which haven't been processed yet. + * We don't need to be more accurate than this re ordering, since the requests are being fired off synchronously. + */ + *getOrderedQueue() { + yield* this.requestRetryQueue; + yield* this.requestQueue; + } + processQueue() { + const { proxyData } = this; + if (proxyData === void 0) + return; + for (const [request, deferredResponse] of this.getOrderedQueue()) { + this.requestRetryQueue.delete(request); + this.requestQueue.delete(request); + const outerUrl = new URL(request.url); + const headers = new Headers(request.headers); + const userWorkerUrl = new URL(request.url); + Object.assign(userWorkerUrl, proxyData.userWorkerUrl); + const innerUrl = urlFromParts( + proxyData.userWorkerInnerUrlOverrides ?? {}, + request.url + ); + headers.set("MF-Original-URL", innerUrl.href); + headers.set("MF-Disable-Pretty-Error", "true"); + const encoding = request.cf?.clientAcceptEncoding; + if (encoding !== void 0) + headers.set("Accept-Encoding", encoding); + rewriteUrlRelatedHeaders(headers, outerUrl, innerUrl); + for (const [key, value] of Object.entries(proxyData.headers ?? {})) { + if (value === void 0) + continue; + if (key.toLowerCase() === "cookie") { + const existing = request.headers.get("cookie") ?? ""; + headers.set("cookie", `${existing};${value}`); + } else { + headers.set(key, value); + } + } + void fetch(userWorkerUrl, new Request(request, { headers })).then((res) => { + res = new Response(res.body, res); + rewriteUrlRelatedHeaders(res.headers, innerUrl, outerUrl); + if (isHtmlResponse(res)) { + res = insertLiveReloadScript(request, res, this.env, proxyData); + } + deferredResponse.resolve(res); + }).catch((error) => { + const newUserWorkerUrl = this.proxyData && urlFromParts(this.proxyData.userWorkerUrl); + if (userWorkerUrl.href === newUserWorkerUrl?.href) { + void sendMessageToProxyController(this.env, { + type: "error", + error: { + name: error.name, + message: error.message, + stack: error.stack, + cause: error.cause + } + }); + deferredResponse.reject(error); + } else if (request.method === "GET" || request.method === "HEAD") { + this.requestRetryQueue.set(request, deferredResponse); + } else { + deferredResponse.resolve( + new Response( + "Your worker restarted mid-request. Please try sending the request again. Only GET or HEAD requests are retried automatically.", + { + status: 503, + headers: { "Retry-After": "0" } + } + ) + ); + } + }); + } + } +}; +function isRequestFromProxyController(req, env) { + return req.headers.get("Authorization") === env.PROXY_CONTROLLER_AUTH_SECRET; +} +function isHtmlResponse(res) { + return res.headers.get("content-type")?.startsWith("text/html") ?? false; +} +function isRequestForLiveReloadWebsocket(req) { + const websocketProtocol = req.headers.get("Sec-WebSocket-Protocol"); + const isWebSocketUpgrade = req.headers.get("Upgrade") === "websocket"; + return isWebSocketUpgrade && websocketProtocol === LIVE_RELOAD_PROTOCOL; +} +function sendMessageToProxyController(env, message) { + return env.PROXY_CONTROLLER.fetch("http://dummy", { + method: "POST", + body: JSON.stringify(message) + }); +} +function insertLiveReloadScript(request, response, env, proxyData) { + const htmlRewriter = new HTMLRewriter(); + let errorDetails = ""; + htmlRewriter.on("#cf-error-details", { + text(element) { + errorDetails += element.text; + } + }); + htmlRewriter.onDocument({ + end(end) { + if (response.status === 400 && errorDetails.includes("Invalid Workers Preview configuration")) { + void sendMessageToProxyController(env, { + type: "previewTokenExpired", + proxyData + }); + } + if (proxyData.liveReload) { + const websocketUrl = new URL(request.url); + websocketUrl.protocol = websocketUrl.protocol === "http:" ? "ws:" : "wss:"; + end.append(liveReloadScript, { html: true }); + } + } + }); + return htmlRewriter.transform(response); +} +var liveReloadScript = ` + +`; +function rewriteUrlRelatedHeaders(headers, from, to) { + const setCookie = headers.getAll("Set-Cookie"); + headers.delete("Set-Cookie"); + headers.forEach((value, key) => { + if (typeof value === "string" && value.includes(from.host)) { + headers.set( + key, + value.replaceAll(from.origin, to.origin).replaceAll(from.host, to.host) + ); + } + }); + for (const cookie of setCookie) { + headers.append( + "Set-Cookie", + cookie.replace( + new RegExp(`Domain=${from.hostname}($|;|,)`), + `Domain=${to.hostname}$1` + ) + ); + } +} +export { + ProxyWorker, + ProxyWorker_default as default +}; +//# sourceMappingURL=ProxyWorker.js.map diff --git a/worker/node_modules/zod/lib/index.umd.js b/worker/node_modules/zod/lib/index.umd.js new file mode 100644 index 0000000000000000000000000000000000000000..8b1f963ba6664a96612e318ebe82641758b78a64 --- /dev/null +++ b/worker/node_modules/zod/lib/index.umd.js @@ -0,0 +1,4120 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Zod = {})); +})(this, (function (exports) { 'use strict'; + + exports.util = void 0; + (function (util) { + util.assertEqual = (val) => val; + function assertIs(_arg) { } + util.assertIs = assertIs; + function assertNever(_x) { + throw new Error(); + } + util.assertNever = assertNever; + util.arrayToEnum = (items) => { + const obj = {}; + for (const item of items) { + obj[item] = item; + } + return obj; + }; + util.getValidEnumValues = (obj) => { + const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); + const filtered = {}; + for (const k of validKeys) { + filtered[k] = obj[k]; + } + return util.objectValues(filtered); + }; + util.objectValues = (obj) => { + return util.objectKeys(obj).map(function (e) { + return obj[e]; + }); + }; + util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban + ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban + : (object) => { + const keys = []; + for (const key in object) { + if (Object.prototype.hasOwnProperty.call(object, key)) { + keys.push(key); + } + } + return keys; + }; + util.find = (arr, checker) => { + for (const item of arr) { + if (checker(item)) + return item; + } + return undefined; + }; + util.isInteger = typeof Number.isInteger === "function" + ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban + : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val; + function joinValues(array, separator = " | ") { + return array + .map((val) => (typeof val === "string" ? `'${val}'` : val)) + .join(separator); + } + util.joinValues = joinValues; + util.jsonStringifyReplacer = (_, value) => { + if (typeof value === "bigint") { + return value.toString(); + } + return value; + }; + })(exports.util || (exports.util = {})); + exports.objectUtil = void 0; + (function (objectUtil) { + objectUtil.mergeShapes = (first, second) => { + return { + ...first, + ...second, // second overwrites first + }; + }; + })(exports.objectUtil || (exports.objectUtil = {})); + const ZodParsedType = exports.util.arrayToEnum([ + "string", + "nan", + "number", + "integer", + "float", + "boolean", + "date", + "bigint", + "symbol", + "function", + "undefined", + "null", + "array", + "object", + "unknown", + "promise", + "void", + "never", + "map", + "set", + ]); + const getParsedType = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return ZodParsedType.undefined; + case "string": + return ZodParsedType.string; + case "number": + return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; + case "boolean": + return ZodParsedType.boolean; + case "function": + return ZodParsedType.function; + case "bigint": + return ZodParsedType.bigint; + case "symbol": + return ZodParsedType.symbol; + case "object": + if (Array.isArray(data)) { + return ZodParsedType.array; + } + if (data === null) { + return ZodParsedType.null; + } + if (data.then && + typeof data.then === "function" && + data.catch && + typeof data.catch === "function") { + return ZodParsedType.promise; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return ZodParsedType.map; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return ZodParsedType.set; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return ZodParsedType.date; + } + return ZodParsedType.object; + default: + return ZodParsedType.unknown; + } + }; + + const ZodIssueCode = exports.util.arrayToEnum([ + "invalid_type", + "invalid_literal", + "custom", + "invalid_union", + "invalid_union_discriminator", + "invalid_enum_value", + "unrecognized_keys", + "invalid_arguments", + "invalid_return_type", + "invalid_date", + "invalid_string", + "too_small", + "too_big", + "invalid_intersection_types", + "not_multiple_of", + "not_finite", + ]); + const quotelessJson = (obj) => { + const json = JSON.stringify(obj, null, 2); + return json.replace(/"([^"]+)":/g, "$1:"); + }; + class ZodError extends Error { + constructor(issues) { + super(); + this.issues = []; + this.addIssue = (sub) => { + this.issues = [...this.issues, sub]; + }; + this.addIssues = (subs = []) => { + this.issues = [...this.issues, ...subs]; + }; + const actualProto = new.target.prototype; + if (Object.setPrototypeOf) { + // eslint-disable-next-line ban/ban + Object.setPrototypeOf(this, actualProto); + } + else { + this.__proto__ = actualProto; + } + this.name = "ZodError"; + this.issues = issues; + } + get errors() { + return this.issues; + } + format(_mapper) { + const mapper = _mapper || + function (issue) { + return issue.message; + }; + const fieldErrors = { _errors: [] }; + const processError = (error) => { + for (const issue of error.issues) { + if (issue.code === "invalid_union") { + issue.unionErrors.map(processError); + } + else if (issue.code === "invalid_return_type") { + processError(issue.returnTypeError); + } + else if (issue.code === "invalid_arguments") { + processError(issue.argumentsError); + } + else if (issue.path.length === 0) { + fieldErrors._errors.push(mapper(issue)); + } + else { + let curr = fieldErrors; + let i = 0; + while (i < issue.path.length) { + const el = issue.path[i]; + const terminal = i === issue.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + // if (typeof el === "string") { + // curr[el] = curr[el] || { _errors: [] }; + // } else if (typeof el === "number") { + // const errorArray: any = []; + // errorArray._errors = []; + // curr[el] = curr[el] || errorArray; + // } + } + else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue)); + } + curr = curr[el]; + i++; + } + } + } + }; + processError(this); + return fieldErrors; + } + toString() { + return this.message; + } + get message() { + return JSON.stringify(this.issues, exports.util.jsonStringifyReplacer, 2); + } + get isEmpty() { + return this.issues.length === 0; + } + flatten(mapper = (issue) => issue.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of this.issues) { + if (sub.path.length > 0) { + fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; + fieldErrors[sub.path[0]].push(mapper(sub)); + } + else { + formErrors.push(mapper(sub)); + } + } + return { formErrors, fieldErrors }; + } + get formErrors() { + return this.flatten(); + } + } + ZodError.create = (issues) => { + const error = new ZodError(issues); + return error; + }; + + const errorMap = (issue, _ctx) => { + let message; + switch (issue.code) { + case ZodIssueCode.invalid_type: + if (issue.received === ZodParsedType.undefined) { + message = "Required"; + } + else { + message = `Expected ${issue.expected}, received ${issue.received}`; + } + break; + case ZodIssueCode.invalid_literal: + message = `Invalid literal value, expected ${JSON.stringify(issue.expected, exports.util.jsonStringifyReplacer)}`; + break; + case ZodIssueCode.unrecognized_keys: + message = `Unrecognized key(s) in object: ${exports.util.joinValues(issue.keys, ", ")}`; + break; + case ZodIssueCode.invalid_union: + message = `Invalid input`; + break; + case ZodIssueCode.invalid_union_discriminator: + message = `Invalid discriminator value. Expected ${exports.util.joinValues(issue.options)}`; + break; + case ZodIssueCode.invalid_enum_value: + message = `Invalid enum value. Expected ${exports.util.joinValues(issue.options)}, received '${issue.received}'`; + break; + case ZodIssueCode.invalid_arguments: + message = `Invalid function arguments`; + break; + case ZodIssueCode.invalid_return_type: + message = `Invalid function return type`; + break; + case ZodIssueCode.invalid_date: + message = `Invalid date`; + break; + case ZodIssueCode.invalid_string: + if (typeof issue.validation === "object") { + if ("includes" in issue.validation) { + message = `Invalid input: must include "${issue.validation.includes}"`; + if (typeof issue.validation.position === "number") { + message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; + } + } + else if ("startsWith" in issue.validation) { + message = `Invalid input: must start with "${issue.validation.startsWith}"`; + } + else if ("endsWith" in issue.validation) { + message = `Invalid input: must end with "${issue.validation.endsWith}"`; + } + else { + exports.util.assertNever(issue.validation); + } + } + else if (issue.validation !== "regex") { + message = `Invalid ${issue.validation}`; + } + else { + message = "Invalid"; + } + break; + case ZodIssueCode.too_small: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact + ? `exactly equal to ` + : issue.inclusive + ? `greater than or equal to ` + : `greater than `}${issue.minimum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact + ? `exactly equal to ` + : issue.inclusive + ? `greater than or equal to ` + : `greater than `}${new Date(Number(issue.minimum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode.too_big: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact + ? `exactly` + : issue.inclusive + ? `less than or equal to` + : `less than`} ${issue.maximum}`; + else if (issue.type === "bigint") + message = `BigInt must be ${issue.exact + ? `exactly` + : issue.inclusive + ? `less than or equal to` + : `less than`} ${issue.maximum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact + ? `exactly` + : issue.inclusive + ? `smaller than or equal to` + : `smaller than`} ${new Date(Number(issue.maximum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode.custom: + message = `Invalid input`; + break; + case ZodIssueCode.invalid_intersection_types: + message = `Intersection results could not be merged`; + break; + case ZodIssueCode.not_multiple_of: + message = `Number must be a multiple of ${issue.multipleOf}`; + break; + case ZodIssueCode.not_finite: + message = "Number must be finite"; + break; + default: + message = _ctx.defaultError; + exports.util.assertNever(issue); + } + return { message }; + }; + + let overrideErrorMap = errorMap; + function setErrorMap(map) { + overrideErrorMap = map; + } + function getErrorMap() { + return overrideErrorMap; + } + + const makeIssue = (params) => { + const { data, path, errorMaps, issueData } = params; + const fullPath = [...path, ...(issueData.path || [])]; + const fullIssue = { + ...issueData, + path: fullPath, + }; + let errorMessage = ""; + const maps = errorMaps + .filter((m) => !!m) + .slice() + .reverse(); + for (const map of maps) { + errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; + } + return { + ...issueData, + path: fullPath, + message: issueData.message || errorMessage, + }; + }; + const EMPTY_PATH = []; + function addIssueToContext(ctx, issueData) { + const issue = makeIssue({ + issueData: issueData, + data: ctx.data, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + getErrorMap(), + errorMap, // then global default map + ].filter((x) => !!x), + }); + ctx.common.issues.push(issue); + } + class ParseStatus { + constructor() { + this.value = "valid"; + } + dirty() { + if (this.value === "valid") + this.value = "dirty"; + } + abort() { + if (this.value !== "aborted") + this.value = "aborted"; + } + static mergeArray(status, results) { + const arrayValue = []; + for (const s of results) { + if (s.status === "aborted") + return INVALID; + if (s.status === "dirty") + status.dirty(); + arrayValue.push(s.value); + } + return { status: status.value, value: arrayValue }; + } + static async mergeObjectAsync(status, pairs) { + const syncPairs = []; + for (const pair of pairs) { + syncPairs.push({ + key: await pair.key, + value: await pair.value, + }); + } + return ParseStatus.mergeObjectSync(status, syncPairs); + } + static mergeObjectSync(status, pairs) { + const finalObject = {}; + for (const pair of pairs) { + const { key, value } = pair; + if (key.status === "aborted") + return INVALID; + if (value.status === "aborted") + return INVALID; + if (key.status === "dirty") + status.dirty(); + if (value.status === "dirty") + status.dirty(); + if (key.value !== "__proto__" && + (typeof value.value !== "undefined" || pair.alwaysSet)) { + finalObject[key.value] = value.value; + } + } + return { status: status.value, value: finalObject }; + } + } + const INVALID = Object.freeze({ + status: "aborted", + }); + const DIRTY = (value) => ({ status: "dirty", value }); + const OK = (value) => ({ status: "valid", value }); + const isAborted = (x) => x.status === "aborted"; + const isDirty = (x) => x.status === "dirty"; + const isValid = (x) => x.status === "valid"; + const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; + + var errorUtil; + (function (errorUtil) { + errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {}; + errorUtil.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message; + })(errorUtil || (errorUtil = {})); + + class ParseInputLazyPath { + constructor(parent, value, path, key) { + this._cachedPath = []; + this.parent = parent; + this.data = value; + this._path = path; + this._key = key; + } + get path() { + if (!this._cachedPath.length) { + if (this._key instanceof Array) { + this._cachedPath.push(...this._path, ...this._key); + } + else { + this._cachedPath.push(...this._path, this._key); + } + } + return this._cachedPath; + } + } + const handleResult = (ctx, result) => { + 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._error) + return this._error; + const error = new ZodError(ctx.common.issues); + this._error = error; + return this._error; + }, + }; + } + }; + function processCreateParams(params) { + 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 = (iss, ctx) => { + if (iss.code !== "invalid_type") + return { message: ctx.defaultError }; + if (typeof ctx.data === "undefined") { + return { message: required_error !== null && required_error !== void 0 ? required_error : ctx.defaultError }; + } + return { message: invalid_type_error !== null && invalid_type_error !== void 0 ? invalid_type_error : ctx.defaultError }; + }; + return { errorMap: customMap, description }; + } + class ZodType { + constructor(def) { + /** Alias of safeParseAsync */ + this.spa = this.safeParseAsync; + 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); + } + get description() { + return this._def.description; + } + _getType(input) { + return getParsedType(input.data); + } + _getOrReturnCtx(input, ctx) { + 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) { + 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) { + const result = this._parse(input); + if (isAsync(result)) { + throw new Error("Synchronous parse encountered promise."); + } + return result; + } + _parseAsync(input) { + const result = this._parse(input); + return Promise.resolve(result); + } + parse(data, params) { + const result = this.safeParse(data, params); + if (result.success) + return result.data; + throw result.error; + } + safeParse(data, params) { + var _a; + const ctx = { + common: { + issues: [], + async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false, + contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, + }, + path: (params === null || params === void 0 ? void 0 : 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); + } + async parseAsync(data, params) { + const result = await this.safeParseAsync(data, params); + if (result.success) + return result.data; + throw result.error; + } + async safeParseAsync(data, params) { + const ctx = { + common: { + issues: [], + contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, + async: true, + }, + path: (params === null || params === void 0 ? void 0 : 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); + } + refine(check, message) { + const getIssueProperties = (val) => { + 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, refinementData) { + return this._refinement((val, ctx) => { + if (!check(val)) { + ctx.addIssue(typeof refinementData === "function" + ? refinementData(val, ctx) + : refinementData); + return false; + } + else { + return true; + } + }); + } + _refinement(refinement) { + return new ZodEffects({ + schema: this, + typeName: exports.ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "refinement", refinement }, + }); + } + superRefine(refinement) { + return this._refinement(refinement); + } + optional() { + return ZodOptional.create(this, this._def); + } + nullable() { + return ZodNullable.create(this, this._def); + } + nullish() { + return this.nullable().optional(); + } + array() { + return ZodArray.create(this, this._def); + } + promise() { + return ZodPromise.create(this, this._def); + } + or(option) { + return ZodUnion.create([this, option], this._def); + } + and(incoming) { + return ZodIntersection.create(this, incoming, this._def); + } + transform(transform) { + return new ZodEffects({ + ...processCreateParams(this._def), + schema: this, + typeName: exports.ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "transform", transform }, + }); + } + default(def) { + const defaultValueFunc = typeof def === "function" ? def : () => def; + return new ZodDefault({ + ...processCreateParams(this._def), + innerType: this, + defaultValue: defaultValueFunc, + typeName: exports.ZodFirstPartyTypeKind.ZodDefault, + }); + } + brand() { + return new ZodBranded({ + typeName: exports.ZodFirstPartyTypeKind.ZodBranded, + type: this, + ...processCreateParams(this._def), + }); + } + catch(def) { + const catchValueFunc = typeof def === "function" ? def : () => def; + return new ZodCatch({ + ...processCreateParams(this._def), + innerType: this, + catchValue: catchValueFunc, + typeName: exports.ZodFirstPartyTypeKind.ZodCatch, + }); + } + describe(description) { + const This = this.constructor; + return new This({ + ...this._def, + description, + }); + } + pipe(target) { + return ZodPipeline.create(this, target); + } + readonly() { + return ZodReadonly.create(this); + } + isOptional() { + return this.safeParse(undefined).success; + } + isNullable() { + return this.safeParse(null).success; + } + } + const cuidRegex = /^c[^\s-]{8,}$/i; + const cuid2Regex = /^[a-z][a-z0-9]*$/; + const ulidRegex = /[0-9A-HJKMNP-TV-Z]{26}/; + // 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; + // 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})+$/u; + const ipv4Regex = /^(((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 = /^(([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})))$/; + // Adapted from https://stackoverflow.com/a/3143231 + const datetimeRegex = (args) => { + if (args.precision) { + if (args.offset) { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`); + } + else { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`); + } + } + else if (args.precision === 0) { + if (args.offset) { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$`); + } + else { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$`); + } + } + else { + if (args.offset) { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$`); + } + else { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$`); + } + } + }; + function isValidIP(ip, version) { + if ((version === "v4" || !version) && ipv4Regex.test(ip)) { + return true; + } + if ((version === "v6" || !version) && ipv6Regex.test(ip)) { + return true; + } + return false; + } + class ZodString extends ZodType { + constructor() { + super(...arguments); + this._regex = (regex, validation, message) => this.refinement((data) => regex.test(data), { + validation, + code: ZodIssueCode.invalid_string, + ...errorUtil.errToObj(message), + }); + /** + * @deprecated Use z.string().min(1) instead. + * @see {@link ZodString.min} + */ + this.nonempty = (message) => this.min(1, errorUtil.errToObj(message)); + this.trim = () => new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "trim" }], + }); + this.toLowerCase = () => new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toLowerCase" }], + }); + this.toUpperCase = () => new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toUpperCase" }], + }); + } + _parse(input) { + 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; + 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.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 === "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 (_a) { + 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.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.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.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 === "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 { + exports.util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + _addCheck(check) { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + email(message) { + return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); + } + url(message) { + return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); + } + emoji(message) { + return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); + } + uuid(message) { + return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); + } + cuid(message) { + return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); + } + cuid2(message) { + return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); + } + ulid(message) { + return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); + } + ip(options) { + return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); + } + datetime(options) { + var _a; + if (typeof options === "string") { + return this._addCheck({ + kind: "datetime", + precision: null, + offset: false, + message: options, + }); + } + return this._addCheck({ + kind: "datetime", + precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision, + offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false, + ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), + }); + } + regex(regex, message) { + return this._addCheck({ + kind: "regex", + regex: regex, + ...errorUtil.errToObj(message), + }); + } + includes(value, options) { + return this._addCheck({ + kind: "includes", + value: value, + position: options === null || options === void 0 ? void 0 : options.position, + ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), + }); + } + startsWith(value, message) { + return this._addCheck({ + kind: "startsWith", + value: value, + ...errorUtil.errToObj(message), + }); + } + endsWith(value, message) { + return this._addCheck({ + kind: "endsWith", + value: value, + ...errorUtil.errToObj(message), + }); + } + min(minLength, message) { + return this._addCheck({ + kind: "min", + value: minLength, + ...errorUtil.errToObj(message), + }); + } + max(maxLength, message) { + return this._addCheck({ + kind: "max", + value: maxLength, + ...errorUtil.errToObj(message), + }); + } + length(len, message) { + return this._addCheck({ + kind: "length", + value: len, + ...errorUtil.errToObj(message), + }); + } + get isDatetime() { + return !!this._def.checks.find((ch) => ch.kind === "datetime"); + } + 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 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 minLength() { + let min = 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 = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + } + ZodString.create = (params) => { + var _a; + return new ZodString({ + checks: [], + typeName: exports.ZodFirstPartyTypeKind.ZodString, + coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, + ...processCreateParams(params), + }); + }; + // https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034 + function floatSafeRemainder(val, step) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = parseInt(step.toFixed(decCount).replace(".", "")); + return (valInt % stepInt) / Math.pow(10, decCount); + } + class ZodNumber extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + this.step = this.multipleOf; + } + _parse(input) { + 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; + const status = new ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "int") { + if (!exports.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 { + exports.util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new ZodNumber({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message), + }, + ], + }); + } + _addCheck(check) { + return new ZodNumber({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + int(message) { + return this._addCheck({ + kind: "int", + message: errorUtil.toString(message), + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: false, + message: errorUtil.toString(message), + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: false, + message: errorUtil.toString(message), + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: true, + message: errorUtil.toString(message), + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: true, + message: errorUtil.toString(message), + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value: value, + message: errorUtil.toString(message), + }); + } + finite(message) { + return this._addCheck({ + kind: "finite", + message: errorUtil.toString(message), + }); + } + safe(message) { + 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 = 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 = 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" && exports.util.isInteger(ch.value))); + } + get isFinite() { + let max = null, min = 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); + } + } + ZodNumber.create = (params) => { + return new ZodNumber({ + checks: [], + typeName: exports.ZodFirstPartyTypeKind.ZodNumber, + coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, + ...processCreateParams(params), + }); + }; + class ZodBigInt extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + } + _parse(input) { + if (this._def.coerce) { + input.data = BigInt(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.bigint) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.bigint, + received: ctx.parsedType, + }); + return INVALID; + } + let ctx = 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 { + exports.util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new ZodBigInt({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message), + }, + ], + }); + } + _addCheck(check) { + return new ZodBigInt({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message), + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message), + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message), + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message), + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message), + }); + } + get minValue() { + let min = 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 = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + } + ZodBigInt.create = (params) => { + var _a; + return new ZodBigInt({ + checks: [], + typeName: exports.ZodFirstPartyTypeKind.ZodBigInt, + coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, + ...processCreateParams(params), + }); + }; + class ZodBoolean extends ZodType { + _parse(input) { + 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); + } + } + ZodBoolean.create = (params) => { + return new ZodBoolean({ + typeName: exports.ZodFirstPartyTypeKind.ZodBoolean, + coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, + ...processCreateParams(params), + }); + }; + class ZodDate extends ZodType { + _parse(input) { + 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 (isNaN(input.data.getTime())) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_date, + }); + return INVALID; + } + const status = new ParseStatus(); + let ctx = 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 { + exports.util.assertNever(check); + } + } + return { + status: status.value, + value: new Date(input.data.getTime()), + }; + } + _addCheck(check) { + return new ZodDate({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + min(minDate, message) { + return this._addCheck({ + kind: "min", + value: minDate.getTime(), + message: errorUtil.toString(message), + }); + } + max(maxDate, message) { + return this._addCheck({ + kind: "max", + value: maxDate.getTime(), + message: errorUtil.toString(message), + }); + } + get minDate() { + let min = 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 = 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; + } + } + ZodDate.create = (params) => { + return new ZodDate({ + checks: [], + coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, + typeName: exports.ZodFirstPartyTypeKind.ZodDate, + ...processCreateParams(params), + }); + }; + class ZodSymbol extends ZodType { + _parse(input) { + 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); + } + } + ZodSymbol.create = (params) => { + return new ZodSymbol({ + typeName: exports.ZodFirstPartyTypeKind.ZodSymbol, + ...processCreateParams(params), + }); + }; + class ZodUndefined extends ZodType { + _parse(input) { + 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); + } + } + ZodUndefined.create = (params) => { + return new ZodUndefined({ + typeName: exports.ZodFirstPartyTypeKind.ZodUndefined, + ...processCreateParams(params), + }); + }; + class ZodNull extends ZodType { + _parse(input) { + 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); + } + } + ZodNull.create = (params) => { + return new ZodNull({ + typeName: exports.ZodFirstPartyTypeKind.ZodNull, + ...processCreateParams(params), + }); + }; + class ZodAny extends ZodType { + constructor() { + super(...arguments); + // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject. + this._any = true; + } + _parse(input) { + return OK(input.data); + } + } + ZodAny.create = (params) => { + return new ZodAny({ + typeName: exports.ZodFirstPartyTypeKind.ZodAny, + ...processCreateParams(params), + }); + }; + class ZodUnknown extends ZodType { + constructor() { + super(...arguments); + // required + this._unknown = true; + } + _parse(input) { + return OK(input.data); + } + } + ZodUnknown.create = (params) => { + return new ZodUnknown({ + typeName: exports.ZodFirstPartyTypeKind.ZodUnknown, + ...processCreateParams(params), + }); + }; + class ZodNever extends ZodType { + _parse(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.never, + received: ctx.parsedType, + }); + return INVALID; + } + } + ZodNever.create = (params) => { + return new ZodNever({ + typeName: exports.ZodFirstPartyTypeKind.ZodNever, + ...processCreateParams(params), + }); + }; + class ZodVoid extends ZodType { + _parse(input) { + 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); + } + } + ZodVoid.create = (params) => { + return new ZodVoid({ + typeName: exports.ZodFirstPartyTypeKind.ZodVoid, + ...processCreateParams(params), + }); + }; + class ZodArray extends ZodType { + _parse(input) { + 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), + maximum: (tooBig ? def.exactLength.value : undefined), + 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].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].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, message) { + return new ZodArray({ + ...this._def, + minLength: { value: minLength, message: errorUtil.toString(message) }, + }); + } + max(maxLength, message) { + return new ZodArray({ + ...this._def, + maxLength: { value: maxLength, message: errorUtil.toString(message) }, + }); + } + length(len, message) { + return new ZodArray({ + ...this._def, + exactLength: { value: len, message: errorUtil.toString(message) }, + }); + } + nonempty(message) { + return this.min(1, message); + } + } + ZodArray.create = (schema, params) => { + return new ZodArray({ + type: schema, + minLength: null, + maxLength: null, + exactLength: null, + typeName: exports.ZodFirstPartyTypeKind.ZodArray, + ...processCreateParams(params), + }); + }; + function deepPartialify(schema) { + if (schema instanceof ZodObject) { + const newShape = {}; + for (const key in schema.shape) { + const fieldSchema = schema.shape[key]; + newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); + } + return new ZodObject({ + ...schema._def, + shape: () => newShape, + }); + } + 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) => deepPartialify(item))); + } + else { + return schema; + } + } + class ZodObject extends ZodType { + constructor() { + super(...arguments); + this._cached = null; + /** + * @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. + */ + this.nonstrict = this.passthrough; + // 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 + * */ + this.augment = this.extend; + } + _getCached() { + if (this._cached !== null) + return this._cached; + const shape = this._def.shape(); + const keys = exports.util.objectKeys(shape); + return (this._cached = { shape, keys }); + } + _parse(input) { + 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 = []; + 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 = []; + 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 = []; + for (const pair of pairs) { + const key = await pair.key; + syncPairs.push({ + key, + value: await pair.value, + alwaysSet: pair.alwaysSet, + }); + } + return syncPairs; + }) + .then((syncPairs) => { + return ParseStatus.mergeObjectSync(status, syncPairs); + }); + } + else { + return ParseStatus.mergeObjectSync(status, pairs); + } + } + get shape() { + return this._def.shape(); + } + strict(message) { + errorUtil.errToObj; + return new ZodObject({ + ...this._def, + unknownKeys: "strict", + ...(message !== undefined + ? { + errorMap: (issue, ctx) => { + var _a, _b, _c, _d; + const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError; + if (issue.code === "unrecognized_keys") + return { + message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError, + }; + return { + message: defaultError, + }; + }, + } + : {}), + }); + } + strip() { + return new ZodObject({ + ...this._def, + unknownKeys: "strip", + }); + } + passthrough() { + return new ZodObject({ + ...this._def, + unknownKeys: "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) { + return new ZodObject({ + ...this._def, + shape: () => ({ + ...this._def.shape(), + ...augmentation, + }), + }); + } + /** + * 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) { + const merged = new ZodObject({ + unknownKeys: merging._def.unknownKeys, + catchall: merging._def.catchall, + shape: () => ({ + ...this._def.shape(), + ...merging._def.shape(), + }), + typeName: exports.ZodFirstPartyTypeKind.ZodObject, + }); + 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, schema) { + return this.augment({ [key]: schema }); + } + // 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) { + return new ZodObject({ + ...this._def, + catchall: index, + }); + } + pick(mask) { + const shape = {}; + exports.util.objectKeys(mask).forEach((key) => { + if (mask[key] && this.shape[key]) { + shape[key] = this.shape[key]; + } + }); + return new ZodObject({ + ...this._def, + shape: () => shape, + }); + } + omit(mask) { + const shape = {}; + exports.util.objectKeys(this.shape).forEach((key) => { + if (!mask[key]) { + shape[key] = this.shape[key]; + } + }); + return new ZodObject({ + ...this._def, + shape: () => shape, + }); + } + /** + * @deprecated + */ + deepPartial() { + return deepPartialify(this); + } + partial(mask) { + const newShape = {}; + exports.util.objectKeys(this.shape).forEach((key) => { + const fieldSchema = this.shape[key]; + if (mask && !mask[key]) { + newShape[key] = fieldSchema; + } + else { + newShape[key] = fieldSchema.optional(); + } + }); + return new ZodObject({ + ...this._def, + shape: () => newShape, + }); + } + required(mask) { + const newShape = {}; + exports.util.objectKeys(this.shape).forEach((key) => { + if (mask && !mask[key]) { + newShape[key] = this.shape[key]; + } + else { + const fieldSchema = this.shape[key]; + let newField = fieldSchema; + while (newField instanceof ZodOptional) { + newField = newField._def.innerType; + } + newShape[key] = newField; + } + }); + return new ZodObject({ + ...this._def, + shape: () => newShape, + }); + } + keyof() { + return createZodEnum(exports.util.objectKeys(this.shape)); + } + } + ZodObject.create = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: exports.ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }); + }; + ZodObject.strictCreate = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strict", + catchall: ZodNever.create(), + typeName: exports.ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }); + }; + ZodObject.lazycreate = (shape, params) => { + return new ZodObject({ + shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: exports.ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }); + }; + class ZodUnion extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const options = this._def.options; + function handleResults(results) { + // 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 = { + ...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; + const issues = []; + for (const option of options) { + const childCtx = { + ...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; + } + } + ZodUnion.create = (types, params) => { + return new ZodUnion({ + options: types, + typeName: exports.ZodFirstPartyTypeKind.ZodUnion, + ...processCreateParams(params), + }); + }; + ///////////////////////////////////////////////////// + ///////////////////////////////////////////////////// + ////////// ////////// + ////////// ZodDiscriminatedUnion ////////// + ////////// ////////// + ///////////////////////////////////////////////////// + ///////////////////////////////////////////////////// + const getDiscriminator = (type) => { + 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 Object.keys(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 { + return null; + } + }; + class ZodDiscriminatedUnion extends ZodType { + _parse(input) { + 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 = 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, + }); + } + else { + return option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + } + } + 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, options, params) { + // Get all the valid discriminator values + const optionsMap = new Map(); + // try { + for (const type of options) { + const discriminatorValues = getDiscriminator(type.shape[discriminator]); + if (!discriminatorValues) { + 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({ + typeName: exports.ZodFirstPartyTypeKind.ZodDiscriminatedUnion, + discriminator, + options, + optionsMap, + ...processCreateParams(params), + }); + } + } + function mergeValues(a, b) { + 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 = exports.util.objectKeys(b); + const sharedKeys = exports.util + .objectKeys(a) + .filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...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 = []; + 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 }; + } + } + class ZodIntersection extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const handleParsed = (parsedLeft, parsedRight) => { + 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]) => 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, + })); + } + } + } + ZodIntersection.create = (left, right, params) => { + return new ZodIntersection({ + left: left, + right: right, + typeName: exports.ZodFirstPartyTypeKind.ZodIntersection, + ...processCreateParams(params), + }); + }; + class ZodTuple extends ZodType { + _parse(input) { + 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] + .map((item, itemIndex) => { + const schema = this._def.items[itemIndex] || this._def.rest; + if (!schema) + return null; + 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); + } + } + get items() { + return this._def.items; + } + rest(rest) { + return new ZodTuple({ + ...this._def, + rest, + }); + } + } + ZodTuple.create = (schemas, params) => { + if (!Array.isArray(schemas)) { + throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); + } + return new ZodTuple({ + items: schemas, + typeName: exports.ZodFirstPartyTypeKind.ZodTuple, + rest: null, + ...processCreateParams(params), + }); + }; + class ZodRecord extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + 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 = []; + 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)), + }); + } + if (ctx.common.async) { + return ParseStatus.mergeObjectAsync(status, pairs); + } + else { + return ParseStatus.mergeObjectSync(status, pairs); + } + } + get element() { + return this._def.valueType; + } + static create(first, second, third) { + if (second instanceof ZodType) { + return new ZodRecord({ + keyType: first, + valueType: second, + typeName: exports.ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(third), + }); + } + return new ZodRecord({ + keyType: ZodString.create(), + valueType: first, + typeName: exports.ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(second), + }); + } + } + class ZodMap extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + 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.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; + const value = 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 }; + } + } + } + ZodMap.create = (keyType, valueType, params) => { + return new ZodMap({ + valueType, + keyType, + typeName: exports.ZodFirstPartyTypeKind.ZodMap, + ...processCreateParams(params), + }); + }; + class ZodSet extends ZodType { + _parse(input) { + 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) { + 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.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); + } + } + min(minSize, message) { + return new ZodSet({ + ...this._def, + minSize: { value: minSize, message: errorUtil.toString(message) }, + }); + } + max(maxSize, message) { + return new ZodSet({ + ...this._def, + maxSize: { value: maxSize, message: errorUtil.toString(message) }, + }); + } + size(size, message) { + return this.min(size, message).max(size, message); + } + nonempty(message) { + return this.min(1, message); + } + } + ZodSet.create = (valueType, params) => { + return new ZodSet({ + valueType, + minSize: null, + maxSize: null, + typeName: exports.ZodFirstPartyTypeKind.ZodSet, + ...processCreateParams(params), + }); + }; + class ZodFunction extends ZodType { + constructor() { + super(...arguments); + this.validate = this.implement; + } + _parse(input) { + 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, error) { + return makeIssue({ + data: args, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + getErrorMap(), + errorMap, + ].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_arguments, + argumentsError: error, + }, + }); + } + function makeReturnsIssue(returns, error) { + return makeIssue({ + data: returns, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + getErrorMap(), + errorMap, + ].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 (...args) { + 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); + const parsedReturns = await me._def.returns._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 (...args) { + 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; + }); + } + } + parameters() { + return this._def.args; + } + returnType() { + return this._def.returns; + } + args(...items) { + return new ZodFunction({ + ...this._def, + args: ZodTuple.create(items).rest(ZodUnknown.create()), + }); + } + returns(returnType) { + return new ZodFunction({ + ...this._def, + returns: returnType, + }); + } + implement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + strictImplement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + static create(args, returns, params) { + return new ZodFunction({ + args: (args + ? args + : ZodTuple.create([]).rest(ZodUnknown.create())), + returns: returns || ZodUnknown.create(), + typeName: exports.ZodFirstPartyTypeKind.ZodFunction, + ...processCreateParams(params), + }); + } + } + class ZodLazy extends ZodType { + get schema() { + return this._def.getter(); + } + _parse(input) { + const { ctx } = this._processInputParams(input); + const lazySchema = this._def.getter(); + return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); + } + } + ZodLazy.create = (getter, params) => { + return new ZodLazy({ + getter: getter, + typeName: exports.ZodFirstPartyTypeKind.ZodLazy, + ...processCreateParams(params), + }); + }; + class ZodLiteral extends ZodType { + _parse(input) { + 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; + } + } + ZodLiteral.create = (value, params) => { + return new ZodLiteral({ + value: value, + typeName: exports.ZodFirstPartyTypeKind.ZodLiteral, + ...processCreateParams(params), + }); + }; + function createZodEnum(values, params) { + return new ZodEnum({ + values, + typeName: exports.ZodFirstPartyTypeKind.ZodEnum, + ...processCreateParams(params), + }); + } + class ZodEnum extends ZodType { + _parse(input) { + if (typeof input.data !== "string") { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + expected: exports.util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type, + }); + return INVALID; + } + if (this._def.values.indexOf(input.data) === -1) { + 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() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + get Values() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + get Enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + extract(values) { + return ZodEnum.create(values); + } + exclude(values) { + return ZodEnum.create(this.options.filter((opt) => !values.includes(opt))); + } + } + ZodEnum.create = createZodEnum; + class ZodNativeEnum extends ZodType { + _parse(input) { + const nativeEnumValues = exports.util.getValidEnumValues(this._def.values); + const ctx = this._getOrReturnCtx(input); + if (ctx.parsedType !== ZodParsedType.string && + ctx.parsedType !== ZodParsedType.number) { + const expectedValues = exports.util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + expected: exports.util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type, + }); + return INVALID; + } + if (nativeEnumValues.indexOf(input.data) === -1) { + const expectedValues = exports.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; + } + } + ZodNativeEnum.create = (values, params) => { + return new ZodNativeEnum({ + values: values, + typeName: exports.ZodFirstPartyTypeKind.ZodNativeEnum, + ...processCreateParams(params), + }); + }; + class ZodPromise extends ZodType { + unwrap() { + return this._def.type; + } + _parse(input) { + 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) => { + return this._def.type.parseAsync(data, { + path: ctx.path, + errorMap: ctx.common.contextualErrorMap, + }); + })); + } + } + ZodPromise.create = (schema, params) => { + return new ZodPromise({ + type: schema, + typeName: exports.ZodFirstPartyTypeKind.ZodPromise, + ...processCreateParams(params), + }); + }; + class ZodEffects extends ZodType { + innerType() { + return this._def.schema; + } + sourceType() { + return this._def.schema._def.typeName === exports.ZodFirstPartyTypeKind.ZodEffects + ? this._def.schema.sourceType() + : this._def.schema; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const effect = this._def.effect || null; + const checkCtx = { + addIssue: (arg) => { + 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.issues.length) { + return { + status: "dirty", + value: ctx.data, + }; + } + if (ctx.common.async) { + return Promise.resolve(processed).then((processed) => { + return this._def.schema._parseAsync({ + data: processed, + path: ctx.path, + parent: ctx, + }); + }); + } + else { + return this._def.schema._parseSync({ + data: processed, + path: ctx.path, + parent: ctx, + }); + } + } + if (effect.type === "refinement") { + const executeRefinement = (acc + // effect: RefinementEffect + ) => { + 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 base; + 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 base; + return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result })); + }); + } + } + exports.util.assertNever(effect); + } + } + ZodEffects.create = (schema, effect, params) => { + return new ZodEffects({ + schema, + typeName: exports.ZodFirstPartyTypeKind.ZodEffects, + effect, + ...processCreateParams(params), + }); + }; + ZodEffects.createWithPreprocess = (preprocess, schema, params) => { + return new ZodEffects({ + schema, + effect: { type: "preprocess", transform: preprocess }, + typeName: exports.ZodFirstPartyTypeKind.ZodEffects, + ...processCreateParams(params), + }); + }; + class ZodOptional extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType.undefined) { + return OK(undefined); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } + } + ZodOptional.create = (type, params) => { + return new ZodOptional({ + innerType: type, + typeName: exports.ZodFirstPartyTypeKind.ZodOptional, + ...processCreateParams(params), + }); + }; + class ZodNullable extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType.null) { + return OK(null); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } + } + ZodNullable.create = (type, params) => { + return new ZodNullable({ + innerType: type, + typeName: exports.ZodFirstPartyTypeKind.ZodNullable, + ...processCreateParams(params), + }); + }; + class ZodDefault extends ZodType { + _parse(input) { + 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; + } + } + ZodDefault.create = (type, params) => { + return new ZodDefault({ + innerType: type, + typeName: exports.ZodFirstPartyTypeKind.ZodDefault, + defaultValue: typeof params.default === "function" + ? params.default + : () => params.default, + ...processCreateParams(params), + }); + }; + class ZodCatch extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + // newCtx is used to not collect issues from inner types in ctx + const newCtx = { + ...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; + } + } + ZodCatch.create = (type, params) => { + return new ZodCatch({ + innerType: type, + typeName: exports.ZodFirstPartyTypeKind.ZodCatch, + catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, + ...processCreateParams(params), + }); + }; + class ZodNaN extends ZodType { + _parse(input) { + 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 }; + } + } + ZodNaN.create = (params) => { + return new ZodNaN({ + typeName: exports.ZodFirstPartyTypeKind.ZodNaN, + ...processCreateParams(params), + }); + }; + const BRAND = Symbol("zod_brand"); + class ZodBranded extends ZodType { + _parse(input) { + 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; + } + } + class ZodPipeline extends ZodType { + _parse(input) { + 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, b) { + return new ZodPipeline({ + in: a, + out: b, + typeName: exports.ZodFirstPartyTypeKind.ZodPipeline, + }); + } + } + class ZodReadonly extends ZodType { + _parse(input) { + const result = this._def.innerType._parse(input); + if (isValid(result)) { + result.value = Object.freeze(result.value); + } + return result; + } + } + ZodReadonly.create = (type, params) => { + return new ZodReadonly({ + innerType: type, + typeName: exports.ZodFirstPartyTypeKind.ZodReadonly, + ...processCreateParams(params), + }); + }; + const custom = (check, params = {}, + /* + * @deprecated + * + * Pass `fatal` into the params object instead: + * + * ```ts + * z.string().custom((val) => val.length > 5, { fatal: false }) + * ``` + * + */ + fatal) => { + if (check) + return ZodAny.create().superRefine((data, ctx) => { + var _a, _b; + if (!check(data)) { + const p = typeof params === "function" + ? params(data) + : typeof params === "string" + ? { message: params } + : params; + const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true; + const p2 = typeof p === "string" ? { message: p } : p; + ctx.addIssue({ code: "custom", ...p2, fatal: _fatal }); + } + }); + return ZodAny.create(); + }; + const late = { + object: ZodObject.lazycreate, + }; + exports.ZodFirstPartyTypeKind = void 0; + (function (ZodFirstPartyTypeKind) { + ZodFirstPartyTypeKind["ZodString"] = "ZodString"; + ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber"; + ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN"; + ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt"; + ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean"; + ZodFirstPartyTypeKind["ZodDate"] = "ZodDate"; + ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol"; + ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined"; + ZodFirstPartyTypeKind["ZodNull"] = "ZodNull"; + ZodFirstPartyTypeKind["ZodAny"] = "ZodAny"; + ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown"; + ZodFirstPartyTypeKind["ZodNever"] = "ZodNever"; + ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid"; + ZodFirstPartyTypeKind["ZodArray"] = "ZodArray"; + ZodFirstPartyTypeKind["ZodObject"] = "ZodObject"; + ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion"; + ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; + ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection"; + ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple"; + ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord"; + ZodFirstPartyTypeKind["ZodMap"] = "ZodMap"; + ZodFirstPartyTypeKind["ZodSet"] = "ZodSet"; + ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction"; + ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy"; + ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral"; + ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum"; + ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects"; + ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum"; + ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional"; + ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable"; + ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault"; + ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch"; + ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise"; + ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded"; + ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline"; + ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly"; + })(exports.ZodFirstPartyTypeKind || (exports.ZodFirstPartyTypeKind = {})); + const instanceOfType = ( + // const instanceOfType = any>( + cls, params = { + 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(); + const coerce = { + string: ((arg) => ZodString.create({ ...arg, coerce: true })), + number: ((arg) => ZodNumber.create({ ...arg, coerce: true })), + boolean: ((arg) => ZodBoolean.create({ + ...arg, + coerce: true, + })), + bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })), + date: ((arg) => ZodDate.create({ ...arg, coerce: true })), + }; + const NEVER = INVALID; + + var z = /*#__PURE__*/Object.freeze({ + __proto__: null, + defaultErrorMap: errorMap, + setErrorMap: setErrorMap, + getErrorMap: getErrorMap, + makeIssue: makeIssue, + EMPTY_PATH: EMPTY_PATH, + addIssueToContext: addIssueToContext, + ParseStatus: ParseStatus, + INVALID: INVALID, + DIRTY: DIRTY, + OK: OK, + isAborted: isAborted, + isDirty: isDirty, + isValid: isValid, + isAsync: isAsync, + get util () { return exports.util; }, + get objectUtil () { return exports.objectUtil; }, + ZodParsedType: ZodParsedType, + getParsedType: getParsedType, + ZodType: ZodType, + ZodString: ZodString, + ZodNumber: ZodNumber, + 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, + ZodNativeEnum: ZodNativeEnum, + ZodPromise: ZodPromise, + ZodEffects: ZodEffects, + ZodTransformer: ZodEffects, + ZodOptional: ZodOptional, + ZodNullable: ZodNullable, + ZodDefault: ZodDefault, + ZodCatch: ZodCatch, + ZodNaN: ZodNaN, + BRAND: BRAND, + ZodBranded: ZodBranded, + ZodPipeline: ZodPipeline, + ZodReadonly: ZodReadonly, + custom: custom, + Schema: ZodType, + ZodSchema: ZodType, + late: late, + get ZodFirstPartyTypeKind () { return exports.ZodFirstPartyTypeKind; }, + coerce: coerce, + any: anyType, + array: arrayType, + bigint: bigIntType, + boolean: booleanType, + date: dateType, + discriminatedUnion: discriminatedUnionType, + effect: effectsType, + 'enum': enumType, + 'function': functionType, + 'instanceof': instanceOfType, + intersection: intersectionType, + lazy: lazyType, + literal: literalType, + map: mapType, + nan: nanType, + nativeEnum: nativeEnumType, + never: neverType, + 'null': nullType, + nullable: nullableType, + number: numberType, + object: objectType, + oboolean: oboolean, + onumber: onumber, + optional: optionalType, + ostring: ostring, + pipeline: pipelineType, + preprocess: preprocessType, + promise: promiseType, + record: recordType, + set: setType, + strictObject: strictObjectType, + string: stringType, + symbol: symbolType, + transformer: effectsType, + tuple: tupleType, + 'undefined': undefinedType, + union: unionType, + unknown: unknownType, + 'void': voidType, + NEVER: NEVER, + ZodIssueCode: ZodIssueCode, + quotelessJson: quotelessJson, + ZodError: ZodError + }); + + exports.BRAND = BRAND; + exports.DIRTY = DIRTY; + exports.EMPTY_PATH = EMPTY_PATH; + exports.INVALID = INVALID; + exports.NEVER = NEVER; + exports.OK = OK; + exports.ParseStatus = ParseStatus; + exports.Schema = ZodType; + exports.ZodAny = ZodAny; + exports.ZodArray = ZodArray; + exports.ZodBigInt = ZodBigInt; + exports.ZodBoolean = ZodBoolean; + exports.ZodBranded = ZodBranded; + exports.ZodCatch = ZodCatch; + exports.ZodDate = ZodDate; + exports.ZodDefault = ZodDefault; + exports.ZodDiscriminatedUnion = ZodDiscriminatedUnion; + exports.ZodEffects = ZodEffects; + exports.ZodEnum = ZodEnum; + exports.ZodError = ZodError; + exports.ZodFunction = ZodFunction; + exports.ZodIntersection = ZodIntersection; + exports.ZodIssueCode = ZodIssueCode; + exports.ZodLazy = ZodLazy; + exports.ZodLiteral = ZodLiteral; + exports.ZodMap = ZodMap; + exports.ZodNaN = ZodNaN; + exports.ZodNativeEnum = ZodNativeEnum; + exports.ZodNever = ZodNever; + exports.ZodNull = ZodNull; + exports.ZodNullable = ZodNullable; + exports.ZodNumber = ZodNumber; + exports.ZodObject = ZodObject; + exports.ZodOptional = ZodOptional; + exports.ZodParsedType = ZodParsedType; + exports.ZodPipeline = ZodPipeline; + exports.ZodPromise = ZodPromise; + exports.ZodReadonly = ZodReadonly; + exports.ZodRecord = ZodRecord; + exports.ZodSchema = ZodType; + exports.ZodSet = ZodSet; + exports.ZodString = ZodString; + exports.ZodSymbol = ZodSymbol; + exports.ZodTransformer = ZodEffects; + exports.ZodTuple = ZodTuple; + exports.ZodType = ZodType; + exports.ZodUndefined = ZodUndefined; + exports.ZodUnion = ZodUnion; + exports.ZodUnknown = ZodUnknown; + exports.ZodVoid = ZodVoid; + exports.addIssueToContext = addIssueToContext; + exports.any = anyType; + exports.array = arrayType; + exports.bigint = bigIntType; + exports.boolean = booleanType; + exports.coerce = coerce; + exports.custom = custom; + exports.date = dateType; + exports["default"] = z; + exports.defaultErrorMap = errorMap; + exports.discriminatedUnion = discriminatedUnionType; + exports.effect = effectsType; + exports["enum"] = enumType; + exports["function"] = functionType; + exports.getErrorMap = getErrorMap; + exports.getParsedType = getParsedType; + exports["instanceof"] = instanceOfType; + exports.intersection = intersectionType; + exports.isAborted = isAborted; + exports.isAsync = isAsync; + exports.isDirty = isDirty; + exports.isValid = isValid; + exports.late = late; + exports.lazy = lazyType; + exports.literal = literalType; + exports.makeIssue = makeIssue; + exports.map = mapType; + exports.nan = nanType; + exports.nativeEnum = nativeEnumType; + exports.never = neverType; + exports["null"] = nullType; + exports.nullable = nullableType; + exports.number = numberType; + exports.object = objectType; + exports.oboolean = oboolean; + exports.onumber = onumber; + exports.optional = optionalType; + exports.ostring = ostring; + exports.pipeline = pipelineType; + exports.preprocess = preprocessType; + exports.promise = promiseType; + exports.quotelessJson = quotelessJson; + exports.record = recordType; + exports.set = setType; + exports.setErrorMap = setErrorMap; + exports.strictObject = strictObjectType; + exports.string = stringType; + exports.symbol = symbolType; + exports.transformer = effectsType; + exports.tuple = tupleType; + exports["undefined"] = undefinedType; + exports.union = unionType; + exports.unknown = unknownType; + exports["void"] = voidType; + exports.z = z; + + Object.defineProperty(exports, '__esModule', { value: true }); + +}));