@volter/tabnode 0.5.26 → 0.5.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -18,6 +18,8 @@ var __privateWrapper = (obj, member, setter, getter) => ({
18
18
  }
19
19
  });
20
20
  var _a, _b, _asyncId, _triggerAsyncId, _c, _d, _e, _f, _g, _h, _i, _j, _ptr, _type, _maxHeaderSize, _headerBytes, _headers, _field, _value, _readingValue, _url, _statusMessage, _headersSent, _paused, _buffer, _bufferPtr, _bufferSize, _connections, _HTTPParser_instances, reset_fn, copyIn_fn, pushHeader_fn, countHeaderBytes_fn, _parsers, _strm, _writeState, _callback, _level, _strategy, _windowBits, _memLevel, _dictionary, _ended, _Zlib_instances, inflating_get, windowFor_fn, start_fn, fail_fn, report_fn, run_fn, end_fn, _writeState2, _callback2, _input, _output, _outputAt, _BrotliDecoderHandle_instances, run_fn2, _k, _resolveChain, _loadChain, _initializing, _initializeFailure, _RunModuleHooks_instances, run_fn3;
21
+ import { u as uint8ToBase64, b as base64ToUint8, a as uint8ToBinaryString, c as uint8ToHex, P as PortBridge } from "./port-bridge-CixAESwA.js";
22
+ import { g } from "./port-bridge-CixAESwA.js";
21
23
  import { defineCommand, Bash, getCommandNames } from "just-bash";
22
24
  import { imports, resolve as resolve$3 } from "resolve.exports";
23
25
  import { wrap, proxy } from "comlink";
@@ -94,36 +96,6 @@ forGuestRealm(() => {
94
96
  const realm = globalThis;
95
97
  if (!realm.__browserRuntimeHeldWork) takeFromHost(globalThis, "__browserRuntimeHeldWork", ownHeldWork);
96
98
  });
97
- const CHUNK = 8192;
98
- function uint8ToBase64(bytes2) {
99
- const parts = [];
100
- for (let i2 = 0; i2 < bytes2.length; i2 += CHUNK) {
101
- parts.push(String.fromCharCode.apply(null, Array.from(bytes2.subarray(i2, i2 + CHUNK))));
102
- }
103
- return btoa(parts.join(""));
104
- }
105
- function base64ToUint8(base642) {
106
- const binary = atob(base642);
107
- const bytes2 = new Uint8Array(binary.length);
108
- for (let i2 = 0; i2 < binary.length; i2++) {
109
- bytes2[i2] = binary.charCodeAt(i2);
110
- }
111
- return bytes2;
112
- }
113
- function uint8ToHex(bytes2) {
114
- const hex = new Array(bytes2.length);
115
- for (let i2 = 0; i2 < bytes2.length; i2++) {
116
- hex[i2] = bytes2[i2].toString(16).padStart(2, "0");
117
- }
118
- return hex.join("");
119
- }
120
- function uint8ToBinaryString(bytes2) {
121
- const parts = [];
122
- for (let i2 = 0; i2 < bytes2.length; i2 += CHUNK) {
123
- parts.push(String.fromCharCode.apply(null, Array.from(bytes2.subarray(i2, i2 + CHUNK))));
124
- }
125
- return parts.join("");
126
- }
127
99
  const PRIMORDIALS_SOURCE = "'use strict';\n\n/* eslint-disable node-core/prefer-primordials */\n\n// This file subclasses and stores the JS builtins that come from the VM\n// so that Node.js's builtin modules do not need to later look these up from\n// the global proxy, which can be mutated by users.\n\n// Use of primordials have sometimes a dramatic impact on performance, please\n// benchmark all changes made in performance-sensitive areas of the codebase.\n// See: https://github.com/nodejs/node/pull/38248\n\nconst {\n defineProperty: ReflectDefineProperty,\n getOwnPropertyDescriptor: ReflectGetOwnPropertyDescriptor,\n ownKeys: ReflectOwnKeys,\n} = Reflect;\n\n// `uncurryThis` is equivalent to `func => Function.prototype.call.bind(func)`.\n// It is using `bind.bind(call)` to avoid using `Function.prototype.bind`\n// and `Function.prototype.call` after it may have been mutated by users.\nconst { apply, bind, call } = Function.prototype;\nconst uncurryThis = bind.bind(call);\nprimordials.uncurryThis = uncurryThis;\n\n// `applyBind` is equivalent to `func => Function.prototype.apply.bind(func)`.\n// It is using `bind.bind(apply)` to avoid using `Function.prototype.bind`\n// and `Function.prototype.apply` after it may have been mutated by users.\nconst applyBind = bind.bind(apply);\nprimordials.applyBind = applyBind;\n\n// Methods that accept a variable number of arguments, and thus it's useful to\n// also create `${prefix}${key}Apply`, which uses `Function.prototype.apply`,\n// instead of `Function.prototype.call`, and thus doesn't require iterator\n// destructuring.\nconst varargsMethods = [\n // 'ArrayPrototypeConcat' is omitted, because it performs the spread\n // on its own for arrays and array-likes with a truthy\n // @@isConcatSpreadable symbol property.\n 'ArrayOf',\n 'ArrayPrototypePush',\n 'ArrayPrototypeUnshift',\n // 'FunctionPrototypeCall' is omitted, since there's 'ReflectApply'\n // and 'FunctionPrototypeApply'.\n 'MathHypot',\n 'MathMax',\n 'MathMin',\n 'StringFromCharCode',\n 'StringFromCodePoint',\n 'StringPrototypeConcat',\n 'TypedArrayOf',\n];\n\nfunction getNewKey(key) {\n return typeof key === 'symbol' ?\n `Symbol${key.description[7].toUpperCase()}${key.description.slice(8)}` :\n `${key[0].toUpperCase()}${key.slice(1)}`;\n}\n\nfunction copyAccessor(dest, prefix, key, { enumerable, get, set }) {\n ReflectDefineProperty(dest, `${prefix}Get${key}`, {\n __proto__: null,\n value: uncurryThis(get),\n enumerable,\n });\n if (set !== undefined) {\n ReflectDefineProperty(dest, `${prefix}Set${key}`, {\n __proto__: null,\n value: uncurryThis(set),\n enumerable,\n });\n }\n}\n\nfunction copyPropsRenamed(src, dest, prefix) {\n for (const key of ReflectOwnKeys(src)) {\n const newKey = getNewKey(key);\n const desc = ReflectGetOwnPropertyDescriptor(src, key);\n if ('get' in desc) {\n copyAccessor(dest, prefix, newKey, desc);\n } else {\n const name = `${prefix}${newKey}`;\n ReflectDefineProperty(dest, name, { __proto__: null, ...desc });\n if (varargsMethods.includes(name)) {\n ReflectDefineProperty(dest, `${name}Apply`, {\n __proto__: null,\n // `src` is bound as the `this` so that the static `this` points\n // to the object it was defined on,\n // e.g.: `ArrayOfApply` gets a `this` of `Array`:\n value: applyBind(desc.value, src),\n });\n }\n }\n }\n}\n\nfunction copyPropsRenamedBound(src, dest, prefix) {\n for (const key of ReflectOwnKeys(src)) {\n const newKey = getNewKey(key);\n const desc = ReflectGetOwnPropertyDescriptor(src, key);\n if ('get' in desc) {\n copyAccessor(dest, prefix, newKey, desc);\n } else {\n const { value } = desc;\n if (typeof value === 'function') {\n desc.value = value.bind(src);\n }\n\n const name = `${prefix}${newKey}`;\n ReflectDefineProperty(dest, name, { __proto__: null, ...desc });\n if (varargsMethods.includes(name)) {\n ReflectDefineProperty(dest, `${name}Apply`, {\n __proto__: null,\n value: applyBind(value, src),\n });\n }\n }\n }\n}\n\nfunction copyPrototype(src, dest, prefix) {\n for (const key of ReflectOwnKeys(src)) {\n const newKey = getNewKey(key);\n const desc = ReflectGetOwnPropertyDescriptor(src, key);\n if ('get' in desc) {\n copyAccessor(dest, prefix, newKey, desc);\n } else {\n const { value } = desc;\n if (typeof value === 'function') {\n desc.value = uncurryThis(value);\n }\n\n const name = `${prefix}${newKey}`;\n ReflectDefineProperty(dest, name, { __proto__: null, ...desc });\n if (varargsMethods.includes(name)) {\n ReflectDefineProperty(dest, `${name}Apply`, {\n __proto__: null,\n value: applyBind(value),\n });\n }\n }\n }\n}\n\n// Create copies of configurable value properties of the global object\n[\n 'Proxy',\n 'globalThis',\n].forEach((name) => {\n // eslint-disable-next-line no-restricted-globals\n primordials[name] = globalThis[name];\n});\n\n// Create copies of URI handling functions\n[\n decodeURI,\n decodeURIComponent,\n encodeURI,\n encodeURIComponent,\n].forEach((fn) => {\n primordials[fn.name] = fn;\n});\n\n// Create copies of legacy functions\n[\n escape,\n eval,\n unescape,\n].forEach((fn) => {\n primordials[fn.name] = fn;\n});\n\n// Create copies of the namespace objects\n[\n 'Atomics',\n 'JSON',\n 'Math',\n 'Proxy',\n 'Reflect',\n].forEach((name) => {\n // eslint-disable-next-line no-restricted-globals\n copyPropsRenamed(globalThis[name], primordials, name);\n});\n\n// Create copies of intrinsic objects\n[\n 'AggregateError',\n 'Array',\n 'ArrayBuffer',\n 'BigInt',\n 'BigInt64Array',\n 'BigUint64Array',\n 'Boolean',\n 'DataView',\n 'Date',\n 'Error',\n 'EvalError',\n 'FinalizationRegistry',\n 'Float32Array',\n 'Float64Array',\n 'Function',\n 'Int16Array',\n 'Int32Array',\n 'Int8Array',\n 'Map',\n 'Number',\n 'Object',\n 'RangeError',\n 'ReferenceError',\n 'RegExp',\n 'Set',\n 'String',\n 'Symbol',\n 'SyntaxError',\n 'TypeError',\n 'URIError',\n 'Uint16Array',\n 'Uint32Array',\n 'Uint8Array',\n 'Uint8ClampedArray',\n 'WeakMap',\n 'WeakRef',\n 'WeakSet',\n].forEach((name) => {\n // eslint-disable-next-line no-restricted-globals\n const original = globalThis[name];\n primordials[name] = original;\n copyPropsRenamed(original, primordials, name);\n copyPrototype(original.prototype, primordials, `${name}Prototype`);\n});\n\n\n// Create copies of intrinsic objects that require a valid `this` to call\n// static methods.\n// Refs: https://www.ecma-international.org/ecma-262/#sec-promise.all\n[\n 'Promise',\n].forEach((name) => {\n // eslint-disable-next-line no-restricted-globals\n const original = globalThis[name];\n primordials[name] = original;\n copyPropsRenamedBound(original, primordials, name);\n copyPrototype(original.prototype, primordials, `${name}Prototype`);\n});\n\n// Create copies of abstract intrinsic objects that are not directly exposed\n// on the global object.\n// Refs: https://tc39.es/ecma262/#sec-%typedarray%-intrinsic-object\n[\n { name: 'TypedArray', original: Reflect.getPrototypeOf(Uint8Array) },\n { name: 'ArrayIterator', original: {\n prototype: Reflect.getPrototypeOf(Array.prototype[Symbol.iterator]()),\n } },\n { name: 'StringIterator', original: {\n prototype: Reflect.getPrototypeOf(String.prototype[Symbol.iterator]()),\n } },\n].forEach(({ name, original }) => {\n primordials[name] = original;\n // The static %TypedArray% methods require a valid `this`, but can't be bound,\n // as they need a subclass constructor as the receiver:\n copyPrototype(original, primordials, name);\n copyPrototype(original.prototype, primordials, `${name}Prototype`);\n});\n\nprimordials.IteratorPrototype = Reflect.getPrototypeOf(primordials.ArrayIteratorPrototype);\n\n/* eslint-enable node-core/prefer-primordials */\n\nconst {\n Array: ArrayConstructor,\n ArrayPrototypeForEach,\n ArrayPrototypeMap,\n FinalizationRegistry,\n FunctionPrototypeCall,\n Map,\n ObjectDefineProperties,\n ObjectDefineProperty,\n ObjectFreeze,\n ObjectSetPrototypeOf,\n Promise,\n PromisePrototypeThen,\n PromiseResolve,\n ReflectApply,\n ReflectConstruct,\n ReflectGet,\n ReflectSet,\n RegExp,\n RegExpPrototype,\n RegExpPrototypeExec,\n RegExpPrototypeGetDotAll,\n RegExpPrototypeGetFlags,\n RegExpPrototypeGetGlobal,\n RegExpPrototypeGetHasIndices,\n RegExpPrototypeGetIgnoreCase,\n RegExpPrototypeGetMultiline,\n RegExpPrototypeGetSource,\n RegExpPrototypeGetSticky,\n RegExpPrototypeGetUnicode,\n Set,\n SymbolIterator,\n SymbolMatch,\n SymbolMatchAll,\n SymbolReplace,\n SymbolSearch,\n SymbolSpecies,\n SymbolSplit,\n WeakMap,\n WeakRef,\n WeakSet,\n} = primordials;\n\n\n/**\n * Creates a class that can be safely iterated over.\n *\n * Because these functions are used by `makeSafe`, which is exposed on the\n * `primordials` object, it's important to use const references to the\n * primordials that they use.\n * @template {Iterable} T\n * @template {*} TReturn\n * @template {*} TNext\n * @param {(self: T) => IterableIterator<T>} factory\n * @param {(...args: [] | [TNext]) => IteratorResult<T, TReturn>} next\n * @returns {Iterator<T, TReturn, TNext>}\n */\nconst createSafeIterator = (factory, next) => {\n class SafeIterator {\n constructor(iterable) {\n this._iterator = factory(iterable);\n }\n next() {\n return next(this._iterator);\n }\n [SymbolIterator]() {\n return this;\n }\n }\n ObjectSetPrototypeOf(SafeIterator.prototype, null);\n ObjectFreeze(SafeIterator.prototype);\n ObjectFreeze(SafeIterator);\n return SafeIterator;\n};\n\nprimordials.SafeArrayIterator = createSafeIterator(\n primordials.ArrayPrototypeSymbolIterator,\n primordials.ArrayIteratorPrototypeNext,\n);\nprimordials.SafeStringIterator = createSafeIterator(\n primordials.StringPrototypeSymbolIterator,\n primordials.StringIteratorPrototypeNext,\n);\n\nconst copyProps = (src, dest) => {\n ArrayPrototypeForEach(ReflectOwnKeys(src), (key) => {\n if (!ReflectGetOwnPropertyDescriptor(dest, key)) {\n ReflectDefineProperty(\n dest,\n key,\n { __proto__: null, ...ReflectGetOwnPropertyDescriptor(src, key) });\n }\n });\n};\n\n/**\n * @type {typeof primordials.makeSafe}\n */\nconst makeSafe = (unsafe, safe) => {\n if (SymbolIterator in unsafe.prototype) {\n const dummy = new unsafe();\n let next; // We can reuse the same `next` method.\n\n ArrayPrototypeForEach(ReflectOwnKeys(unsafe.prototype), (key) => {\n if (!ReflectGetOwnPropertyDescriptor(safe.prototype, key)) {\n const desc = ReflectGetOwnPropertyDescriptor(unsafe.prototype, key);\n if (\n typeof desc.value === 'function' &&\n desc.value.length === 0 &&\n SymbolIterator in (FunctionPrototypeCall(desc.value, dummy) ?? {})\n ) {\n const createIterator = uncurryThis(desc.value);\n next ??= uncurryThis(createIterator(dummy).next);\n const SafeIterator = createSafeIterator(createIterator, next);\n desc.value = function() {\n return new SafeIterator(this);\n };\n }\n ReflectDefineProperty(safe.prototype, key, { __proto__: null, ...desc });\n }\n });\n } else {\n copyProps(unsafe.prototype, safe.prototype);\n }\n copyProps(unsafe, safe);\n\n ObjectSetPrototypeOf(safe.prototype, null);\n ObjectFreeze(safe.prototype);\n ObjectFreeze(safe);\n return safe;\n};\nprimordials.makeSafe = makeSafe;\n\n// Subclass the constructors because we need to use their prototype\n// methods later.\n// Defining the `constructor` is necessary here to avoid the default\n// constructor which uses the user-mutable `%ArrayIteratorPrototype%.next`.\nprimordials.SafeMap = makeSafe(\n Map,\n class SafeMap extends Map {\n constructor(i) { super(i); } // eslint-disable-line no-useless-constructor\n },\n);\nprimordials.SafeWeakMap = makeSafe(\n WeakMap,\n class SafeWeakMap extends WeakMap {\n constructor(i) { super(i); } // eslint-disable-line no-useless-constructor\n },\n);\n\nprimordials.SafeSet = makeSafe(\n Set,\n class SafeSet extends Set {\n constructor(i) { super(i); } // eslint-disable-line no-useless-constructor\n },\n);\nprimordials.SafeWeakSet = makeSafe(\n WeakSet,\n class SafeWeakSet extends WeakSet {\n constructor(i) { super(i); } // eslint-disable-line no-useless-constructor\n },\n);\n\nprimordials.SafeFinalizationRegistry = makeSafe(\n FinalizationRegistry,\n class SafeFinalizationRegistry extends FinalizationRegistry {\n // eslint-disable-next-line no-useless-constructor\n constructor(cleanupCallback) { super(cleanupCallback); }\n },\n);\nprimordials.SafeWeakRef = makeSafe(\n WeakRef,\n class SafeWeakRef extends WeakRef {\n // eslint-disable-next-line no-useless-constructor\n constructor(target) { super(target); }\n },\n);\n\nconst SafePromise = makeSafe(\n Promise,\n class SafePromise extends Promise {\n // eslint-disable-next-line no-useless-constructor\n constructor(executor) { super(executor); }\n },\n);\n\n/**\n * Attaches a callback that is invoked when the Promise is settled (fulfilled or\n * rejected). The resolved value cannot be modified from the callback.\n * Prefer using async functions when possible.\n * @param {Promise<any>} thisPromise\n * @param {(() => void) | undefined | null} onFinally The callback to execute\n * when the Promise is settled (fulfilled or rejected).\n * @returns {Promise} A Promise for the completion of the callback.\n */\nprimordials.SafePromisePrototypeFinally = (thisPromise, onFinally) =>\n // Wrapping on a new Promise is necessary to not expose the SafePromise\n // prototype to user-land.\n new Promise((a, b) =>\n new SafePromise((a, b) => PromisePrototypeThen(thisPromise, a, b))\n .finally(onFinally)\n .then(a, b),\n );\n\nprimordials.AsyncIteratorPrototype =\n primordials.ReflectGetPrototypeOf(\n primordials.ReflectGetPrototypeOf(\n async function* () {}).prototype);\n\nconst arrayToSafePromiseIterable = (promises, mapFn) =>\n new primordials.SafeArrayIterator(\n ArrayPrototypeMap(\n promises,\n (promise, i) =>\n new SafePromise((a, b) => PromisePrototypeThen(mapFn == null ? promise : mapFn(promise, i), a, b)),\n ),\n );\n\n/**\n * @template T,U\n * @param {Array<T | PromiseLike<T>>} promises\n * @param {(v: T|PromiseLike<T>, k: number) => U|PromiseLike<U>} [mapFn]\n * @returns {Promise<Awaited<U>[]>}\n */\nprimordials.SafePromiseAll = (promises, mapFn) =>\n // Wrapping on a new Promise is necessary to not expose the SafePromise\n // prototype to user-land.\n new Promise((a, b) =>\n SafePromise.all(arrayToSafePromiseIterable(promises, mapFn)).then(a, b),\n );\n\n/**\n * Should only be used for internal functions, this would produce similar\n * results as `Promise.all` but without prototype pollution, and the return\n * value is not a genuine Array but an array-like object.\n * @template T,U\n * @param {ArrayLike<T | PromiseLike<T>>} promises\n * @param {(v: T|PromiseLike<T>, k: number) => U|PromiseLike<U>} [mapFn]\n * @returns {Promise<ArrayLike<Awaited<U>>>}\n */\nprimordials.SafePromiseAllReturnArrayLike = (promises, mapFn) =>\n new Promise((resolve, reject) => {\n const { length } = promises;\n\n const returnVal = ArrayConstructor(length);\n ObjectSetPrototypeOf(returnVal, null);\n if (length === 0) resolve(returnVal);\n\n let pendingPromises = length;\n for (let i = 0; i < length; i++) {\n const promise = mapFn != null ? mapFn(promises[i], i) : promises[i];\n PromisePrototypeThen(PromiseResolve(promise), (result) => {\n returnVal[i] = result;\n if (--pendingPromises === 0) resolve(returnVal);\n }, reject);\n }\n });\n\n/**\n * Should only be used when we only care about waiting for all the promises to\n * resolve, not what value they resolve to.\n * @template T,U\n * @param {ArrayLike<T | PromiseLike<T>>} promises\n * @param {(v: T|PromiseLike<T>, k: number) => U|PromiseLike<U>} [mapFn]\n * @returns {Promise<void>}\n */\nprimordials.SafePromiseAllReturnVoid = (promises, mapFn) =>\n new Promise((resolve, reject) => {\n let pendingPromises = promises.length;\n if (pendingPromises === 0) resolve();\n const onFulfilled = () => {\n if (--pendingPromises === 0) {\n resolve();\n }\n };\n for (let i = 0; i < promises.length; i++) {\n const promise = mapFn != null ? mapFn(promises[i], i) : promises[i];\n PromisePrototypeThen(PromiseResolve(promise), onFulfilled, reject);\n }\n });\n\n/**\n * @template T,U\n * @param {Array<T|PromiseLike<T>>} promises\n * @param {(v: T|PromiseLike<T>, k: number) => U|PromiseLike<U>} [mapFn]\n * @returns {Promise<PromiseSettledResult<any>[]>}\n */\nprimordials.SafePromiseAllSettled = (promises, mapFn) =>\n // Wrapping on a new Promise is necessary to not expose the SafePromise\n // prototype to user-land.\n new Promise((a, b) =>\n SafePromise.allSettled(arrayToSafePromiseIterable(promises, mapFn)).then(a, b),\n );\n\n/**\n * Should only be used when we only care about waiting for all the promises to\n * settle, not what value they resolve or reject to.\n * @template T,U\n * @param {ArrayLike<T|PromiseLike<T>>} promises\n * @param {(v: T|PromiseLike<T>, k: number) => U|PromiseLike<U>} [mapFn]\n * @returns {Promise<void>}\n */\nprimordials.SafePromiseAllSettledReturnVoid = (promises, mapFn) => new Promise((resolve) => {\n let pendingPromises = promises.length;\n if (pendingPromises === 0) resolve();\n const onSettle = () => {\n if (--pendingPromises === 0) resolve();\n };\n for (let i = 0; i < promises.length; i++) {\n const promise = mapFn != null ? mapFn(promises[i], i) : promises[i];\n PromisePrototypeThen(PromiseResolve(promise), onSettle, onSettle);\n }\n});\n\n/**\n * @template T,U\n * @param {Array<T|PromiseLike<T>>} promises\n * @param {(v: T|PromiseLike<T>, k: number) => U|PromiseLike<U>} [mapFn]\n * @returns {Promise<Awaited<U>>}\n */\nprimordials.SafePromiseAny = (promises, mapFn) =>\n // Wrapping on a new Promise is necessary to not expose the SafePromise\n // prototype to user-land.\n new Promise((a, b) =>\n SafePromise.any(arrayToSafePromiseIterable(promises, mapFn)).then(a, b),\n );\n\n/**\n * @template T,U\n * @param {Array<T|PromiseLike<T>>} promises\n * @param {(v: T|PromiseLike<T>, k: number) => U|PromiseLike<U>} [mapFn]\n * @returns {Promise<Awaited<U>>}\n */\nprimordials.SafePromiseRace = (promises, mapFn) =>\n // Wrapping on a new Promise is necessary to not expose the SafePromise\n // prototype to user-land.\n new Promise((a, b) =>\n SafePromise.race(arrayToSafePromiseIterable(promises, mapFn)).then(a, b),\n );\n\n\nconst {\n exec: OriginalRegExpPrototypeExec,\n [SymbolMatch]: OriginalRegExpPrototypeSymbolMatch,\n [SymbolMatchAll]: OriginalRegExpPrototypeSymbolMatchAll,\n [SymbolReplace]: OriginalRegExpPrototypeSymbolReplace,\n [SymbolSearch]: OriginalRegExpPrototypeSymbolSearch,\n [SymbolSplit]: OriginalRegExpPrototypeSymbolSplit,\n} = RegExpPrototype;\n\nclass RegExpLikeForStringSplitting {\n #regex;\n constructor() {\n this.#regex = ReflectConstruct(RegExp, arguments);\n }\n\n get lastIndex() {\n return ReflectGet(this.#regex, 'lastIndex');\n }\n set lastIndex(value) {\n ReflectSet(this.#regex, 'lastIndex', value);\n }\n\n exec() {\n return ReflectApply(OriginalRegExpPrototypeExec, this.#regex, arguments);\n }\n}\nObjectSetPrototypeOf(RegExpLikeForStringSplitting.prototype, null);\n\n/**\n * @param {RegExp} pattern\n * @returns {RegExp}\n */\nprimordials.hardenRegExp = function hardenRegExp(pattern) {\n ObjectDefineProperties(pattern, {\n [SymbolMatch]: {\n __proto__: null,\n configurable: true,\n value: OriginalRegExpPrototypeSymbolMatch,\n },\n [SymbolMatchAll]: {\n __proto__: null,\n configurable: true,\n value: OriginalRegExpPrototypeSymbolMatchAll,\n },\n [SymbolReplace]: {\n __proto__: null,\n configurable: true,\n value: OriginalRegExpPrototypeSymbolReplace,\n },\n [SymbolSearch]: {\n __proto__: null,\n configurable: true,\n value: OriginalRegExpPrototypeSymbolSearch,\n },\n [SymbolSplit]: {\n __proto__: null,\n configurable: true,\n value: OriginalRegExpPrototypeSymbolSplit,\n },\n constructor: {\n __proto__: null,\n configurable: true,\n value: {\n [SymbolSpecies]: RegExpLikeForStringSplitting,\n },\n },\n dotAll: {\n __proto__: null,\n configurable: true,\n value: RegExpPrototypeGetDotAll(pattern),\n },\n exec: {\n __proto__: null,\n configurable: true,\n value: OriginalRegExpPrototypeExec,\n },\n global: {\n __proto__: null,\n configurable: true,\n value: RegExpPrototypeGetGlobal(pattern),\n },\n hasIndices: {\n __proto__: null,\n configurable: true,\n value: RegExpPrototypeGetHasIndices(pattern),\n },\n ignoreCase: {\n __proto__: null,\n configurable: true,\n value: RegExpPrototypeGetIgnoreCase(pattern),\n },\n multiline: {\n __proto__: null,\n configurable: true,\n value: RegExpPrototypeGetMultiline(pattern),\n },\n source: {\n __proto__: null,\n configurable: true,\n value: RegExpPrototypeGetSource(pattern),\n },\n sticky: {\n __proto__: null,\n configurable: true,\n value: RegExpPrototypeGetSticky(pattern),\n },\n unicode: {\n __proto__: null,\n configurable: true,\n value: RegExpPrototypeGetUnicode(pattern),\n },\n });\n ObjectDefineProperty(pattern, 'flags', {\n __proto__: null,\n configurable: true,\n value: RegExpPrototypeGetFlags(pattern),\n });\n return pattern;\n};\n\n\n/**\n * @param {string} str\n * @param {RegExp} regexp\n * @returns {number}\n */\nprimordials.SafeStringPrototypeSearch = (str, regexp) => {\n regexp.lastIndex = 0;\n const match = RegExpPrototypeExec(regexp, str);\n return match ? match.index : -1;\n};\n\nObjectSetPrototypeOf(primordials, null);\nObjectFreeze(primordials);\n";
128
100
  const NAVIGATOR = "'use strict';\n\nconst {\n ObjectDefineProperties,\n ObjectFreeze,\n StringPrototypeIndexOf,\n StringPrototypeSlice,\n StringPrototypeToUpperCase,\n Symbol,\n} = primordials;\n\nconst {\n ERR_ILLEGAL_CONSTRUCTOR,\n} = require('internal/errors').codes;\n\nconst {\n kEnumerableProperty,\n} = require('internal/util');\n\nconst {\n getAvailableParallelism,\n} = internalBinding('os');\n\nconst kInitialize = Symbol('kInitialize');\n\nconst {\n platform,\n arch,\n version: nodeVersion,\n} = require('internal/process/per_thread');\n\nconst {\n getDefaultLocale,\n} = internalBinding('config');\n\n/**\n * @param {string} arch\n * @param {string} platform\n * @returns {string}\n */\nfunction getNavigatorPlatform(arch, platform) {\n if (platform === 'darwin') {\n // On macOS, modern browsers return 'MacIntel' even if running on Apple Silicon.\n return 'MacIntel';\n } else if (platform === 'win32') {\n // On Windows, modern browsers return 'Win32' even if running on a 64-bit version of Windows.\n // https://developer.mozilla.org/en-US/docs/Web/API/Navigator/platform#usage_notes\n return 'Win32';\n } else if (platform === 'linux') {\n if (arch === 'ia32') {\n return 'Linux i686';\n } else if (arch === 'x64') {\n return 'Linux x86_64';\n }\n return `Linux ${arch}`;\n } else if (platform === 'freebsd') {\n if (arch === 'ia32') {\n return 'FreeBSD i386';\n } else if (arch === 'x64') {\n return 'FreeBSD amd64';\n }\n return `FreeBSD ${arch}`;\n } else if (platform === 'openbsd') {\n if (arch === 'ia32') {\n return 'OpenBSD i386';\n } else if (arch === 'x64') {\n return 'OpenBSD amd64';\n }\n return `OpenBSD ${arch}`;\n } else if (platform === 'sunos') {\n if (arch === 'ia32') {\n return 'SunOS i86pc';\n }\n return `SunOS ${arch}`;\n } else if (platform === 'aix') {\n return 'AIX';\n }\n return `${StringPrototypeToUpperCase(platform[0])}${StringPrototypeSlice(platform, 1)} ${arch}`;\n}\n\nclass Navigator {\n // Private properties are used to avoid brand validations.\n #availableParallelism;\n #userAgent;\n #platform;\n #languages;\n\n constructor() {\n if (arguments[0] === kInitialize) {\n return;\n }\n throw new ERR_ILLEGAL_CONSTRUCTOR();\n }\n\n /**\n * @return {number}\n */\n get hardwareConcurrency() {\n this.#availableParallelism ??= getAvailableParallelism();\n return this.#availableParallelism;\n }\n\n /**\n * @return {string}\n */\n get language() {\n // The default locale might be changed dynamically, so always invoke the\n // binding.\n return getDefaultLocale() || 'en-US';\n }\n\n /**\n * @return {Array<string>}\n */\n get languages() {\n this.#languages ??= ObjectFreeze([this.language]);\n return this.#languages;\n }\n\n /**\n * @return {string}\n */\n get userAgent() {\n this.#userAgent ??= `Node.js/${StringPrototypeSlice(nodeVersion, 1, StringPrototypeIndexOf(nodeVersion, '.'))}`;\n return this.#userAgent;\n }\n\n /**\n * @return {string}\n */\n get platform() {\n this.#platform ??= getNavigatorPlatform(arch, platform);\n return this.#platform;\n }\n}\n\nObjectDefineProperties(Navigator.prototype, {\n hardwareConcurrency: kEnumerableProperty,\n language: kEnumerableProperty,\n languages: kEnumerableProperty,\n userAgent: kEnumerableProperty,\n platform: kEnumerableProperty,\n});\n\nmodule.exports = {\n getNavigatorPlatform,\n navigator: new Navigator(kInitialize),\n Navigator,\n};\n";
129
101
  const NODE_PATH_SOURCE = "// VENDORED, UNMODIFIED: Node.js lib/path.js\n//\n// version: v22.18.0\n// commit: d1b18258ce0d85253e4e44cede152e31363ef5db\n// source: https://raw.githubusercontent.com/nodejs/node/v22.18.0/lib/path.js\n// sha256: 3448e7d5a3a27f4ddc34e3d5278f39f1a0c560fd4cbbf55d07803113b720cda1\n//\n// Everything below this header is Node's own text, byte for byte; the sha256\n// above is of that text alone, so the vendoring is checkable with\n// tail -n +17 src/node-lib/path.js | shasum -a 256\n// Nothing here is edited. The free names the file expects of the Node runtime\n// -- `primordials`, `require` of `internal/constants`, `internal/validators`,\n// `internal/util` and `internal/deps/minimatch/index`, `module` and `process`\n// -- are supplied by the binding in src/shims/path.ts, which evaluates this\n// text. To move to a newer Node, replace this file and the header, and run\n// Node's own test/parallel/test-path-*.js against the build.\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nconst {\n ArrayPrototypeIncludes,\n ArrayPrototypeJoin,\n ArrayPrototypeSlice,\n FunctionPrototypeBind,\n StringPrototypeCharCodeAt,\n StringPrototypeIncludes,\n StringPrototypeIndexOf,\n StringPrototypeLastIndexOf,\n StringPrototypeRepeat,\n StringPrototypeReplace,\n StringPrototypeSlice,\n StringPrototypeSplit,\n StringPrototypeToLowerCase,\n StringPrototypeToUpperCase,\n} = primordials;\n\nconst {\n CHAR_UPPERCASE_A,\n CHAR_LOWERCASE_A,\n CHAR_UPPERCASE_Z,\n CHAR_LOWERCASE_Z,\n CHAR_DOT,\n CHAR_FORWARD_SLASH,\n CHAR_BACKWARD_SLASH,\n CHAR_COLON,\n CHAR_QUESTION_MARK,\n} = require('internal/constants');\nconst {\n validateObject,\n validateString,\n} = require('internal/validators');\n\nconst {\n getLazy,\n isWindows,\n isMacOS,\n} = require('internal/util');\n\nconst lazyMinimatch = getLazy(() => require('internal/deps/minimatch/index'));\n\nfunction isPathSeparator(code) {\n return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;\n}\n\nfunction isPosixPathSeparator(code) {\n return code === CHAR_FORWARD_SLASH;\n}\n\nconst WINDOWS_RESERVED_NAMES = [\n 'CON', 'PRN', 'AUX', 'NUL',\n 'COM1', 'COM2', 'COM3', 'COM4', 'COM5', 'COM6', 'COM7', 'COM8', 'COM9',\n 'LPT1', 'LPT2', 'LPT3', 'LPT4', 'LPT5', 'LPT6', 'LPT7', 'LPT8', 'LPT9',\n];\n\nfunction isWindowsReservedName(path, colonIndex) {\n const devicePart = StringPrototypeToUpperCase(StringPrototypeSlice(path, 0, colonIndex));\n return ArrayPrototypeIncludes(WINDOWS_RESERVED_NAMES, devicePart);\n}\n\nfunction isWindowsDeviceRoot(code) {\n return (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) ||\n (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z);\n}\n\n// Resolves . and .. elements in a path with directory names\nfunction normalizeString(path, allowAboveRoot, separator, isPathSeparator) {\n let res = '';\n let lastSegmentLength = 0;\n let lastSlash = -1;\n let dots = 0;\n let code = 0;\n for (let i = 0; i <= path.length; ++i) {\n if (i < path.length)\n code = StringPrototypeCharCodeAt(path, i);\n else if (isPathSeparator(code))\n break;\n else\n code = CHAR_FORWARD_SLASH;\n\n if (isPathSeparator(code)) {\n if (lastSlash === i - 1 || dots === 1) {\n // NOOP\n } else if (dots === 2) {\n if (res.length < 2 || lastSegmentLength !== 2 ||\n StringPrototypeCharCodeAt(res, res.length - 1) !== CHAR_DOT ||\n StringPrototypeCharCodeAt(res, res.length - 2) !== CHAR_DOT) {\n if (res.length > 2) {\n const lastSlashIndex = res.length - lastSegmentLength - 1;\n if (lastSlashIndex === -1) {\n res = '';\n lastSegmentLength = 0;\n } else {\n res = StringPrototypeSlice(res, 0, lastSlashIndex);\n lastSegmentLength =\n res.length - 1 - StringPrototypeLastIndexOf(res, separator);\n }\n lastSlash = i;\n dots = 0;\n continue;\n } else if (res.length !== 0) {\n res = '';\n lastSegmentLength = 0;\n lastSlash = i;\n dots = 0;\n continue;\n }\n }\n if (allowAboveRoot) {\n res += res.length > 0 ? `${separator}..` : '..';\n lastSegmentLength = 2;\n }\n } else {\n if (res.length > 0)\n res += `${separator}${StringPrototypeSlice(path, lastSlash + 1, i)}`;\n else\n res = StringPrototypeSlice(path, lastSlash + 1, i);\n lastSegmentLength = i - lastSlash - 1;\n }\n lastSlash = i;\n dots = 0;\n } else if (code === CHAR_DOT && dots !== -1) {\n ++dots;\n } else {\n dots = -1;\n }\n }\n return res;\n}\n\nfunction formatExt(ext) {\n return ext ? `${ext[0] === '.' ? '' : '.'}${ext}` : '';\n}\n\n/**\n * @param {string} sep\n * @param {{\n * dir?: string;\n * root?: string;\n * base?: string;\n * name?: string;\n * ext?: string;\n * }} pathObject\n * @returns {string}\n */\nfunction _format(sep, pathObject) {\n validateObject(pathObject, 'pathObject');\n const dir = pathObject.dir || pathObject.root;\n const base = pathObject.base ||\n `${pathObject.name || ''}${formatExt(pathObject.ext)}`;\n if (!dir) {\n return base;\n }\n return dir === pathObject.root ? `${dir}${base}` : `${dir}${sep}${base}`;\n}\n\nfunction glob(path, pattern, windows) {\n validateString(path, 'path');\n validateString(pattern, 'pattern');\n return lazyMinimatch().minimatch(path, pattern, {\n __proto__: null,\n nocase: isMacOS || isWindows,\n windowsPathsNoEscape: true,\n nonegate: true,\n nocomment: true,\n optimizationLevel: 2,\n platform: windows ? 'win32' : 'posix',\n nocaseMagicOnly: true,\n });\n}\nconst forwardSlashRegExp = /\\//g;\n\nconst win32 = {\n /**\n * path.resolve([from ...], to)\n * @param {...string} args\n * @returns {string}\n */\n resolve(...args) {\n let resolvedDevice = '';\n let resolvedTail = '';\n let resolvedAbsolute = false;\n\n for (let i = args.length - 1; i >= -1; i--) {\n let path;\n if (i >= 0) {\n path = args[i];\n validateString(path, `paths[${i}]`);\n\n // Skip empty entries\n if (path.length === 0) {\n continue;\n }\n } else if (resolvedDevice.length === 0) {\n path = process.cwd();\n // Fast path for current directory\n if (args.length === 0 || ((args.length === 1 && (args[0] === '' || args[0] === '.')) &&\n isPathSeparator(StringPrototypeCharCodeAt(path, 0)))) {\n if (!isWindows) {\n path = StringPrototypeReplace(path, forwardSlashRegExp, '\\\\');\n }\n return path;\n }\n } else {\n // Windows has the concept of drive-specific current working\n // directories. If we've resolved a drive letter but not yet an\n // absolute path, get cwd for that drive, or the process cwd if\n // the drive cwd is not available. We're sure the device is not\n // a UNC path at this points, because UNC paths are always absolute.\n path = process.env[`=${resolvedDevice}`] || process.cwd();\n\n // Verify that a cwd was found and that it actually points\n // to our drive. If not, default to the drive's root.\n if (path === undefined ||\n (StringPrototypeToLowerCase(StringPrototypeSlice(path, 0, 2)) !==\n StringPrototypeToLowerCase(resolvedDevice) &&\n StringPrototypeCharCodeAt(path, 2) === CHAR_BACKWARD_SLASH)) {\n path = `${resolvedDevice}\\\\`;\n }\n }\n\n const len = path.length;\n let rootEnd = 0;\n let device = '';\n let isAbsolute = false;\n const code = StringPrototypeCharCodeAt(path, 0);\n\n // Try to match a root\n if (len === 1) {\n if (isPathSeparator(code)) {\n // `path` contains just a path separator\n rootEnd = 1;\n isAbsolute = true;\n }\n } else if (isPathSeparator(code)) {\n // Possible UNC root\n\n // If we started with a separator, we know we at least have an\n // absolute path of some kind (UNC or otherwise)\n isAbsolute = true;\n\n if (isPathSeparator(StringPrototypeCharCodeAt(path, 1))) {\n // Matched double path separator at beginning\n let j = 2;\n let last = j;\n // Match 1 or more non-path separators\n while (j < len &&\n !isPathSeparator(StringPrototypeCharCodeAt(path, j))) {\n j++;\n }\n if (j < len && j !== last) {\n const firstPart = StringPrototypeSlice(path, last, j);\n // Matched!\n last = j;\n // Match 1 or more path separators\n while (j < len &&\n isPathSeparator(StringPrototypeCharCodeAt(path, j))) {\n j++;\n }\n if (j < len && j !== last) {\n // Matched!\n last = j;\n // Match 1 or more non-path separators\n while (j < len &&\n !isPathSeparator(StringPrototypeCharCodeAt(path, j))) {\n j++;\n }\n if (j === len || j !== last) {\n // We matched a UNC root\n device =\n `\\\\\\\\${firstPart}\\\\${StringPrototypeSlice(path, last, j)}`;\n rootEnd = j;\n }\n }\n }\n } else {\n rootEnd = 1;\n }\n } else if (isWindowsDeviceRoot(code) &&\n StringPrototypeCharCodeAt(path, 1) === CHAR_COLON) {\n // Possible device root\n device = StringPrototypeSlice(path, 0, 2);\n rootEnd = 2;\n if (len > 2 && isPathSeparator(StringPrototypeCharCodeAt(path, 2))) {\n // Treat separator following drive name as an absolute path\n // indicator\n isAbsolute = true;\n rootEnd = 3;\n }\n }\n\n if (device.length > 0) {\n if (resolvedDevice.length > 0) {\n if (StringPrototypeToLowerCase(device) !==\n StringPrototypeToLowerCase(resolvedDevice))\n // This path points to another device so it is not applicable\n continue;\n } else {\n resolvedDevice = device;\n }\n }\n\n if (resolvedAbsolute) {\n if (resolvedDevice.length > 0)\n break;\n } else {\n resolvedTail =\n `${StringPrototypeSlice(path, rootEnd)}\\\\${resolvedTail}`;\n resolvedAbsolute = isAbsolute;\n if (isAbsolute && resolvedDevice.length > 0) {\n break;\n }\n }\n }\n\n // At this point the path should be resolved to a full absolute path,\n // but handle relative paths to be safe (might happen when process.cwd()\n // fails)\n\n // Normalize the tail path\n resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, '\\\\',\n isPathSeparator);\n\n return resolvedAbsolute ?\n `${resolvedDevice}\\\\${resolvedTail}` :\n `${resolvedDevice}${resolvedTail}` || '.';\n },\n\n /**\n * @param {string} path\n * @returns {string}\n */\n normalize(path) {\n validateString(path, 'path');\n const len = path.length;\n if (len === 0)\n return '.';\n let rootEnd = 0;\n let device;\n let isAbsolute = false;\n const code = StringPrototypeCharCodeAt(path, 0);\n\n // Try to match a root\n if (len === 1) {\n // `path` contains just a single char, exit early to avoid\n // unnecessary work\n return isPosixPathSeparator(code) ? '\\\\' : path;\n }\n if (isPathSeparator(code)) {\n // Possible UNC root\n\n // If we started with a separator, we know we at least have an absolute\n // path of some kind (UNC or otherwise)\n isAbsolute = true;\n\n if (isPathSeparator(StringPrototypeCharCodeAt(path, 1))) {\n // Matched double path separator at beginning\n let j = 2;\n let last = j;\n // Match 1 or more non-path separators\n while (j < len &&\n !isPathSeparator(StringPrototypeCharCodeAt(path, j))) {\n j++;\n }\n if (j < len && j !== last) {\n const firstPart = StringPrototypeSlice(path, last, j);\n // Matched!\n last = j;\n // Match 1 or more path separators\n while (j < len &&\n isPathSeparator(StringPrototypeCharCodeAt(path, j))) {\n j++;\n }\n if (j < len && j !== last) {\n // Matched!\n last = j;\n // Match 1 or more non-path separators\n while (j < len &&\n !isPathSeparator(StringPrototypeCharCodeAt(path, j))) {\n j++;\n }\n if (j === len) {\n // We matched a UNC root only\n // Return the normalized version of the UNC root since there\n // is nothing left to process\n return `\\\\\\\\${firstPart}\\\\${StringPrototypeSlice(path, last)}\\\\`;\n }\n if (j !== last) {\n // We matched a UNC root with leftovers\n device =\n `\\\\\\\\${firstPart}\\\\${StringPrototypeSlice(path, last, j)}`;\n rootEnd = j;\n }\n }\n }\n } else {\n rootEnd = 1;\n }\n } else {\n const colonIndex = StringPrototypeIndexOf(path, ':');\n if (colonIndex > 0) {\n if (isWindowsDeviceRoot(code) && colonIndex === 1) {\n device = StringPrototypeSlice(path, 0, 2);\n rootEnd = 2;\n if (len > 2 && isPathSeparator(StringPrototypeCharCodeAt(path, 2))) {\n isAbsolute = true;\n rootEnd = 3;\n }\n } else if (isWindowsReservedName(path, colonIndex)) {\n device = StringPrototypeSlice(path, 0, colonIndex + 1);\n rootEnd = colonIndex + 1;\n\n }\n }\n }\n\n let tail = rootEnd < len ?\n normalizeString(StringPrototypeSlice(path, rootEnd),\n !isAbsolute, '\\\\', isPathSeparator) :\n '';\n if (tail.length === 0 && !isAbsolute)\n tail = '.';\n if (tail.length > 0 &&\n isPathSeparator(StringPrototypeCharCodeAt(path, len - 1)))\n tail += '\\\\';\n if (!isAbsolute && device === undefined && StringPrototypeIncludes(path, ':')) {\n // If the original path was not absolute and if we have not been able to\n // resolve it relative to a particular device, we need to ensure that the\n // `tail` has not become something that Windows might interpret as an\n // absolute path. See CVE-2024-36139.\n if (tail.length >= 2 &&\n isWindowsDeviceRoot(StringPrototypeCharCodeAt(tail, 0)) &&\n StringPrototypeCharCodeAt(tail, 1) === CHAR_COLON) {\n return `.\\\\${tail}`;\n }\n let index = StringPrototypeIndexOf(path, ':');\n\n do {\n if (index === len - 1 || isPathSeparator(StringPrototypeCharCodeAt(path, index + 1))) {\n return `.\\\\${tail}`;\n }\n } while ((index = StringPrototypeIndexOf(path, ':', index + 1)) !== -1);\n }\n const colonIndex = StringPrototypeIndexOf(path, ':');\n if (isWindowsReservedName(path, colonIndex)) {\n return `.\\\\${device ?? ''}${tail}`;\n }\n if (device === undefined) {\n return isAbsolute ? `\\\\${tail}` : tail;\n }\n return isAbsolute ? `${device}\\\\${tail}` : `${device}${tail}`;\n },\n\n /**\n * @param {string} path\n * @returns {boolean}\n */\n isAbsolute(path) {\n validateString(path, 'path');\n const len = path.length;\n if (len === 0)\n return false;\n\n const code = StringPrototypeCharCodeAt(path, 0);\n return isPathSeparator(code) ||\n // Possible device root\n (len > 2 &&\n isWindowsDeviceRoot(code) &&\n StringPrototypeCharCodeAt(path, 1) === CHAR_COLON &&\n isPathSeparator(StringPrototypeCharCodeAt(path, 2)));\n },\n\n /**\n * @param {...string} args\n * @returns {string}\n */\n join(...args) {\n if (args.length === 0)\n return '.';\n\n let joined;\n let firstPart;\n for (let i = 0; i < args.length; ++i) {\n const arg = args[i];\n validateString(arg, 'path');\n if (arg.length > 0) {\n if (joined === undefined)\n joined = firstPart = arg;\n else\n joined += `\\\\${arg}`;\n }\n }\n\n if (joined === undefined)\n return '.';\n\n // Make sure that the joined path doesn't start with two slashes, because\n // normalize() will mistake it for a UNC path then.\n //\n // This step is skipped when it is very clear that the user actually\n // intended to point at a UNC path. This is assumed when the first\n // non-empty string arguments starts with exactly two slashes followed by\n // at least one more non-slash character.\n //\n // Note that for normalize() to treat a path as a UNC path it needs to\n // have at least 2 components, so we don't filter for that here.\n // This means that the user can use join to construct UNC paths from\n // a server name and a share name; for example:\n // path.join('//server', 'share') -> '\\\\\\\\server\\\\share\\\\')\n let needsReplace = true;\n let slashCount = 0;\n if (isPathSeparator(StringPrototypeCharCodeAt(firstPart, 0))) {\n ++slashCount;\n const firstLen = firstPart.length;\n if (firstLen > 1 &&\n isPathSeparator(StringPrototypeCharCodeAt(firstPart, 1))) {\n ++slashCount;\n if (firstLen > 2) {\n if (isPathSeparator(StringPrototypeCharCodeAt(firstPart, 2)))\n ++slashCount;\n else {\n // We matched a UNC path in the first part\n needsReplace = false;\n }\n }\n }\n }\n if (needsReplace) {\n // Find any more consecutive slashes we need to replace\n while (slashCount < joined.length &&\n isPathSeparator(StringPrototypeCharCodeAt(joined, slashCount))) {\n slashCount++;\n }\n\n // Replace the slashes if needed\n if (slashCount >= 2)\n joined = `\\\\${StringPrototypeSlice(joined, slashCount)}`;\n }\n\n return win32.normalize(joined);\n },\n\n /**\n * It will solve the relative path from `from` to `to`, for instance\n * from = 'C:\\\\orandea\\\\test\\\\aaa'\n * to = 'C:\\\\orandea\\\\impl\\\\bbb'\n * The output of the function should be: '..\\\\..\\\\impl\\\\bbb'\n * @param {string} from\n * @param {string} to\n * @returns {string}\n */\n relative(from, to) {\n validateString(from, 'from');\n validateString(to, 'to');\n\n if (from === to)\n return '';\n\n const fromOrig = win32.resolve(from);\n const toOrig = win32.resolve(to);\n\n if (fromOrig === toOrig)\n return '';\n\n from = StringPrototypeToLowerCase(fromOrig);\n to = StringPrototypeToLowerCase(toOrig);\n\n if (from === to)\n return '';\n\n if (fromOrig.length !== from.length || toOrig.length !== to.length) {\n const fromSplit = StringPrototypeSplit(fromOrig, '\\\\');\n const toSplit = StringPrototypeSplit(toOrig, '\\\\');\n if (fromSplit[fromSplit.length - 1] === '') {\n fromSplit.pop();\n }\n if (toSplit[toSplit.length - 1] === '') {\n toSplit.pop();\n }\n\n const fromLen = fromSplit.length;\n const toLen = toSplit.length;\n const length = fromLen < toLen ? fromLen : toLen;\n\n let i;\n for (i = 0; i < length; i++) {\n if (StringPrototypeToLowerCase(fromSplit[i]) !== StringPrototypeToLowerCase(toSplit[i])) {\n break;\n }\n }\n\n if (i === 0) {\n return toOrig;\n } else if (i === length) {\n if (toLen > length) {\n return ArrayPrototypeJoin(ArrayPrototypeSlice(toSplit, i), '\\\\');\n }\n if (fromLen > length) {\n return StringPrototypeRepeat('..\\\\', fromLen - 1 - i) + '..';\n }\n return '';\n }\n\n return StringPrototypeRepeat('..\\\\', fromLen - i) + ArrayPrototypeJoin(ArrayPrototypeSlice(toSplit, i), '\\\\');\n }\n\n // Trim any leading backslashes\n let fromStart = 0;\n while (fromStart < from.length &&\n StringPrototypeCharCodeAt(from, fromStart) === CHAR_BACKWARD_SLASH) {\n fromStart++;\n }\n // Trim trailing backslashes (applicable to UNC paths only)\n let fromEnd = from.length;\n while (\n fromEnd - 1 > fromStart &&\n StringPrototypeCharCodeAt(from, fromEnd - 1) === CHAR_BACKWARD_SLASH\n ) {\n fromEnd--;\n }\n const fromLen = fromEnd - fromStart;\n\n // Trim any leading backslashes\n let toStart = 0;\n while (toStart < to.length &&\n StringPrototypeCharCodeAt(to, toStart) === CHAR_BACKWARD_SLASH) {\n toStart++;\n }\n // Trim trailing backslashes (applicable to UNC paths only)\n let toEnd = to.length;\n while (toEnd - 1 > toStart &&\n StringPrototypeCharCodeAt(to, toEnd - 1) === CHAR_BACKWARD_SLASH) {\n toEnd--;\n }\n const toLen = toEnd - toStart;\n\n // Compare paths to find the longest common path from root\n const length = fromLen < toLen ? fromLen : toLen;\n let lastCommonSep = -1;\n let i = 0;\n for (; i < length; i++) {\n const fromCode = StringPrototypeCharCodeAt(from, fromStart + i);\n if (fromCode !== StringPrototypeCharCodeAt(to, toStart + i))\n break;\n else if (fromCode === CHAR_BACKWARD_SLASH)\n lastCommonSep = i;\n }\n\n // We found a mismatch before the first common path separator was seen, so\n // return the original `to`.\n if (i !== length) {\n if (lastCommonSep === -1)\n return toOrig;\n } else {\n if (toLen > length) {\n if (StringPrototypeCharCodeAt(to, toStart + i) ===\n CHAR_BACKWARD_SLASH) {\n // We get here if `from` is the exact base path for `to`.\n // For example: from='C:\\\\foo\\\\bar'; to='C:\\\\foo\\\\bar\\\\baz'\n return StringPrototypeSlice(toOrig, toStart + i + 1);\n }\n if (i === 2) {\n // We get here if `from` is the device root.\n // For example: from='C:\\\\'; to='C:\\\\foo'\n return StringPrototypeSlice(toOrig, toStart + i);\n }\n }\n if (fromLen > length) {\n if (StringPrototypeCharCodeAt(from, fromStart + i) ===\n CHAR_BACKWARD_SLASH) {\n // We get here if `to` is the exact base path for `from`.\n // For example: from='C:\\\\foo\\\\bar'; to='C:\\\\foo'\n lastCommonSep = i;\n } else if (i === 2) {\n // We get here if `to` is the device root.\n // For example: from='C:\\\\foo\\\\bar'; to='C:\\\\'\n lastCommonSep = 3;\n }\n }\n if (lastCommonSep === -1)\n lastCommonSep = 0;\n }\n\n let out = '';\n // Generate the relative path based on the path difference between `to` and\n // `from`\n for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {\n if (i === fromEnd ||\n StringPrototypeCharCodeAt(from, i) === CHAR_BACKWARD_SLASH) {\n out += out.length === 0 ? '..' : '\\\\..';\n }\n }\n\n toStart += lastCommonSep;\n\n // Lastly, append the rest of the destination (`to`) path that comes after\n // the common path parts\n if (out.length > 0)\n return `${out}${StringPrototypeSlice(toOrig, toStart, toEnd)}`;\n\n if (StringPrototypeCharCodeAt(toOrig, toStart) === CHAR_BACKWARD_SLASH)\n ++toStart;\n return StringPrototypeSlice(toOrig, toStart, toEnd);\n },\n\n /**\n * @param {string} path\n * @returns {string}\n */\n toNamespacedPath(path) {\n // Note: this will *probably* throw somewhere.\n if (typeof path !== 'string' || path.length === 0)\n return path;\n\n const resolvedPath = win32.resolve(path);\n\n if (resolvedPath.length <= 2)\n return path;\n\n if (StringPrototypeCharCodeAt(resolvedPath, 0) === CHAR_BACKWARD_SLASH) {\n // Possible UNC root\n if (StringPrototypeCharCodeAt(resolvedPath, 1) === CHAR_BACKWARD_SLASH) {\n const code = StringPrototypeCharCodeAt(resolvedPath, 2);\n if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) {\n // Matched non-long UNC root, convert the path to a long UNC path\n return `\\\\\\\\?\\\\UNC\\\\${StringPrototypeSlice(resolvedPath, 2)}`;\n }\n }\n } else if (\n isWindowsDeviceRoot(StringPrototypeCharCodeAt(resolvedPath, 0)) &&\n StringPrototypeCharCodeAt(resolvedPath, 1) === CHAR_COLON &&\n StringPrototypeCharCodeAt(resolvedPath, 2) === CHAR_BACKWARD_SLASH\n ) {\n // Matched device root, convert the path to a long UNC path\n return `\\\\\\\\?\\\\${resolvedPath}`;\n }\n\n return resolvedPath;\n },\n\n /**\n * @param {string} path\n * @returns {string}\n */\n dirname(path) {\n validateString(path, 'path');\n const len = path.length;\n if (len === 0)\n return '.';\n let rootEnd = -1;\n let offset = 0;\n const code = StringPrototypeCharCodeAt(path, 0);\n\n if (len === 1) {\n // `path` contains just a path separator, exit early to avoid\n // unnecessary work or a dot.\n return isPathSeparator(code) ? path : '.';\n }\n\n // Try to match a root\n if (isPathSeparator(code)) {\n // Possible UNC root\n\n rootEnd = offset = 1;\n\n if (isPathSeparator(StringPrototypeCharCodeAt(path, 1))) {\n // Matched double path separator at beginning\n let j = 2;\n let last = j;\n // Match 1 or more non-path separators\n while (j < len &&\n !isPathSeparator(StringPrototypeCharCodeAt(path, j))) {\n j++;\n }\n if (j < len && j !== last) {\n // Matched!\n last = j;\n // Match 1 or more path separators\n while (j < len &&\n isPathSeparator(StringPrototypeCharCodeAt(path, j))) {\n j++;\n }\n if (j < len && j !== last) {\n // Matched!\n last = j;\n // Match 1 or more non-path separators\n while (j < len &&\n !isPathSeparator(StringPrototypeCharCodeAt(path, j))) {\n j++;\n }\n if (j === len) {\n // We matched a UNC root only\n return path;\n }\n if (j !== last) {\n // We matched a UNC root with leftovers\n\n // Offset by 1 to include the separator after the UNC root to\n // treat it as a \"normal root\" on top of a (UNC) root\n rootEnd = offset = j + 1;\n }\n }\n }\n }\n // Possible device root\n } else if (isWindowsDeviceRoot(code) &&\n StringPrototypeCharCodeAt(path, 1) === CHAR_COLON) {\n rootEnd =\n len > 2 && isPathSeparator(StringPrototypeCharCodeAt(path, 2)) ? 3 : 2;\n offset = rootEnd;\n }\n\n let end = -1;\n let matchedSlash = true;\n for (let i = len - 1; i >= offset; --i) {\n if (isPathSeparator(StringPrototypeCharCodeAt(path, i))) {\n if (!matchedSlash) {\n end = i;\n break;\n }\n } else {\n // We saw the first non-path separator\n matchedSlash = false;\n }\n }\n\n if (end === -1) {\n if (rootEnd === -1)\n return '.';\n\n end = rootEnd;\n }\n return StringPrototypeSlice(path, 0, end);\n },\n\n /**\n * @param {string} path\n * @param {string} [suffix]\n * @returns {string}\n */\n basename(path, suffix) {\n if (suffix !== undefined)\n validateString(suffix, 'suffix');\n validateString(path, 'path');\n let start = 0;\n let end = -1;\n let matchedSlash = true;\n\n // Check for a drive letter prefix so as not to mistake the following\n // path separator as an extra separator at the end of the path that can be\n // disregarded\n if (path.length >= 2 &&\n isWindowsDeviceRoot(StringPrototypeCharCodeAt(path, 0)) &&\n StringPrototypeCharCodeAt(path, 1) === CHAR_COLON) {\n start = 2;\n }\n\n if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {\n if (suffix === path)\n return '';\n let extIdx = suffix.length - 1;\n let firstNonSlashEnd = -1;\n for (let i = path.length - 1; i >= start; --i) {\n const code = StringPrototypeCharCodeAt(path, i);\n if (isPathSeparator(code)) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n start = i + 1;\n break;\n }\n } else {\n if (firstNonSlashEnd === -1) {\n // We saw the first non-path separator, remember this index in case\n // we need it if the extension ends up not matching\n matchedSlash = false;\n firstNonSlashEnd = i + 1;\n }\n if (extIdx >= 0) {\n // Try to match the explicit extension\n if (code === StringPrototypeCharCodeAt(suffix, extIdx)) {\n if (--extIdx === -1) {\n // We matched the extension, so mark this as the end of our path\n // component\n end = i;\n }\n } else {\n // Extension does not match, so our result is the entire path\n // component\n extIdx = -1;\n end = firstNonSlashEnd;\n }\n }\n }\n }\n\n if (start === end)\n end = firstNonSlashEnd;\n else if (end === -1)\n end = path.length;\n return StringPrototypeSlice(path, start, end);\n }\n for (let i = path.length - 1; i >= start; --i) {\n if (isPathSeparator(StringPrototypeCharCodeAt(path, i))) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n start = i + 1;\n break;\n }\n } else if (end === -1) {\n // We saw the first non-path separator, mark this as the end of our\n // path component\n matchedSlash = false;\n end = i + 1;\n }\n }\n\n if (end === -1)\n return '';\n return StringPrototypeSlice(path, start, end);\n },\n\n /**\n * @param {string} path\n * @returns {string}\n */\n extname(path) {\n validateString(path, 'path');\n let start = 0;\n let startDot = -1;\n let startPart = 0;\n let end = -1;\n let matchedSlash = true;\n // Track the state of characters (if any) we see before our first dot and\n // after any path separator we find\n let preDotState = 0;\n\n // Check for a drive letter prefix so as not to mistake the following\n // path separator as an extra separator at the end of the path that can be\n // disregarded\n\n if (path.length >= 2 &&\n StringPrototypeCharCodeAt(path, 1) === CHAR_COLON &&\n isWindowsDeviceRoot(StringPrototypeCharCodeAt(path, 0))) {\n start = startPart = 2;\n }\n\n for (let i = path.length - 1; i >= start; --i) {\n const code = StringPrototypeCharCodeAt(path, i);\n if (isPathSeparator(code)) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n startPart = i + 1;\n break;\n }\n continue;\n }\n if (end === -1) {\n // We saw the first non-path separator, mark this as the end of our\n // extension\n matchedSlash = false;\n end = i + 1;\n }\n if (code === CHAR_DOT) {\n // If this is our first dot, mark it as the start of our extension\n if (startDot === -1)\n startDot = i;\n else if (preDotState !== 1)\n preDotState = 1;\n } else if (startDot !== -1) {\n // We saw a non-dot and non-path separator before our dot, so we should\n // have a good chance at having a non-empty extension\n preDotState = -1;\n }\n }\n\n if (startDot === -1 ||\n end === -1 ||\n // We saw a non-dot character immediately before the dot\n preDotState === 0 ||\n // The (right-most) trimmed path component is exactly '..'\n (preDotState === 1 &&\n startDot === end - 1 &&\n startDot === startPart + 1)) {\n return '';\n }\n return StringPrototypeSlice(path, startDot, end);\n },\n\n format: FunctionPrototypeBind(_format, null, '\\\\'),\n\n /**\n * @param {string} path\n * @returns {{\n * dir: string;\n * root: string;\n * base: string;\n * name: string;\n * ext: string;\n * }}\n */\n parse(path) {\n validateString(path, 'path');\n\n const ret = { root: '', dir: '', base: '', ext: '', name: '' };\n if (path.length === 0)\n return ret;\n\n const len = path.length;\n let rootEnd = 0;\n let code = StringPrototypeCharCodeAt(path, 0);\n\n if (len === 1) {\n if (isPathSeparator(code)) {\n // `path` contains just a path separator, exit early to avoid\n // unnecessary work\n ret.root = ret.dir = path;\n return ret;\n }\n ret.base = ret.name = path;\n return ret;\n }\n // Try to match a root\n if (isPathSeparator(code)) {\n // Possible UNC root\n\n rootEnd = 1;\n if (isPathSeparator(StringPrototypeCharCodeAt(path, 1))) {\n // Matched double path separator at beginning\n let j = 2;\n let last = j;\n // Match 1 or more non-path separators\n while (j < len &&\n !isPathSeparator(StringPrototypeCharCodeAt(path, j))) {\n j++;\n }\n if (j < len && j !== last) {\n // Matched!\n last = j;\n // Match 1 or more path separators\n while (j < len &&\n isPathSeparator(StringPrototypeCharCodeAt(path, j))) {\n j++;\n }\n if (j < len && j !== last) {\n // Matched!\n last = j;\n // Match 1 or more non-path separators\n while (j < len &&\n !isPathSeparator(StringPrototypeCharCodeAt(path, j))) {\n j++;\n }\n if (j === len) {\n // We matched a UNC root only\n rootEnd = j;\n } else if (j !== last) {\n // We matched a UNC root with leftovers\n rootEnd = j + 1;\n }\n }\n }\n }\n } else if (isWindowsDeviceRoot(code) &&\n StringPrototypeCharCodeAt(path, 1) === CHAR_COLON) {\n // Possible device root\n if (len <= 2) {\n // `path` contains just a drive root, exit early to avoid\n // unnecessary work\n ret.root = ret.dir = path;\n return ret;\n }\n rootEnd = 2;\n if (isPathSeparator(StringPrototypeCharCodeAt(path, 2))) {\n if (len === 3) {\n // `path` contains just a drive root, exit early to avoid\n // unnecessary work\n ret.root = ret.dir = path;\n return ret;\n }\n rootEnd = 3;\n }\n }\n if (rootEnd > 0)\n ret.root = StringPrototypeSlice(path, 0, rootEnd);\n\n let startDot = -1;\n let startPart = rootEnd;\n let end = -1;\n let matchedSlash = true;\n let i = path.length - 1;\n\n // Track the state of characters (if any) we see before our first dot and\n // after any path separator we find\n let preDotState = 0;\n\n // Get non-dir info\n for (; i >= rootEnd; --i) {\n code = StringPrototypeCharCodeAt(path, i);\n if (isPathSeparator(code)) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n startPart = i + 1;\n break;\n }\n continue;\n }\n if (end === -1) {\n // We saw the first non-path separator, mark this as the end of our\n // extension\n matchedSlash = false;\n end = i + 1;\n }\n if (code === CHAR_DOT) {\n // If this is our first dot, mark it as the start of our extension\n if (startDot === -1)\n startDot = i;\n else if (preDotState !== 1)\n preDotState = 1;\n } else if (startDot !== -1) {\n // We saw a non-dot and non-path separator before our dot, so we should\n // have a good chance at having a non-empty extension\n preDotState = -1;\n }\n }\n\n if (end !== -1) {\n if (startDot === -1 ||\n // We saw a non-dot character immediately before the dot\n preDotState === 0 ||\n // The (right-most) trimmed path component is exactly '..'\n (preDotState === 1 &&\n startDot === end - 1 &&\n startDot === startPart + 1)) {\n ret.base = ret.name = StringPrototypeSlice(path, startPart, end);\n } else {\n ret.name = StringPrototypeSlice(path, startPart, startDot);\n ret.base = StringPrototypeSlice(path, startPart, end);\n ret.ext = StringPrototypeSlice(path, startDot, end);\n }\n }\n\n // If the directory is the root, use the entire root as the `dir` including\n // the trailing slash if any (`C:\\abc` -> `C:\\`). Otherwise, strip out the\n // trailing slash (`C:\\abc\\def` -> `C:\\abc`).\n if (startPart > 0 && startPart !== rootEnd)\n ret.dir = StringPrototypeSlice(path, 0, startPart - 1);\n else\n ret.dir = ret.root;\n\n return ret;\n },\n\n matchesGlob(path, pattern) {\n return glob(path, pattern, true);\n },\n\n sep: '\\\\',\n delimiter: ';',\n win32: null,\n posix: null,\n};\n\nconst posixCwd = (() => {\n if (isWindows) {\n // Converts Windows' backslash path separators to POSIX forward slashes\n // and truncates any drive indicator\n const regexp = /\\\\/g;\n return () => {\n const cwd = StringPrototypeReplace(process.cwd(), regexp, '/');\n return StringPrototypeSlice(cwd, StringPrototypeIndexOf(cwd, '/'));\n };\n }\n\n // We're already on POSIX, no need for any transformations\n return () => process.cwd();\n})();\n\nconst posix = {\n /**\n * path.resolve([from ...], to)\n * @param {...string} args\n * @returns {string}\n */\n resolve(...args) {\n if (args.length === 0 || (args.length === 1 && (args[0] === '' || args[0] === '.'))) {\n const cwd = posixCwd();\n if (StringPrototypeCharCodeAt(cwd, 0) === CHAR_FORWARD_SLASH) {\n return cwd;\n }\n }\n let resolvedPath = '';\n let resolvedAbsolute = false;\n\n for (let i = args.length - 1; i >= 0 && !resolvedAbsolute; i--) {\n const path = args[i];\n validateString(path, `paths[${i}]`);\n\n // Skip empty entries\n if (path.length === 0) {\n continue;\n }\n\n resolvedPath = `${path}/${resolvedPath}`;\n resolvedAbsolute =\n StringPrototypeCharCodeAt(path, 0) === CHAR_FORWARD_SLASH;\n }\n\n if (!resolvedAbsolute) {\n const cwd = posixCwd();\n resolvedPath = `${cwd}/${resolvedPath}`;\n resolvedAbsolute =\n StringPrototypeCharCodeAt(cwd, 0) === CHAR_FORWARD_SLASH;\n }\n\n // At this point the path should be resolved to a full absolute path, but\n // handle relative paths to be safe (might happen when process.cwd() fails)\n\n // Normalize the path\n resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, '/',\n isPosixPathSeparator);\n\n if (resolvedAbsolute) {\n return `/${resolvedPath}`;\n }\n return resolvedPath.length > 0 ? resolvedPath : '.';\n },\n\n /**\n * @param {string} path\n * @returns {string}\n */\n normalize(path) {\n validateString(path, 'path');\n\n if (path.length === 0)\n return '.';\n\n const isAbsolute =\n StringPrototypeCharCodeAt(path, 0) === CHAR_FORWARD_SLASH;\n const trailingSeparator =\n StringPrototypeCharCodeAt(path, path.length - 1) === CHAR_FORWARD_SLASH;\n\n // Normalize the path\n path = normalizeString(path, !isAbsolute, '/', isPosixPathSeparator);\n\n if (path.length === 0) {\n if (isAbsolute)\n return '/';\n return trailingSeparator ? './' : '.';\n }\n if (trailingSeparator)\n path += '/';\n\n return isAbsolute ? `/${path}` : path;\n },\n\n /**\n * @param {string} path\n * @returns {boolean}\n */\n isAbsolute(path) {\n validateString(path, 'path');\n return path.length > 0 &&\n StringPrototypeCharCodeAt(path, 0) === CHAR_FORWARD_SLASH;\n },\n\n /**\n * @param {...string} args\n * @returns {string}\n */\n join(...args) {\n if (args.length === 0)\n return '.';\n\n const path = [];\n for (let i = 0; i < args.length; ++i) {\n const arg = args[i];\n validateString(arg, 'path');\n if (arg.length > 0) {\n path.push(arg);\n }\n }\n\n if (path.length === 0)\n return '.';\n\n return posix.normalize(ArrayPrototypeJoin(path, '/'));\n },\n\n /**\n * @param {string} from\n * @param {string} to\n * @returns {string}\n */\n relative(from, to) {\n validateString(from, 'from');\n validateString(to, 'to');\n\n if (from === to)\n return '';\n\n // Trim leading forward slashes.\n from = posix.resolve(from);\n to = posix.resolve(to);\n\n if (from === to)\n return '';\n\n const fromStart = 1;\n const fromEnd = from.length;\n const fromLen = fromEnd - fromStart;\n const toStart = 1;\n const toLen = to.length - toStart;\n\n // Compare paths to find the longest common path from root\n const length = (fromLen < toLen ? fromLen : toLen);\n let lastCommonSep = -1;\n let i = 0;\n for (; i < length; i++) {\n const fromCode = StringPrototypeCharCodeAt(from, fromStart + i);\n if (fromCode !== StringPrototypeCharCodeAt(to, toStart + i))\n break;\n else if (fromCode === CHAR_FORWARD_SLASH)\n lastCommonSep = i;\n }\n if (i === length) {\n if (toLen > length) {\n if (StringPrototypeCharCodeAt(to, toStart + i) === CHAR_FORWARD_SLASH) {\n // We get here if `from` is the exact base path for `to`.\n // For example: from='/foo/bar'; to='/foo/bar/baz'\n return StringPrototypeSlice(to, toStart + i + 1);\n }\n if (i === 0) {\n // We get here if `from` is the root\n // For example: from='/'; to='/foo'\n return StringPrototypeSlice(to, toStart + i);\n }\n } else if (fromLen > length) {\n if (StringPrototypeCharCodeAt(from, fromStart + i) ===\n CHAR_FORWARD_SLASH) {\n // We get here if `to` is the exact base path for `from`.\n // For example: from='/foo/bar/baz'; to='/foo/bar'\n lastCommonSep = i;\n } else if (i === 0) {\n // We get here if `to` is the root.\n // For example: from='/foo/bar'; to='/'\n lastCommonSep = 0;\n }\n }\n }\n\n let out = '';\n // Generate the relative path based on the path difference between `to`\n // and `from`.\n for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {\n if (i === fromEnd ||\n StringPrototypeCharCodeAt(from, i) === CHAR_FORWARD_SLASH) {\n out += out.length === 0 ? '..' : '/..';\n }\n }\n\n // Lastly, append the rest of the destination (`to`) path that comes after\n // the common path parts.\n return `${out}${StringPrototypeSlice(to, toStart + lastCommonSep)}`;\n },\n\n /**\n * @param {string} path\n * @returns {string}\n */\n toNamespacedPath(path) {\n // Non-op on posix systems\n return path;\n },\n\n /**\n * @param {string} path\n * @returns {string}\n */\n dirname(path) {\n validateString(path, 'path');\n if (path.length === 0)\n return '.';\n const hasRoot = StringPrototypeCharCodeAt(path, 0) === CHAR_FORWARD_SLASH;\n let end = -1;\n let matchedSlash = true;\n for (let i = path.length - 1; i >= 1; --i) {\n if (StringPrototypeCharCodeAt(path, i) === CHAR_FORWARD_SLASH) {\n if (!matchedSlash) {\n end = i;\n break;\n }\n } else {\n // We saw the first non-path separator\n matchedSlash = false;\n }\n }\n\n if (end === -1)\n return hasRoot ? '/' : '.';\n if (hasRoot && end === 1)\n return '//';\n return StringPrototypeSlice(path, 0, end);\n },\n\n /**\n * @param {string} path\n * @param {string} [suffix]\n * @returns {string}\n */\n basename(path, suffix) {\n if (suffix !== undefined)\n validateString(suffix, 'suffix');\n validateString(path, 'path');\n\n let start = 0;\n let end = -1;\n let matchedSlash = true;\n\n if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {\n if (suffix === path)\n return '';\n let extIdx = suffix.length - 1;\n let firstNonSlashEnd = -1;\n for (let i = path.length - 1; i >= 0; --i) {\n const code = StringPrototypeCharCodeAt(path, i);\n if (code === CHAR_FORWARD_SLASH) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n start = i + 1;\n break;\n }\n } else {\n if (firstNonSlashEnd === -1) {\n // We saw the first non-path separator, remember this index in case\n // we need it if the extension ends up not matching\n matchedSlash = false;\n firstNonSlashEnd = i + 1;\n }\n if (extIdx >= 0) {\n // Try to match the explicit extension\n if (code === StringPrototypeCharCodeAt(suffix, extIdx)) {\n if (--extIdx === -1) {\n // We matched the extension, so mark this as the end of our path\n // component\n end = i;\n }\n } else {\n // Extension does not match, so our result is the entire path\n // component\n extIdx = -1;\n end = firstNonSlashEnd;\n }\n }\n }\n }\n\n if (start === end)\n end = firstNonSlashEnd;\n else if (end === -1)\n end = path.length;\n return StringPrototypeSlice(path, start, end);\n }\n for (let i = path.length - 1; i >= 0; --i) {\n if (StringPrototypeCharCodeAt(path, i) === CHAR_FORWARD_SLASH) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n start = i + 1;\n break;\n }\n } else if (end === -1) {\n // We saw the first non-path separator, mark this as the end of our\n // path component\n matchedSlash = false;\n end = i + 1;\n }\n }\n\n if (end === -1)\n return '';\n return StringPrototypeSlice(path, start, end);\n },\n\n /**\n * @param {string} path\n * @returns {string}\n */\n extname(path) {\n validateString(path, 'path');\n let startDot = -1;\n let startPart = 0;\n let end = -1;\n let matchedSlash = true;\n // Track the state of characters (if any) we see before our first dot and\n // after any path separator we find\n let preDotState = 0;\n for (let i = path.length - 1; i >= 0; --i) {\n const char = path[i];\n if (char === '/') {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n startPart = i + 1;\n break;\n }\n continue;\n }\n if (end === -1) {\n // We saw the first non-path separator, mark this as the end of our\n // extension\n matchedSlash = false;\n end = i + 1;\n }\n if (char === '.') {\n // If this is our first dot, mark it as the start of our extension\n if (startDot === -1)\n startDot = i;\n else if (preDotState !== 1)\n preDotState = 1;\n } else if (startDot !== -1) {\n // We saw a non-dot and non-path separator before our dot, so we should\n // have a good chance at having a non-empty extension\n preDotState = -1;\n }\n }\n\n if (startDot === -1 ||\n end === -1 ||\n // We saw a non-dot character immediately before the dot\n preDotState === 0 ||\n // The (right-most) trimmed path component is exactly '..'\n (preDotState === 1 &&\n startDot === end - 1 &&\n startDot === startPart + 1)) {\n return '';\n }\n return StringPrototypeSlice(path, startDot, end);\n },\n\n format: FunctionPrototypeBind(_format, null, '/'),\n\n /**\n * @param {string} path\n * @returns {{\n * dir: string;\n * root: string;\n * base: string;\n * name: string;\n * ext: string;\n * }}\n */\n parse(path) {\n validateString(path, 'path');\n\n const ret = { root: '', dir: '', base: '', ext: '', name: '' };\n if (path.length === 0)\n return ret;\n const isAbsolute =\n StringPrototypeCharCodeAt(path, 0) === CHAR_FORWARD_SLASH;\n let start;\n if (isAbsolute) {\n ret.root = '/';\n start = 1;\n } else {\n start = 0;\n }\n let startDot = -1;\n let startPart = 0;\n let end = -1;\n let matchedSlash = true;\n let i = path.length - 1;\n\n // Track the state of characters (if any) we see before our first dot and\n // after any path separator we find\n let preDotState = 0;\n\n // Get non-dir info\n for (; i >= start; --i) {\n const code = StringPrototypeCharCodeAt(path, i);\n if (code === CHAR_FORWARD_SLASH) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n startPart = i + 1;\n break;\n }\n continue;\n }\n if (end === -1) {\n // We saw the first non-path separator, mark this as the end of our\n // extension\n matchedSlash = false;\n end = i + 1;\n }\n if (code === CHAR_DOT) {\n // If this is our first dot, mark it as the start of our extension\n if (startDot === -1)\n startDot = i;\n else if (preDotState !== 1)\n preDotState = 1;\n } else if (startDot !== -1) {\n // We saw a non-dot and non-path separator before our dot, so we should\n // have a good chance at having a non-empty extension\n preDotState = -1;\n }\n }\n\n if (end !== -1) {\n const start = startPart === 0 && isAbsolute ? 1 : startPart;\n if (startDot === -1 ||\n // We saw a non-dot character immediately before the dot\n preDotState === 0 ||\n // The (right-most) trimmed path component is exactly '..'\n (preDotState === 1 &&\n startDot === end - 1 &&\n startDot === startPart + 1)) {\n ret.base = ret.name = StringPrototypeSlice(path, start, end);\n } else {\n ret.name = StringPrototypeSlice(path, start, startDot);\n ret.base = StringPrototypeSlice(path, start, end);\n ret.ext = StringPrototypeSlice(path, startDot, end);\n }\n }\n\n if (startPart > 0)\n ret.dir = StringPrototypeSlice(path, 0, startPart - 1);\n else if (isAbsolute)\n ret.dir = '/';\n\n return ret;\n },\n\n matchesGlob(path, pattern) {\n return glob(path, pattern, false);\n },\n\n sep: '/',\n delimiter: ':',\n win32: null,\n posix: null,\n};\n\nposix.win32 = win32.win32 = win32;\nposix.posix = win32.posix = posix;\n\n// Legacy internal API, docs-only deprecated: DEP0080\nwin32._makeLong = win32.toNamespacedPath;\nposix._makeLong = posix.toNamespacedPath;\n\nmodule.exports = isWindows ? win32 : posix;\n";
@@ -7158,7 +7130,7 @@ class NativeStreamDriver {
7158
7130
  if (failures.length) throw new AggregateError(failures, "Native stream shutdown callbacks failed.");
7159
7131
  }
7160
7132
  }
7161
- function ownedBytes$1(view) {
7133
+ function ownedBytes(view) {
7162
7134
  const copy2 = new Uint8Array(view.byteLength);
7163
7135
  copy2.set(new Uint8Array(view.buffer, view.byteOffset, view.byteLength));
7164
7136
  return copy2;
@@ -7506,7 +7478,7 @@ class LibuvStreamWrap {
7506
7478
  const peer = this.peer;
7507
7479
  if (!peer || peer.closed) return 0;
7508
7480
  if (length === 0) return 0;
7509
- peer.receive(ownedBytes$1(buffer2), handle);
7481
+ peer.receive(ownedBytes(buffer2), handle);
7510
7482
  return 0;
7511
7483
  }
7512
7484
  /**
@@ -21951,11 +21923,11 @@ function requireAvailableTypedArrays() {
21951
21923
  if (hasRequiredAvailableTypedArrays) return availableTypedArrays;
21952
21924
  hasRequiredAvailableTypedArrays = 1;
21953
21925
  var possibleNames = requirePossibleTypedArrayNames();
21954
- var g = typeof globalThis === "undefined" ? globalThis : globalThis;
21926
+ var g2 = typeof globalThis === "undefined" ? globalThis : globalThis;
21955
21927
  availableTypedArrays = function availableTypedArrays2() {
21956
21928
  var out = [];
21957
21929
  for (var i2 = 0; i2 < possibleNames.length; i2++) {
21958
- if (typeof g[possibleNames[i2]] === "function") {
21930
+ if (typeof g2[possibleNames[i2]] === "function") {
21959
21931
  out[out.length] = possibleNames[i2];
21960
21932
  }
21961
21933
  }
@@ -22150,7 +22122,7 @@ function requireWhichTypedArray() {
22150
22122
  var getProto2 = requireGetProto();
22151
22123
  var $toString = callBound2("Object.prototype.toString");
22152
22124
  var hasToStringTag = requireShams()();
22153
- var g = typeof globalThis === "undefined" ? globalThis : globalThis;
22125
+ var g2 = typeof globalThis === "undefined" ? globalThis : globalThis;
22154
22126
  var typedArrays = availableTypedArrays2();
22155
22127
  var $slice = callBound2("String.prototype.slice");
22156
22128
  var $indexOf2 = callBound2("Array.prototype.indexOf", true) || function indexOf(array, value) {
@@ -22164,7 +22136,7 @@ function requireWhichTypedArray() {
22164
22136
  var cache2 = { __proto__: null };
22165
22137
  if (hasToStringTag && gOPD2 && getProto2) {
22166
22138
  forEach2(typedArrays, function(typedArray) {
22167
- var arr = new g[typedArray]();
22139
+ var arr = new g2[typedArray]();
22168
22140
  if (Symbol.toStringTag in arr && getProto2) {
22169
22141
  var proto = getProto2(arr);
22170
22142
  var descriptor = gOPD2(proto, Symbol.toStringTag);
@@ -22183,7 +22155,7 @@ function requireWhichTypedArray() {
22183
22155
  });
22184
22156
  } else {
22185
22157
  forEach2(typedArrays, function(typedArray) {
22186
- var arr = new g[typedArray]();
22158
+ var arr = new g2[typedArray]();
22187
22159
  var fn = arr.slice || arr.set;
22188
22160
  if (fn) {
22189
22161
  var bound = (
@@ -22663,7 +22635,7 @@ Sha256$1.prototype._update = function(M) {
22663
22635
  var d = this._d | 0;
22664
22636
  var e = this._e | 0;
22665
22637
  var f = this._f | 0;
22666
- var g = this._g | 0;
22638
+ var g2 = this._g | 0;
22667
22639
  var h = this._h | 0;
22668
22640
  for (var i2 = 0; i2 < 16; ++i2) {
22669
22641
  w[i2] = M.readInt32BE(i2 * 4);
@@ -22672,10 +22644,10 @@ Sha256$1.prototype._update = function(M) {
22672
22644
  w[i2] = gamma1(w[i2 - 2]) + w[i2 - 7] + gamma0(w[i2 - 15]) + w[i2 - 16] | 0;
22673
22645
  }
22674
22646
  for (var j = 0; j < 64; ++j) {
22675
- var T1 = h + sigma1$1(e) + ch(e, f, g) + K$2[j] + w[j] | 0;
22647
+ var T1 = h + sigma1$1(e) + ch(e, f, g2) + K$2[j] + w[j] | 0;
22676
22648
  var T2 = sigma0$1(a) + maj$1(a, b, c) | 0;
22677
- h = g;
22678
- g = f;
22649
+ h = g2;
22650
+ g2 = f;
22679
22651
  f = e;
22680
22652
  e = d + T1 | 0;
22681
22653
  d = c;
@@ -22689,7 +22661,7 @@ Sha256$1.prototype._update = function(M) {
22689
22661
  this._d = d + this._d | 0;
22690
22662
  this._e = e + this._e | 0;
22691
22663
  this._f = f + this._f | 0;
22692
- this._g = g + this._g | 0;
22664
+ this._g = g2 + this._g | 0;
22693
22665
  this._h = h + this._h | 0;
22694
22666
  };
22695
22667
  Sha256$1.prototype._hash = function() {
@@ -23390,21 +23362,21 @@ class _MD5 extends HashMD {
23390
23362
  MD5_W[i2] = view.getUint32(offset2, true);
23391
23363
  let { A, B, C, D } = this;
23392
23364
  for (let i2 = 0; i2 < 64; i2++) {
23393
- let F, g;
23365
+ let F, g2;
23394
23366
  if (i2 < 16) {
23395
23367
  F = Chi(B, C, D);
23396
- g = i2;
23368
+ g2 = i2;
23397
23369
  } else if (i2 < 32) {
23398
23370
  F = Chi(D, B, C);
23399
- g = (5 * i2 + 1) % 16;
23371
+ g2 = (5 * i2 + 1) % 16;
23400
23372
  } else if (i2 < 48) {
23401
23373
  F = B ^ C ^ D;
23402
- g = (3 * i2 + 5) % 16;
23374
+ g2 = (3 * i2 + 5) % 16;
23403
23375
  } else {
23404
23376
  F = C ^ (B | ~D);
23405
- g = 7 * i2 % 16;
23377
+ g2 = 7 * i2 % 16;
23406
23378
  }
23407
- F = F + A + K[i2] + MD5_W[g];
23379
+ F = F + A + K[i2] + MD5_W[g2];
23408
23380
  A = D;
23409
23381
  D = C;
23410
23382
  C = B;
@@ -29909,12 +29881,12 @@ let Worker$1 = class Worker3 extends EventEmitter {
29909
29881
  return Promise.resolve({});
29910
29882
  }
29911
29883
  };
29912
- let MessageChannel$1 = class MessageChannel2 {
29884
+ class MessageChannel {
29913
29885
  constructor() {
29914
29886
  __publicField(this, "port1", new MessagePort());
29915
29887
  __publicField(this, "port2", new MessagePort());
29916
29888
  }
29917
- };
29889
+ }
29918
29890
  class MessagePort extends EventEmitter {
29919
29891
  postMessage(value, transferList) {
29920
29892
  }
@@ -29969,7 +29941,7 @@ const worker_threads = {
29969
29941
  workerData,
29970
29942
  threadId,
29971
29943
  Worker: Worker$1,
29972
- MessageChannel: MessageChannel$1,
29944
+ MessageChannel,
29973
29945
  MessagePort,
29974
29946
  BroadcastChannel: BroadcastChannel$1,
29975
29947
  moveMessagePortToContext,
@@ -29984,7 +29956,7 @@ const worker_threads = {
29984
29956
  const workerThreadsShim = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
29985
29957
  __proto__: null,
29986
29958
  BroadcastChannel: BroadcastChannel$1,
29987
- MessageChannel: MessageChannel$1,
29959
+ MessageChannel,
29988
29960
  MessagePort,
29989
29961
  SHARE_ENV,
29990
29962
  Worker: Worker$1,
@@ -40148,7 +40120,7 @@ class WorkerRuntime {
40148
40120
  this.worker = new Worker(
40149
40121
  new URL(
40150
40122
  /* @vite-ignore */
40151
- "/assets/runtime-worker-VIeZbbDr.js",
40123
+ "/assets/runtime-worker-DPvtXRd8.js",
40152
40124
  import.meta.url
40153
40125
  ),
40154
40126
  { type: "module" }
@@ -41814,14 +41786,6 @@ function __upgradeOverLoopback(port, method, url2, headers) {
41814
41786
  });
41815
41787
  }
41816
41788
  const _encoder = new TextEncoder();
41817
- const FLOW_MAX_REQUEST_BYTES = 64 * 1024 * 1024;
41818
- const FLOW_MAX_CHUNK_BYTES = 65536;
41819
- const FLOW_QUEUED_CHUNKS = 4;
41820
- function ownedBytes(view) {
41821
- const copy2 = new Uint8Array(view.byteLength);
41822
- copy2.set(new Uint8Array(view.buffer, view.byteOffset, view.byteLength));
41823
- return copy2;
41824
- }
41825
41789
  function guestListeningServer(port, address) {
41826
41790
  const hostname2 = address;
41827
41791
  return {
@@ -41831,7 +41795,10 @@ function guestListeningServer(port, address) {
41831
41795
  address: hostname2,
41832
41796
  family: hostname2.includes(":") ? "IPv6" : "IPv4"
41833
41797
  }),
41834
- handleRequest: (method, url2, headers, body) => __requestOverLoopback(port, method, url2, headers, typeof body === "string" ? Buffer$9.from(body) : body)
41798
+ handleRequest: (method, url2, headers, body) => (
41799
+ // this engine's bridge hands its servers a Buffer (`bodyOf`)
41800
+ __requestOverLoopback(port, method, url2, headers, typeof body === "string" ? Buffer$9.from(body) : body)
41801
+ )
41835
41802
  };
41836
41803
  }
41837
41804
  const __substrateUpgradeSockets = /* @__PURE__ */ new Map();
@@ -42060,22 +42027,11 @@ function __substrateListenForUpgrades(bridge) {
42060
42027
  });
42061
42028
  return channel;
42062
42029
  }
42063
- const _ServerBridge = class _ServerBridge extends EventEmitter {
42030
+ class ServerBridge extends PortBridge {
42064
42031
  constructor(options = {}) {
42065
- super();
42066
- __publicField(this, "servers", /* @__PURE__ */ new Map());
42067
- __publicField(this, "baseUrl");
42068
- __publicField(this, "options");
42069
- __publicField(this, "messageChannel", null);
42032
+ super(options);
42070
42033
  /** The upgrade channel this bridge opened, held so it can be given back. */
42071
42034
  __publicField(this, "upgradeChannel", null);
42072
- __publicField(this, "serviceWorkerReady", false);
42073
- __publicField(this, "keepaliveInterval", null);
42074
- /**
42075
- * Give back everything this bridge opened: the upgrade channel and the
42076
- * service worker keepalive. A host that is done with a container calls it
42077
- * and has its process back; calling it twice is nothing.
42078
- */
42079
42035
  /**
42080
42036
  * Every port a guest starts listening on becomes a server this bridge can
42081
42037
  * answer for, and every port it stops listening on stops being one. The
@@ -42083,17 +42039,6 @@ const _ServerBridge = class _ServerBridge extends EventEmitter {
42083
42039
  * the engine's `http` is Node's own file and knows nothing of a page.
42084
42040
  */
42085
42041
  __publicField(this, "guestServers", /* @__PURE__ */ new WeakSet());
42086
- /** The server the service worker answers at the origin's root, the preview's; null for none. */
42087
- __publicField(this, "primaryPort", null);
42088
- __publicField(this, "ownDocuments");
42089
- /** Flow-controlled requests in flight: a pull is one chunk's credit, a cancel ends the upstream. */
42090
- __publicField(this, "controlledStreams", /* @__PURE__ */ new Map());
42091
- this.options = options;
42092
- if (typeof location !== "undefined") {
42093
- this.baseUrl = options.baseUrl || `${location.protocol}//${location.host}`;
42094
- } else {
42095
- this.baseUrl = options.baseUrl || "http://localhost";
42096
- }
42097
42042
  this.watchGuestPorts();
42098
42043
  this.upgradeChannel = __substrateListenForUpgrades();
42099
42044
  }
@@ -42123,507 +42068,23 @@ const _ServerBridge = class _ServerBridge extends EventEmitter {
42123
42068
  }
42124
42069
  this.upgradeChannel = null;
42125
42070
  }
42126
- if (this.keepaliveInterval !== null) {
42127
- clearInterval(this.keepaliveInterval);
42128
- this.keepaliveInterval = null;
42129
- }
42130
- }
42131
- /**
42132
- * Register a server on a port
42133
- */
42134
- registerServer(server, port, hostname2 = "0.0.0.0") {
42135
- this.servers.set(port, { server, port, hostname: hostname2 });
42136
- const url2 = this.getServerUrl(port);
42137
- this.emit("server-ready", port, url2);
42138
- if (this.options.onServerReady) {
42139
- this.options.onServerReady(port, url2);
42140
- }
42141
- this.notifyServiceWorker("server-registered", { port, hostname: hostname2, primary: port === this.primaryPort });
42142
- }
42143
- /**
42144
- * Unregister a server
42145
- */
42146
- unregisterServer(port) {
42147
- this.servers.delete(port);
42148
- if (this.primaryPort === port) this.primaryPort = null;
42149
- this.notifyServiceWorker("server-unregistered", { port });
42150
- }
42151
- /**
42152
- * Names the server the service worker serves at the origin's root, as an
42153
- * app is served at its own origin's root: its documents read their routes
42154
- * from `location.pathname`, which under /__virtual__/<port>/ is not the
42155
- * path they expect. Told to the worker now and again whenever the worker
42156
- * is (re)initialized, since a worker that restarted remembers nothing.
42157
- */
42158
- setPrimaryPort(port) {
42159
- const previous = this.primaryPort;
42160
- this.primaryPort = port;
42161
- if (previous !== null && previous !== port) {
42162
- const entry = this.servers.get(previous);
42163
- if (entry) this.notifyServiceWorker("server-registered", { port: previous, hostname: entry.hostname, primary: false });
42164
- }
42165
- if (port !== null) {
42166
- const entry = this.servers.get(port);
42167
- this.notifyServiceWorker("server-registered", { port, hostname: (entry == null ? void 0 : entry.hostname) ?? "0.0.0.0", primary: true });
42168
- }
42169
- }
42170
- /** Every registration the worker should hold, sent again to a worker that was (re)initialized. */
42171
- announceServers() {
42172
- if (this.ownDocuments) this.notifyServiceWorker("own-documents", { paths: this.ownDocuments });
42173
- for (const [port, entry] of this.servers) {
42174
- this.notifyServiceWorker("server-registered", { port, hostname: entry.hostname, primary: port === this.primaryPort });
42175
- }
42176
- }
42177
- /**
42178
- * Get server URL for a port
42179
- */
42180
- getServerUrl(port) {
42181
- return `${this.baseUrl}/__virtual__/${port}`;
42182
- }
42183
- /**
42184
- * Get all registered server ports
42185
- */
42186
- getServerPorts() {
42187
- return [...this.servers.keys()];
42188
- }
42189
- /**
42190
- * Handle an incoming request from Service Worker
42191
- */
42192
- async handleRequest(port, method, url2, headers, body) {
42193
- const virtualServer = this.servers.get(port);
42194
- if (!virtualServer) {
42195
- return {
42196
- statusCode: 503,
42197
- statusMessage: "Service Unavailable",
42198
- headers: { "Content-Type": "text/plain" },
42199
- body: ownedBytes(Buffer$9.from(`No server listening on port ${port}`))
42200
- };
42201
- }
42202
- try {
42203
- const bodyBuffer = body ? Buffer$9.from(new Uint8Array(body)) : void 0;
42204
- const named = Object.keys(headers).some((name) => name.toLowerCase() === "host");
42205
- const authority = `${virtualServer.hostname && virtualServer.hostname !== "0.0.0.0" && virtualServer.hostname !== "::" ? virtualServer.hostname : "127.0.0.1"}:${port}`;
42206
- const withHost = named ? headers : { ...headers, host: authority };
42207
- if (virtualServer.server) return await virtualServer.server.handleRequest(method, url2, withHost, bodyBuffer);
42208
- return await __requestOverLoopback(port, method, url2, withHost, bodyBuffer);
42209
- } catch (error) {
42210
- const message = error instanceof Error ? error.message : "Internal Server Error";
42211
- return {
42212
- statusCode: 500,
42213
- statusMessage: "Internal Server Error",
42214
- headers: { "Content-Type": "text/plain" },
42215
- body: ownedBytes(Buffer$9.from(message))
42216
- };
42217
- }
42218
- }
42219
- /**
42220
- * Initialize Service Worker communication
42221
- * @param options - Configuration options for the service worker
42222
- * @param options.swUrl - Custom URL path to the service worker file (default: '/__sw__.js')
42223
- */
42224
- async initServiceWorker(options) {
42225
- if (!("serviceWorker" in navigator)) {
42226
- throw new Error("Service Workers not supported");
42227
- }
42228
- const swUrl = (options == null ? void 0 : options.swUrl) ?? "/__sw__.js";
42229
- const controllerReady = navigator.serviceWorker.controller ? Promise.resolve() : new Promise((resolve2) => {
42230
- navigator.serviceWorker.addEventListener("controllerchange", () => resolve2(), { once: true });
42231
- });
42232
- const registration = await navigator.serviceWorker.register(swUrl, {
42233
- scope: "/"
42234
- });
42235
- const sw = registration.active || registration.waiting || registration.installing;
42236
- if (!sw) {
42237
- throw new Error("Service Worker registration failed");
42238
- }
42239
- await new Promise((resolve2) => {
42240
- if (sw.state === "activated") {
42241
- resolve2();
42242
- } else {
42243
- const handler = () => {
42244
- if (sw.state === "activated") {
42245
- sw.removeEventListener("statechange", handler);
42246
- resolve2();
42247
- }
42248
- };
42249
- sw.addEventListener("statechange", handler);
42250
- }
42251
- });
42252
- this.messageChannel = new MessageChannel();
42253
- this.messageChannel.port1.onmessage = this.handleServiceWorkerMessage.bind(this);
42254
- this.ownDocuments = options == null ? void 0 : options.ownDocuments;
42255
- sw.postMessage({ type: "init", port: this.messageChannel.port2, data: { ownDocuments: this.ownDocuments ?? [] } }, [
42256
- this.messageChannel.port2
42257
- ]);
42258
- await controllerReady;
42259
- const reinit = () => {
42260
- if (navigator.serviceWorker.controller) {
42261
- for (const stream of [...this.controlledStreams.values()]) stream.cancel();
42262
- this.messageChannel = new MessageChannel();
42263
- this.messageChannel.port1.onmessage = this.handleServiceWorkerMessage.bind(this);
42264
- navigator.serviceWorker.controller.postMessage(
42265
- { type: "init", port: this.messageChannel.port2, data: { ownDocuments: this.ownDocuments ?? [] } },
42266
- [this.messageChannel.port2]
42267
- );
42268
- this.announceServers();
42269
- }
42270
- };
42271
- navigator.serviceWorker.addEventListener("controllerchange", reinit);
42272
- navigator.serviceWorker.addEventListener("message", (event) => {
42273
- var _a2;
42274
- if (((_a2 = event.data) == null ? void 0 : _a2.type) === "sw-needs-init") {
42275
- reinit();
42276
- }
42277
- });
42278
- this.keepaliveInterval = setInterval(() => {
42279
- var _a2;
42280
- (_a2 = this.messageChannel) == null ? void 0 : _a2.port1.postMessage({ type: "keepalive" });
42281
- }, 2e4);
42282
- this.serviceWorkerReady = true;
42283
- this.announceServers();
42284
- this.emit("sw-ready");
42285
- }
42286
- /**
42287
- * Handle messages from Service Worker
42288
- */
42289
- async handleServiceWorkerMessage(event) {
42290
- var _a2, _b2, _c2;
42291
- const { type: type2, id, data: data2 } = event.data;
42292
- _ServerBridge.DEBUG && console.log("[ServerBridge] SW message:", type2, id, data2 == null ? void 0 : data2.url);
42293
- if (type2 === "stream-pull" || type2 === "stream-cancel") {
42294
- const stream = this.controlledStreams.get(id);
42295
- if (type2 === "stream-pull") stream == null ? void 0 : stream.pull();
42296
- else stream == null ? void 0 : stream.cancel();
42297
- return;
42298
- }
42299
- if (type2 === "request" && (data2 == null ? void 0 : data2.flowControl) === 1) {
42300
- const { port, method, url: url2, headers, body } = data2;
42301
- await this.controlledStream(id, port, method, url2, headers, body);
42302
- return;
42303
- }
42304
- if (type2 === "request") {
42305
- const { port, method, url: url2, headers, body, streaming } = data2;
42306
- _ServerBridge.DEBUG && console.log("[ServerBridge] Handling request:", port, method, url2, "streaming:", streaming);
42307
- if (streaming) {
42308
- _ServerBridge.DEBUG && console.log("[ServerBridge] 🔴 Will use streaming handler");
42309
- }
42310
- try {
42311
- if (streaming) {
42312
- await this.streamToServiceWorker(id, port, method, url2, headers, body);
42313
- } else {
42314
- const response = await this.handleRequest(port, method, url2, headers, body);
42315
- _ServerBridge.DEBUG && console.log("[ServerBridge] Response:", response.statusCode, "body length:", (_a2 = response.body) == null ? void 0 : _a2.length);
42316
- let bodyBase64 = "";
42317
- if (response.body && response.body.length > 0) {
42318
- const bytes2 = response.body instanceof Uint8Array ? response.body : new Uint8Array(0);
42319
- bodyBase64 = uint8ToBase64(bytes2);
42320
- }
42321
- _ServerBridge.DEBUG && console.log("[ServerBridge] Sending response to SW, body base64 length:", bodyBase64.length);
42322
- (_b2 = this.messageChannel) == null ? void 0 : _b2.port1.postMessage({
42323
- type: "response",
42324
- id,
42325
- data: {
42326
- statusCode: response.statusCode,
42327
- statusMessage: response.statusMessage,
42328
- headers: response.headers,
42329
- bodyBase64
42330
- }
42331
- });
42332
- }
42333
- } catch (error) {
42334
- (_c2 = this.messageChannel) == null ? void 0 : _c2.port1.postMessage({
42335
- type: "response",
42336
- id,
42337
- error: error instanceof Error ? error.message : "Unknown error"
42338
- });
42339
- }
42340
- }
42071
+ super.close();
42341
42072
  }
42342
- /**
42343
- * Handle a streaming request - sends chunks as they arrive
42344
- */
42345
- /**
42346
- * A page-side request streamed to the caller as it arrives, the door a host
42347
- * reads a guest's server through when it wants chunks rather than a body:
42348
- * a guest's own server is reached over the loopback as any client reaches
42349
- * it; a server the host registered answers through its own streaming
42350
- * method where it has one, else its buffered answer is delivered whole.
42351
- */
42352
- async handleStreamingRequest(port, method, url2, headers, body, callbacks, flow) {
42353
- const virtualServer = this.servers.get(port);
42354
- if (!virtualServer) return false;
42355
- const bodyBuffer = body ? Buffer$9.from(new Uint8Array(body)) : void 0;
42356
- if (virtualServer.server === null || this.guestServers.has(virtualServer.server)) {
42357
- const named = Object.keys(headers).some((name) => name.toLowerCase() === "host");
42358
- const authority = `${virtualServer.hostname && virtualServer.hostname !== "0.0.0.0" && virtualServer.hostname !== "::" ? virtualServer.hostname : "127.0.0.1"}:${port}`;
42359
- await __streamOverLoopback(
42360
- port,
42361
- method,
42362
- url2,
42363
- named ? headers : { ...headers, host: authority },
42364
- bodyBuffer,
42365
- (statusCode, statusMessage, respHeaders) => callbacks.start(statusCode, statusMessage, respHeaders),
42366
- (chunk) => callbacks.chunk(ownedBytes(chunk)),
42367
- () => callbacks.end(),
42368
- flow
42369
- );
42370
- return true;
42371
- }
42372
- const server = virtualServer.server;
42373
- if (typeof server.handleStreamingRequest === "function") {
42374
- await server.handleStreamingRequest(
42375
- method,
42376
- url2,
42377
- headers,
42378
- bodyBuffer,
42379
- (statusCode, statusMessage, respHeaders) => callbacks.start(statusCode, statusMessage, respHeaders),
42380
- (chunk) => callbacks.chunk(typeof chunk === "string" ? _encoder.encode(chunk) : ownedBytes(chunk)),
42381
- () => callbacks.end(),
42382
- flow
42383
- );
42384
- return true;
42385
- }
42386
- const response = await this.handleRequest(port, method, url2, headers, body);
42387
- callbacks.start(response.statusCode, response.statusMessage ?? "", response.headers);
42388
- if (response.body) {
42389
- const body2 = typeof response.body === "string" ? _encoder.encode(response.body) : response.body;
42390
- callbacks.chunk(ownedBytes(body2));
42391
- }
42392
- callbacks.end();
42393
- return true;
42073
+ /** A guest's listener (the old null sentinel, now a request adapter) is answered over the loopback. */
42074
+ isGuest(entry) {
42075
+ return entry.server === null || this.guestServers.has(entry.server);
42394
42076
  }
42395
- async streamToServiceWorker(id, port, method, url2, headers, body) {
42396
- var _a2, _b2, _c2, _d2, _e2;
42397
- const virtualServer = this.servers.get(port);
42398
- if (!virtualServer) {
42399
- (_a2 = this.messageChannel) == null ? void 0 : _a2.port1.postMessage({
42400
- type: "stream-start",
42401
- id,
42402
- data: { statusCode: 503, statusMessage: "Service Unavailable", headers: {} }
42403
- });
42404
- (_b2 = this.messageChannel) == null ? void 0 : _b2.port1.postMessage({ type: "stream-end", id });
42405
- return;
42406
- }
42407
- if (virtualServer.server === null || this.guestServers.has(virtualServer.server)) {
42408
- const bodyBuffer = body ? Buffer$9.from(new Uint8Array(body)) : void 0;
42409
- const named = Object.keys(headers).some((name) => name.toLowerCase() === "host");
42410
- const authority = `${virtualServer.hostname && virtualServer.hostname !== "0.0.0.0" && virtualServer.hostname !== "::" ? virtualServer.hostname : "127.0.0.1"}:${port}`;
42411
- await __streamOverLoopback(
42412
- port,
42413
- method,
42414
- url2,
42415
- named ? headers : { ...headers, host: authority },
42416
- bodyBuffer,
42417
- (statusCode, statusMessage, respHeaders) => {
42418
- var _a3;
42419
- (_a3 = this.messageChannel) == null ? void 0 : _a3.port1.postMessage({ type: "stream-start", id, data: { statusCode, statusMessage, headers: respHeaders } });
42420
- },
42421
- (chunk) => {
42422
- var _a3;
42423
- const copy2 = ownedBytes(chunk);
42424
- (_a3 = this.messageChannel) == null ? void 0 : _a3.port1.postMessage({ type: "stream-chunk", id, data: copy2.buffer }, [copy2.buffer]);
42425
- },
42426
- () => {
42427
- var _a3;
42428
- (_a3 = this.messageChannel) == null ? void 0 : _a3.port1.postMessage({ type: "stream-end", id });
42429
- }
42430
- );
42431
- return;
42432
- }
42433
- const server = virtualServer.server;
42434
- if (typeof server.handleStreamingRequest === "function") {
42435
- _ServerBridge.DEBUG && console.log("[ServerBridge] 🟢 Server has streaming support, calling handleStreamingRequest");
42436
- const bodyBuffer = body ? Buffer$9.from(new Uint8Array(body)) : void 0;
42437
- await server.handleStreamingRequest(
42438
- method,
42439
- url2,
42440
- headers,
42441
- bodyBuffer,
42442
- // onStart - called with headers
42443
- (statusCode, statusMessage, respHeaders) => {
42444
- var _a3;
42445
- _ServerBridge.DEBUG && console.log("[ServerBridge] 🟢 onStart called, sending stream-start");
42446
- (_a3 = this.messageChannel) == null ? void 0 : _a3.port1.postMessage({
42447
- type: "stream-start",
42448
- id,
42449
- data: { statusCode, statusMessage, headers: respHeaders }
42450
- });
42451
- },
42452
- // onChunk - called for each chunk
42453
- (chunk) => {
42454
- var _a3;
42455
- const bytes2 = typeof chunk === "string" ? _encoder.encode(chunk) : chunk;
42456
- const chunkBase64 = uint8ToBase64(bytes2);
42457
- _ServerBridge.DEBUG && console.log("[ServerBridge] 🟡 onChunk called, sending stream-chunk, size:", chunkBase64.length);
42458
- (_a3 = this.messageChannel) == null ? void 0 : _a3.port1.postMessage({
42459
- type: "stream-chunk",
42460
- id,
42461
- data: { chunkBase64 }
42462
- });
42463
- },
42464
- // onEnd - called when response is complete
42465
- () => {
42466
- var _a3;
42467
- _ServerBridge.DEBUG && console.log("[ServerBridge] 🟢 onEnd called, sending stream-end");
42468
- (_a3 = this.messageChannel) == null ? void 0 : _a3.port1.postMessage({ type: "stream-end", id });
42469
- }
42470
- );
42471
- } else {
42472
- const bodyBuffer = body ? Buffer$9.from(new Uint8Array(body)) : void 0;
42473
- const response = await virtualServer.server.handleRequest(method, url2, headers, bodyBuffer);
42474
- (_c2 = this.messageChannel) == null ? void 0 : _c2.port1.postMessage({
42475
- type: "stream-start",
42476
- id,
42477
- data: {
42478
- statusCode: response.statusCode,
42479
- statusMessage: response.statusMessage,
42480
- headers: response.headers
42481
- }
42482
- });
42483
- if (response.body && response.body.length > 0) {
42484
- const bytes2 = response.body instanceof Uint8Array ? response.body : new Uint8Array(0);
42485
- (_d2 = this.messageChannel) == null ? void 0 : _d2.port1.postMessage({
42486
- type: "stream-chunk",
42487
- id,
42488
- data: { chunkBase64: uint8ToBase64(bytes2) }
42489
- });
42490
- }
42491
- (_e2 = this.messageChannel) == null ? void 0 : _e2.port1.postMessage({ type: "stream-end", id });
42492
- }
42077
+ requestGuest(port, method, url2, headers, body) {
42078
+ return __requestOverLoopback(port, method, url2, headers, body);
42493
42079
  }
42494
- /**
42495
- * Send message to Service Worker
42496
- */
42497
- notifyServiceWorker(type2, data2) {
42498
- if (this.serviceWorkerReady && this.messageChannel) {
42499
- const flow = type2 === "server-registered" ? { flowControl: 1, maxRequestBytes: FLOW_MAX_REQUEST_BYTES, maxChunkBytes: FLOW_MAX_CHUNK_BYTES } : {};
42500
- this.messageChannel.port1.postMessage({ type: type2, data: { ...data2, ...flow } });
42501
- }
42502
- }
42503
- /**
42504
- * A request the worker sent under flow control: the response starts with
42505
- * its head, then goes one chunk (at most FLOW_MAX_CHUNK_BYTES) for each
42506
- * `stream-pull`, and ends with `stream-end` once the server finished and
42507
- * every chunk went out. The upstream connection is paused while chunks wait
42508
- * for credit, so a slow reader holds the server back; `stream-cancel` ends it.
42509
- */
42510
- async controlledStream(id, port, method, url2, headers, body) {
42511
- const channel = this.messageChannel;
42512
- const post = (type2, data2) => {
42513
- channel == null ? void 0 : channel.port1.postMessage({ type: type2, id, ...data2 === void 0 ? {} : { data: data2 } });
42514
- };
42515
- const queue = [];
42516
- const abort = new AbortController();
42517
- let credits = 0;
42518
- let upstreamEnded = false;
42519
- let finished = false;
42520
- let paused = false;
42521
- let pause = () => void 0;
42522
- let resume = () => void 0;
42523
- const finish = () => {
42524
- finished = true;
42525
- this.controlledStreams.delete(id);
42526
- };
42527
- const flush2 = () => {
42528
- if (finished) return;
42529
- while (credits > 0 && queue.length > 0) {
42530
- credits -= 1;
42531
- post("stream-chunk", { chunkBase64: uint8ToBase64(queue.shift()) });
42532
- }
42533
- if (upstreamEnded && queue.length === 0) {
42534
- post("stream-end");
42535
- finish();
42536
- return;
42537
- }
42538
- if (queue.length >= FLOW_QUEUED_CHUNKS && !paused) {
42539
- paused = true;
42540
- pause();
42541
- } else if (queue.length < FLOW_QUEUED_CHUNKS && paused) {
42542
- paused = false;
42543
- resume();
42544
- }
42545
- };
42546
- this.controlledStreams.set(id, {
42547
- pull: () => {
42548
- credits += 1;
42549
- flush2();
42550
- },
42551
- cancel: () => {
42552
- if (finished) return;
42553
- finish();
42554
- queue.length = 0;
42555
- abort.abort();
42556
- }
42557
- });
42558
- try {
42559
- const answered = await this.handleStreamingRequest(port, method, url2, headers, body, {
42560
- start: (statusCode, statusMessage, respHeaders) => post("stream-start", { statusCode, statusMessage, headers: respHeaders }),
42561
- chunk: (chunk) => {
42562
- if (finished) return;
42563
- for (let at2 = 0; at2 < chunk.byteLength; at2 += FLOW_MAX_CHUNK_BYTES) queue.push(chunk.slice(at2, at2 + FLOW_MAX_CHUNK_BYTES));
42564
- flush2();
42565
- },
42566
- end: () => {
42567
- upstreamEnded = true;
42568
- flush2();
42569
- }
42570
- }, { signal: abort.signal, control: (p, r) => {
42571
- pause = p;
42572
- resume = r;
42573
- } });
42574
- if (!answered) {
42575
- post("stream-start", { statusCode: 503, statusMessage: "Service Unavailable", headers: {} });
42576
- post("stream-end");
42577
- finish();
42578
- }
42579
- } catch (error) {
42580
- if (!finished) {
42581
- post("stream-error", { message: error instanceof Error ? error.message : String(error) });
42582
- finish();
42583
- }
42584
- }
42080
+ streamGuest(port, method, url2, headers, body, onStart, onChunk, onEnd, flow) {
42081
+ return __streamOverLoopback(port, method, url2, headers, body, onStart, onChunk, onEnd, flow);
42585
42082
  }
42586
- /**
42587
- * Create a mock request handler for testing without Service Worker
42588
- */
42589
- createFetchHandler() {
42590
- return async (request) => {
42591
- const url2 = new URL(request.url);
42592
- const match = url2.pathname.match(/^\/__virtual__\/(\d+)(\/.*)?$/);
42593
- if (!match) {
42594
- throw new Error("Not a virtual server request");
42595
- }
42596
- const port = parseInt(match[1], 10);
42597
- const path2 = match[2] || "/";
42598
- const headers = {};
42599
- request.headers.forEach((value, key) => {
42600
- headers[key] = value;
42601
- });
42602
- let body;
42603
- if (request.method !== "GET" && request.method !== "HEAD") {
42604
- body = await request.arrayBuffer();
42605
- }
42606
- const response = await this.handleRequest(
42607
- port,
42608
- request.method,
42609
- path2 + url2.search,
42610
- headers,
42611
- body
42612
- );
42613
- const answerHeaders = new Headers();
42614
- for (const [name, value] of Object.entries(response.headers)) {
42615
- for (const each of Array.isArray(value) ? value : [value]) answerHeaders.append(name, each);
42616
- }
42617
- return new Response(response.body, {
42618
- status: response.statusCode,
42619
- statusText: response.statusMessage ?? "",
42620
- headers: answerHeaders
42621
- });
42622
- };
42083
+ /** A server of this engine reads a request's body as Node's Buffer. */
42084
+ bodyOf(bytes2) {
42085
+ return Buffer$9.from(bytes2);
42623
42086
  }
42624
- };
42625
- __publicField(_ServerBridge, "DEBUG", false);
42626
- let ServerBridge = _ServerBridge;
42087
+ }
42627
42088
  let globalBridge = null;
42628
42089
  function getServerBridge(options) {
42629
42090
  if (!globalBridge) {
@@ -43067,6 +42528,7 @@ export {
43067
42528
  NativeStreamScope,
43068
42529
  PREPARED_MODULES_DIR,
43069
42530
  PackageManager,
42531
+ PortBridge,
43070
42532
  Runtime,
43071
42533
  ServerBridge,
43072
42534
  VirtualFS,
@@ -43082,6 +42544,7 @@ export {
43082
42544
  esbuildShim as esbuild,
43083
42545
  eventsModule as events,
43084
42546
  execute,
42547
+ g as getPortBridge,
43085
42548
  getServerBridge,
43086
42549
  guestRealmInstalled,
43087
42550
  httpModule as http,