/** * `velar/env` — the canonical Node environment boundary. The process.env * object and every JavaScript operation used to validate and read it are * captured while the official module initializes, so later application-Realm * replacement cannot redirect environment reads or execute accessors. */ export declare const VELAR_NODE_ENV_RUNTIME = "const __velarEnvNativeError = globalThis.Error;\nconst __velarEnvNativeObject = globalThis.Object;\nconst __velarEnvNativeReflect = globalThis.Reflect;\nconst __velarEnvNativeRegExp = globalThis.RegExp;\nconst __velarEnvNativeTypeError = globalThis.TypeError;\nconst __velarEnvOwnDescriptor = __velarEnvNativeObject.getOwnPropertyDescriptor;\nconst __velarEnvApply = __velarEnvNativeReflect.apply;\nfunction __velarEnvDataOperation(target, name) {\n const descriptor = __velarEnvOwnDescriptor(target, name);\n if (!descriptor || !(\"value\" in descriptor) || typeof descriptor.value !== \"function\") {\n throw new __velarEnvNativeError(\"VelarScript environment host operation '\" + name + \"' is unavailable\");\n }\n return descriptor.value;\n}\nconst __velarEnvRegExpTest = __velarEnvDataOperation(__velarEnvNativeRegExp.prototype, \"test\");\nconst __velarEnvEnvironment = globalThis.process.env;\nconst __velarEnvNamePattern = /^[A-Za-z_][A-Za-z0-9_]*$/u;\n\nfunction __velarEnvName(value) {\n if (typeof value !== \"string\"\n || value.length > 256\n || !__velarEnvApply(__velarEnvRegExpTest, __velarEnvNamePattern, [value])) {\n throw new __velarEnvNativeTypeError(\"Environment variable names use ASCII letters, digits, and underscores, starting with a letter or underscore\");\n }\n return value;\n}\n\nfunction __velarEnvValue(name) {\n const descriptor = __velarEnvOwnDescriptor(__velarEnvEnvironment, name);\n if (!descriptor) return null;\n if (!(\"value\" in descriptor) || typeof descriptor.value !== \"string\") {\n throw new __velarEnvNativeTypeError(\"Environment variable values must be host-owned text\");\n }\n return descriptor.value;\n}\n\nexport function get(name) {\n return __velarEnvValue(__velarEnvName(name));\n}\n\nexport function require(name) {\n name = __velarEnvName(name);\n const value = __velarEnvValue(name);\n if (value === null) throw new __velarEnvNativeError(\"VelarScript environment variable '\" + name + \"' is required\");\n return value;\n}\n"; /** * The canonical application-facing filesystem boundary. Validation, UTF-8 and * immutable Velar values stay in this Realm; all Node fs effects run through * the private isolated velar/node-host-v1 runtime dependency. */ export declare const VELAR_NODE_FILESYSTEM_RUNTIME = "import { __velarNodeHostInvoke } from \"velar/node-host-v1\";\nimport { Bytes as __velarFsBytesType } from \"velar/binary\";\n\nconst __velarFsNativeArray = globalThis.Array;\nconst __velarFsNativeError = globalThis.Error;\nconst __velarFsNativeNumber = globalThis.Number;\nconst __velarFsNativeObject = globalThis.Object;\nconst __velarFsNativeRangeError = globalThis.RangeError;\nconst __velarFsNativeReflect = globalThis.Reflect;\nconst __velarFsNativeString = globalThis.String;\nconst __velarFsNativeTextDecoder = globalThis.TextDecoder;\nconst __velarFsNativeTextEncoder = globalThis.TextEncoder;\nconst __velarFsNativeTypeError = globalThis.TypeError;\nconst __velarFsNativeUint8Array = globalThis.Uint8Array;\nconst __velarFsOwnDescriptor = __velarFsNativeObject.getOwnPropertyDescriptor;\nconst __velarFsApply = __velarFsNativeReflect.apply;\nfunction __velarFsDataOperation(target, name) {\n const descriptor = __velarFsOwnDescriptor(target, name);\n if (!descriptor || !(\"value\" in descriptor) || typeof descriptor.value !== \"function\") {\n throw new __velarFsNativeError(\"VelarScript filesystem host operation '\" + name + \"' is unavailable\");\n }\n return descriptor.value;\n}\nconst __velarFsArraySort = __velarFsDataOperation(__velarFsNativeArray.prototype, \"sort\");\nconst __velarFsArrayIsArray = __velarFsDataOperation(__velarFsNativeArray, \"isArray\");\nconst __velarFsNumberIsFinite = __velarFsDataOperation(__velarFsNativeNumber, \"isFinite\");\nconst __velarFsNumberIsSafeInteger = __velarFsDataOperation(__velarFsNativeNumber, \"isSafeInteger\");\nconst __velarFsObjectCreate = __velarFsDataOperation(__velarFsNativeObject, \"create\");\nconst __velarFsObjectDefineProperty = __velarFsDataOperation(__velarFsNativeObject, \"defineProperty\");\nconst __velarFsObjectFreeze = __velarFsDataOperation(__velarFsNativeObject, \"freeze\");\nconst __velarFsObjectGetPrototypeOf = __velarFsDataOperation(__velarFsNativeObject, \"getPrototypeOf\");\nconst __velarFsObjectKeys = __velarFsDataOperation(__velarFsNativeObject, \"keys\");\nconst __velarFsStringIncludes = __velarFsDataOperation(__velarFsNativeString.prototype, \"includes\");\nconst __velarFsTextDecoderDecode = __velarFsDataOperation(__velarFsNativeTextDecoder.prototype, \"decode\");\nconst __velarFsTextEncoderEncode = __velarFsDataOperation(__velarFsNativeTextEncoder.prototype, \"encode\");\nconst __velarFsTypedArrayPrototype = __velarFsApply(__velarFsObjectGetPrototypeOf, __velarFsNativeObject, [__velarFsNativeUint8Array.prototype]);\nconst __velarFsTypedArrayByteLength = __velarFsOwnDescriptor(__velarFsTypedArrayPrototype, \"byteLength\")?.get;\nif (typeof __velarFsTypedArrayByteLength !== \"function\") throw new __velarFsNativeError(\"VelarScript filesystem byte length operation is unavailable\");\nconst __velarFsDecoder = new __velarFsNativeTextDecoder(\"utf-8\", {fatal: true, ignoreBOM: true});\nconst __velarFsEncoder = new __velarFsNativeTextEncoder();\nconst __velarFsMaxPathCodeUnits = 4096;\nconst __velarFsMaxFileBytes = 16 * 1024 * 1024;\nconst __velarFsMaxListItems = 100000;\nconst __velarFsMaxListCodeUnits = 2 * 1024 * 1024;\nconst __velarFsWatcherToken = Symbol(\"velar.fs.watcher\");\nconst __velarFsMaxWatchPaths = 4096;\n\nfunction __velarFsCall(operation, receiver, arguments_) {\n return __velarFsApply(operation, receiver, arguments_);\n}\n\nfunction __velarFsPath(value, operation) {\n if (typeof value !== \"string\" || value.length === 0) throw new __velarFsNativeTypeError(operation + \" requires a non-empty path string\");\n if (value.length > __velarFsMaxPathCodeUnits || __velarFsCall(__velarFsStringIncludes, value, [\"\\0\"])) {\n throw new __velarFsNativeRangeError(operation + \" path is outside the supported bounds\");\n }\n return value;\n}\n\nfunction __velarFsByteLimit(value, operation) {\n if (!__velarFsCall(__velarFsNumberIsSafeInteger, __velarFsNativeNumber, [value]) || value < 1 || value > __velarFsMaxFileBytes) {\n throw new __velarFsNativeRangeError(operation + \" maxBytes must be an integer from 1 through 16777216\");\n }\n return value;\n}\n\nfunction __velarFsByteLength(value) {\n return __velarFsCall(__velarFsTypedArrayByteLength, value, []);\n}\n\nfunction __velarFsEncode(value) {\n return __velarFsCall(__velarFsTextEncoderEncode, __velarFsEncoder, [value]);\n}\n\nfunction __velarFsBytes(value, operation) {\n const prototype = value && typeof value === \"object\"\n ? __velarFsCall(__velarFsObjectGetPrototypeOf, __velarFsNativeObject, [value])\n : null;\n if (prototype !== __velarFsNativeUint8Array.prototype) throw new __velarFsNativeTypeError(operation + \" host returned invalid bytes\");\n if (__velarFsByteLength(value) > __velarFsMaxFileBytes) throw new __velarFsNativeRangeError(operation + \" host returned oversized bytes\");\n return value;\n}\n\nfunction __velarFsNull(value, operation) {\n if (value !== null) throw new __velarFsNativeTypeError(operation + \" host returned an invalid completion\");\n return null;\n}\n\nfunction __velarFsInfo(value) {\n if (value === null) return null;\n if (!value || typeof value !== \"object\" || __velarFsCall(__velarFsObjectGetPrototypeOf, __velarFsNativeObject, [value]) !== __velarFsNativeObject.prototype) {\n throw new __velarFsNativeTypeError(\"info host returned an invalid result\");\n }\n const output = __velarFsCall(__velarFsObjectCreate, __velarFsNativeObject, [null]);\n const fields = [\"name\", \"kind\", \"size\", \"modifiedAt\"];\n for (let index = 0; index < fields.length; index += 1) {\n const name = fields[index];\n const descriptor = __velarFsOwnDescriptor(value, name);\n if (!descriptor?.enumerable || !(\"value\" in descriptor)) throw new __velarFsNativeTypeError(\"info host returned an invalid result\");\n output[name] = descriptor.value;\n }\n if (typeof output.name !== \"string\" || output.name.length > __velarFsMaxPathCodeUnits\n || output.kind !== \"file\" && output.kind !== \"directory\" && output.kind !== \"symlink\" && output.kind !== \"other\"\n || typeof output.size !== \"number\" || !__velarFsCall(__velarFsNumberIsFinite, __velarFsNativeNumber, [output.size]) || output.size < 0\n || typeof output.modifiedAt !== \"number\" || !__velarFsCall(__velarFsNumberIsFinite, __velarFsNativeNumber, [output.modifiedAt])) {\n throw new __velarFsNativeTypeError(\"info host returned an invalid result\");\n }\n return __velarFsCall(__velarFsObjectFreeze, __velarFsNativeObject, [output]);\n}\n\nfunction __velarFsWatchBatch(value) {\n if (!value || typeof value !== \"object\" || __velarFsCall(__velarFsObjectGetPrototypeOf, __velarFsNativeObject, [value]) !== __velarFsNativeObject.prototype\n || __velarFsCall(__velarFsObjectKeys, __velarFsNativeObject, [value]).length !== 2) {\n throw new __velarFsNativeTypeError(\"FileWatcher.next host returned an invalid batch\");\n }\n const pathsDescriptor = __velarFsOwnDescriptor(value, \"paths\");\n const rescanDescriptor = __velarFsOwnDescriptor(value, \"rescan\");\n if (!pathsDescriptor?.enumerable || !(\"value\" in pathsDescriptor) || !rescanDescriptor?.enumerable || !(\"value\" in rescanDescriptor)\n || typeof rescanDescriptor.value !== \"boolean\"\n || !__velarFsCall(__velarFsArrayIsArray, __velarFsNativeArray, [pathsDescriptor.value])\n || pathsDescriptor.value.length > __velarFsMaxWatchPaths\n || rescanDescriptor.value && pathsDescriptor.value.length !== 0) {\n throw new __velarFsNativeTypeError(\"FileWatcher.next host returned an invalid batch\");\n }\n const paths = [];\n let units = 0;\n let previous = null;\n for (let index = 0; index < pathsDescriptor.value.length; index += 1) {\n const descriptor = __velarFsOwnDescriptor(pathsDescriptor.value, __velarFsNativeString(index));\n if (!descriptor?.enumerable || !(\"value\" in descriptor) || typeof descriptor.value !== \"string\"\n || descriptor.value.length === 0 || descriptor.value.length > __velarFsMaxPathCodeUnits\n || __velarFsCall(__velarFsStringIncludes, descriptor.value, [\"\\0\"])\n || previous !== null && descriptor.value <= previous) {\n throw new __velarFsNativeTypeError(\"FileWatcher.next host returned invalid paths\");\n }\n units += descriptor.value.length;\n if (units > __velarFsMaxListCodeUnits) throw new __velarFsNativeRangeError(\"FileWatcher.next paths cannot exceed 2 MiB of text\");\n paths[index] = descriptor.value;\n previous = descriptor.value;\n }\n return __velarFsCall(__velarFsObjectFreeze, __velarFsNativeObject, [{\n paths,\n rescan: rescanDescriptor.value,\n }]);\n}\n\nclass FileWatcherHandle {\n constructor(token, handle) {\n if (token !== __velarFsWatcherToken || !__velarFsCall(__velarFsNumberIsSafeInteger, __velarFsNativeNumber, [handle]) || handle < 1) {\n throw new __velarFsNativeTypeError(\"FileWatcher values are created only by velar/fs.watchFiles\");\n }\n this.handle = handle;\n this.closed = false;\n this.pending = false;\n this.next = async () => {\n if (this.closed) return null;\n if (this.pending) throw new __velarFsNativeError(\"FileWatcher.next already has an active pull\");\n this.pending = true;\n try {\n const value = await __velarNodeHostInvoke(\"fs.watchNext\", [this.handle]);\n if (value === null) {\n this.closed = true;\n return null;\n }\n return __velarFsWatchBatch(value);\n } catch (error) {\n this.closed = true;\n try { await __velarNodeHostInvoke(\"fs.watchClose\", [this.handle]); } catch {}\n throw error;\n } finally {\n this.pending = false;\n }\n };\n }\n async close() {\n if (this.closed) return null;\n this.closed = true;\n const value = await __velarNodeHostInvoke(\"fs.watchClose\", [this.handle]);\n if (typeof value !== \"boolean\") throw new __velarFsNativeTypeError(\"FileWatcher.close host returned an invalid result\");\n return null;\n }\n}\n\nexport const FileWatcher = __velarFsCall(__velarFsObjectFreeze, __velarFsNativeObject, [{\n is(value) { return value instanceof FileWatcherHandle; },\n parse(value) {\n if (!(value instanceof FileWatcherHandle)) throw new __velarFsNativeTypeError(\"Value does not match FileWatcher\");\n return value;\n },\n}]);\n\nexport const FileWatchBatch = __velarFsCall(__velarFsObjectFreeze, __velarFsNativeObject, [{\n is(value) { try { __velarFsWatchBatch(value); return true; } catch { return false; } },\n parse(value) { return __velarFsWatchBatch(value); },\n}]);\n\nexport async function readText(path, maxBytes = __velarFsMaxFileBytes) {\n path = __velarFsPath(path, \"readText\");\n maxBytes = __velarFsByteLimit(maxBytes, \"readText\");\n const data = __velarFsBytes(await __velarNodeHostInvoke(\"fs.readFile\", [path, maxBytes, \"readText\"]), \"readText\");\n if (__velarFsByteLength(data) > maxBytes) throw new __velarFsNativeRangeError(\"readText file exceeds maxBytes\");\n try { return __velarFsCall(__velarFsTextDecoderDecode, __velarFsDecoder, [data]); }\n catch { throw new __velarFsNativeTypeError(\"readText requires valid UTF-8 text\"); }\n}\n\nexport async function readBytes(path, maxBytes = __velarFsMaxFileBytes) {\n path = __velarFsPath(path, \"readBytes\");\n maxBytes = __velarFsByteLimit(maxBytes, \"readBytes\");\n const data = __velarFsBytes(await __velarNodeHostInvoke(\"fs.readFile\", [path, maxBytes, \"readBytes\"]), \"readBytes\");\n if (__velarFsByteLength(data) > maxBytes) throw new __velarFsNativeRangeError(\"readBytes file exceeds maxBytes\");\n return __velarFsBytesType.parse(data);\n}\n\nexport async function createText(path, text) {\n path = __velarFsPath(path, \"createText\");\n if (typeof text !== \"string\") throw new __velarFsNativeTypeError(\"createText requires text\");\n if (__velarUtf8ByteLength(text) > __velarFsMaxFileBytes) throw new __velarFsNativeRangeError(\"createText cannot write more than 16 MiB\");\n return __velarFsNull(await __velarNodeHostInvoke(\"fs.createFile\", [path, __velarFsEncode(text)]), \"createText\");\n}\n\nexport async function createBytes(path, bytes) {\n path = __velarFsPath(path, \"createBytes\");\n bytes = __velarFsBytesType.parse(bytes);\n if (__velarFsByteLength(bytes) > __velarFsMaxFileBytes) throw new __velarFsNativeRangeError(\"createBytes cannot write more than 16 MiB\");\n return __velarFsNull(await __velarNodeHostInvoke(\"fs.createFile\", [path, bytes, \"createBytes\"]), \"createBytes\");\n}\n\nexport async function replaceTextIfMatches(path, expected, replacement) {\n path = __velarFsPath(path, \"replaceTextIfMatches\");\n if (typeof expected !== \"string\" || typeof replacement !== \"string\") throw new __velarFsNativeTypeError(\"replaceTextIfMatches requires expected and replacement text\");\n if (__velarUtf8ByteLength(expected) > __velarFsMaxFileBytes || __velarUtf8ByteLength(replacement) > __velarFsMaxFileBytes) {\n throw new __velarFsNativeRangeError(\"replaceTextIfMatches text cannot exceed 16 MiB\");\n }\n const value = await __velarNodeHostInvoke(\"fs.replaceFileIfMatches\", [path, __velarFsEncode(expected), __velarFsEncode(replacement)]);\n if (typeof value !== \"boolean\") throw new __velarFsNativeTypeError(\"replaceTextIfMatches host returned an invalid result\");\n return value;\n}\n\nexport async function writeText(path, text) {\n path = __velarFsPath(path, \"writeText\");\n if (typeof text !== \"string\") throw new __velarFsNativeTypeError(\"writeText requires text\");\n if (__velarUtf8ByteLength(text) > __velarFsMaxFileBytes) throw new __velarFsNativeRangeError(\"writeText cannot write more than 16 MiB\");\n return __velarFsNull(await __velarNodeHostInvoke(\"fs.writeFile\", [path, __velarFsEncode(text)]), \"writeText\");\n}\n\nexport async function writeBytes(path, bytes) {\n path = __velarFsPath(path, \"writeBytes\");\n bytes = __velarFsBytesType.parse(bytes);\n if (__velarFsByteLength(bytes) > __velarFsMaxFileBytes) throw new __velarFsNativeRangeError(\"writeBytes cannot write more than 16 MiB\");\n return __velarFsNull(await __velarNodeHostInvoke(\"fs.writeFile\", [path, bytes, \"writeBytes\"]), \"writeBytes\");\n}\n\nexport async function appendText(path, text) {\n path = __velarFsPath(path, \"appendText\");\n if (typeof text !== \"string\") throw new __velarFsNativeTypeError(\"appendText requires text\");\n if (__velarUtf8ByteLength(text) > __velarFsMaxFileBytes) throw new __velarFsNativeRangeError(\"appendText cannot append more than 16 MiB at once\");\n return __velarFsNull(await __velarNodeHostInvoke(\"fs.appendFile\", [path, __velarFsEncode(text)]), \"appendText\");\n}\n\nexport async function exists(path) {\n const value = await __velarNodeHostInvoke(\"fs.exists\", [__velarFsPath(path, \"exists\")]);\n if (typeof value !== \"boolean\") throw new __velarFsNativeTypeError(\"exists host returned an invalid result\");\n return value;\n}\n\nexport async function list(path, maxItems = __velarFsMaxListItems) {\n path = __velarFsPath(path, \"list\");\n if (!__velarFsCall(__velarFsNumberIsSafeInteger, __velarFsNativeNumber, [maxItems]) || maxItems < 1 || maxItems > __velarFsMaxListItems) {\n throw new __velarFsNativeRangeError(\"list maxItems must be an integer from 1 through 100000\");\n }\n const names = await __velarNodeHostInvoke(\"fs.list\", [path, maxItems]);\n if (!__velarFsCall(__velarFsArrayIsArray, __velarFsNativeArray, [names]) || names.length > maxItems) throw new __velarFsNativeTypeError(\"list host returned an invalid result\");\n const output = [];\n let units = 0;\n for (let index = 0; index < names.length; index += 1) {\n const descriptor = __velarFsOwnDescriptor(names, __velarFsNativeString(index));\n if (!descriptor?.enumerable || !(\"value\" in descriptor) || typeof descriptor.value !== \"string\") {\n throw new __velarFsNativeTypeError(\"list host result must contain text names\");\n }\n units += descriptor.value.length;\n if (units > __velarFsMaxListCodeUnits) throw new __velarFsNativeRangeError(\"list result cannot exceed 2 MiB of text\");\n output[index] = descriptor.value;\n }\n return __velarFsCall(__velarFsArraySort, output, []);\n}\n\nexport async function info(path) {\n return __velarFsInfo(await __velarNodeHostInvoke(\"fs.info\", [__velarFsPath(path, \"info\")]));\n}\n\nexport async function canonical(path) {\n const value = await __velarNodeHostInvoke(\"fs.canonical\", [__velarFsPath(path, \"canonical\")]);\n return __velarFsPath(value, \"canonical\");\n}\n\nexport async function makeDirectory(path) {\n return __velarFsNull(await __velarNodeHostInvoke(\"fs.makeDirectory\", [__velarFsPath(path, \"makeDirectory\")]), \"makeDirectory\");\n}\n\nexport async function copyFile(source, target, replace = false) {\n source = __velarFsPath(source, \"copyFile\");\n target = __velarFsPath(target, \"copyFile\");\n if (typeof replace !== \"boolean\") throw new __velarFsNativeTypeError(\"copyFile replace must be bool\");\n return __velarFsNull(await __velarNodeHostInvoke(\"fs.copyFile\", [source, target, replace]), \"copyFile\");\n}\n\nexport async function move(source, target, replace = false) {\n source = __velarFsPath(source, \"move\");\n target = __velarFsPath(target, \"move\");\n if (typeof replace !== \"boolean\") throw new __velarFsNativeTypeError(\"move replace must be bool\");\n return __velarFsNull(await __velarNodeHostInvoke(\"fs.move\", [source, target, replace]), \"move\");\n}\n\nexport async function removeFile(path) {\n return __velarFsNull(await __velarNodeHostInvoke(\"fs.removeFile\", [__velarFsPath(path, \"removeFile\")]), \"removeFile\");\n}\n\nexport async function watchFiles(path, recursive = false) {\n path = __velarFsPath(path, \"watchFiles\");\n if (typeof recursive !== \"boolean\") throw new __velarFsNativeTypeError(\"watchFiles recursive must be bool\");\n const handle = await __velarNodeHostInvoke(\"fs.watchStart\", [path, recursive]);\n return new FileWatcherHandle(__velarFsWatcherToken, handle);\n}\n"; /** `velar/fs` — the filesystem boundary over the compiler's UTF-8 runtime. */ export declare const VELAR_NODE_FS_MODULE_SOURCE: string; /** * `velar/host` — the canonical Node lifecycle boundary. It captures the signal, * exit, timer, Promise and diagnostic operations it uses before application * code can replace their public properties or prototypes. */ export declare const VELAR_NODE_HOST_RUNTIME = "import { writeSync as __velarHostWriteSync } from \"node:fs\";\n\nconst __velarHostNativeArray = globalThis.Array;\nconst __velarHostNativeDate = globalThis.Date;\nconst __velarHostNativeError = globalThis.Error;\nconst __velarHostNativeNumber = globalThis.Number;\nconst __velarHostNativeObject = globalThis.Object;\nconst __velarHostNativePromise = globalThis.Promise;\nconst __velarHostNativeRangeError = globalThis.RangeError;\nconst __velarHostNativeReflect = globalThis.Reflect;\nconst __velarHostNativeTypeError = globalThis.TypeError;\nconst __velarHostOwnDescriptor = __velarHostNativeObject.getOwnPropertyDescriptor;\nconst __velarHostApply = __velarHostNativeReflect.apply;\nfunction __velarHostDataOperation(target, name) {\n const descriptor = __velarHostOwnDescriptor(target, name);\n if (!descriptor || !(\"value\" in descriptor) || typeof descriptor.value !== \"function\") {\n throw new __velarHostNativeError(\"VelarScript host lifecycle operation '\" + name + \"' is unavailable\");\n }\n return descriptor.value;\n}\nconst __velarHostArrayPush = __velarHostDataOperation(__velarHostNativeArray.prototype, \"push\");\nconst __velarHostDateNow = __velarHostDataOperation(__velarHostNativeDate, \"now\");\nconst __velarHostNumberIsSafeInteger = __velarHostDataOperation(__velarHostNativeNumber, \"isSafeInteger\");\nconst __velarHostPromiseThen = __velarHostDataOperation(__velarHostNativePromise.prototype, \"then\");\nconst __velarHostSetTimeout = globalThis.setTimeout;\nconst __velarHostClearTimeout = globalThis.clearTimeout;\nconst __velarHostProcess = globalThis.process;\nconst __velarHostProcessOn = __velarHostProcess.on;\nconst __velarHostProcessExit = __velarHostProcess.exit;\nconst __velarHostCleanups = [];\nconst maxShutdownCleanups = 1024;\nconst shutdownTimeoutMs = 30000;\nlet __velarHostListening = false;\nlet __velarHostShuttingDown = false;\n\nfunction __velarHostCall(operation, receiver, arguments_) {\n return __velarHostApply(operation, receiver, arguments_);\n}\n\nfunction __velarHostNow() {\n return __velarHostCall(__velarHostDateNow, __velarHostNativeDate, []);\n}\n\nfunction __velarHostExitCode(value) {\n if (!__velarHostCall(__velarHostNumberIsSafeInteger, __velarHostNativeNumber, [value]) || value < 0 || value > 255) {\n throw new __velarHostNativeRangeError(\"exit code must be an integer from 0 through 255\");\n }\n return value;\n}\n\nfunction __velarHostThen(value, fulfilled, rejected) {\n return __velarHostCall(__velarHostPromiseThen, value, [fulfilled, rejected]);\n}\n\nfunction __velarHostErrorMessage(error) {\n if (!error || typeof error !== \"object\") return \"Unknown shutdown failure\";\n const descriptor = __velarHostOwnDescriptor(error, \"message\");\n return descriptor && \"value\" in descriptor && typeof descriptor.value === \"string\"\n ? descriptor.value\n : \"Unknown shutdown failure\";\n}\n\nfunction __velarHostDiagnostic(message, error = null) {\n const suffix = error === null ? \"\" : \": \" + __velarHostErrorMessage(error);\n __velarHostWriteSync(2, message + suffix + \"\\n\", null, \"utf8\");\n}\n\nfunction __velarHostDeadline(cleanup, remaining) {\n let timer = null;\n const result = new __velarHostNativePromise((resolve, reject) => {\n timer = __velarHostSetTimeout(\n () => reject(new __velarHostNativeError(\"Shutdown cleanup timed out after \" + shutdownTimeoutMs + \" ms\")),\n remaining,\n );\n let cleanupResult;\n try { cleanupResult = __velarHostCall(cleanup, undefined, []); }\n catch (error) { reject(error); return; }\n try {\n __velarHostThen(\n cleanupResult,\n value => value === null\n ? resolve(null)\n : reject(new __velarHostNativeTypeError(\"A shutdown cleanup must resolve to null\")),\n reject,\n );\n } catch {\n reject(new __velarHostNativeTypeError(\"A shutdown cleanup must return a host Promise\"));\n }\n });\n return { result, cancel() { if (timer !== null) { __velarHostClearTimeout(timer); timer = null; } } };\n}\n\nasync function __velarHostShutdown(signal) {\n if (__velarHostShuttingDown) {\n __velarHostCall(__velarHostProcessExit, __velarHostProcess, [signal === \"SIGINT\" ? 130 : 143]);\n return;\n }\n __velarHostShuttingDown = true;\n let code = signal === \"SIGINT\" ? 130 : 143;\n const deadline = __velarHostNow() + shutdownTimeoutMs;\n for (let index = 0; index < __velarHostCleanups.length; index += 1) {\n const remaining = deadline - __velarHostNow();\n if (remaining <= 0) {\n code = 1;\n __velarHostDiagnostic(\"[velar/host] shutdown cleanup deadline exceeded\");\n break;\n }\n const pending = __velarHostDeadline(__velarHostCleanups[index], remaining);\n try {\n const result = await pending.result;\n if (result !== null) throw new __velarHostNativeTypeError(\"A shutdown cleanup must resolve to null\");\n } catch (error) {\n code = 1;\n __velarHostDiagnostic(\"[velar/host] shutdown cleanup failed\", error);\n if (__velarHostNow() >= deadline) break;\n } finally {\n pending.cancel();\n }\n }\n __velarHostCall(__velarHostProcessExit, __velarHostProcess, [code]);\n}\n\nfunction __velarHostListen() {\n if (__velarHostListening) return;\n __velarHostListening = true;\n __velarHostCall(__velarHostProcessOn, __velarHostProcess, [\"SIGINT\", () => { void __velarHostShutdown(\"SIGINT\"); }]);\n __velarHostCall(__velarHostProcessOn, __velarHostProcess, [\"SIGTERM\", () => { void __velarHostShutdown(\"SIGTERM\"); }]);\n}\n\nexport function exit(code = 0) {\n __velarHostCall(__velarHostProcessExit, __velarHostProcess, [__velarHostExitCode(code)]);\n}\n\nexport function onShutdown(cleanup) {\n if (typeof cleanup !== \"function\") throw new __velarHostNativeTypeError(\"onShutdown requires an async cleanup function\");\n if (__velarHostShuttingDown) throw new __velarHostNativeError(\"Cannot register a shutdown cleanup after shutdown begins\");\n if (__velarHostCleanups.length >= maxShutdownCleanups) {\n throw new __velarHostNativeRangeError(\"onShutdown cannot register more than 1024 cleanups\");\n }\n __velarHostCall(__velarHostArrayPush, __velarHostCleanups, [cleanup]);\n __velarHostListen();\n return null;\n}\n"; /** `velar/http` — the outbound HTTP client over the isolated Node host. */ export declare const VELAR_NODE_HTTP_RUNTIME: string; /** * The static-file half of the privileged Node serve transport, its own file so * that both halves stay inside D115 §一.1's reading budget: path * canonicalization inside a root, the file load with its fallback, * ETag/Last-Modified/Range conditionals, and the ranged write. It is one * contiguous region of the same Worker source, composed back at exactly the * position it occupied. */ export declare const VELAR_NODE_HOST_STATIC_FILE_SOURCE = "function requestPath(value) {\n if (typeof value !== \"string\" || value.length === 0 || value.length > maxPathCodeUnits || value.includes(\"\\0\") || value.includes(\"\\\\\")) {\n throw new StaticNotFound();\n }\n const source = value.startsWith(\"/\") ? value : \"/\" + value;\n const segments = source.split(\"/\").filter(Boolean);\n if (segments.some(segment => segment === \".\" || segment === \"..\")) throw new StaticNotFound();\n return segments.join(\"/\");\n}\n\nfunction inside(root, target) {\n // relative() emits \"..\" only as a whole segment, so the escape test compares\n // whole segments too: a prefix test also rejects an ordinary top-level file\n // whose own name begins with two dots. The separator is the platform's,\n // because relative() writes an escape with a backslash on Windows.\n const path = relative(root, target);\n return path === \"\" || path !== \"..\" && !path.startsWith(\"..\" + sep) && !isAbsolute(path);\n}\n\n/**\n * The directory a static root resolves to.\n *\n * D114 F9-node-cli (audit NO-D1) took the choice away from here. `velar/serve`\n * used to hand over two candidates \u2014 the root against the project root the\n * build knew, and the same root beside the emitted entry \u2014 and this transport\n * picked between them by which of the two directories existed. Existence is not\n * identity: that is how a `dist/` copied beside a stranger's `public/` came to\n * publish the stranger's files as this application's assets. Only `velar/serve`\n * can ask who the directory at that offset belongs to, so it settles one\n * application root base before any request and what arrives here is a single\n * root. A root that does not resolve is the same miss it has always been.\n */\nasync function staticRoot(rootValue) {\n return realpath(resolve(boundedPath(rootValue, \"fileResponse\")));\n}\n\nasync function staticFile(rootValue, pathValue, fallbackValue) {\n const root = await staticRoot(rootValue);\n const relativePath = requestPath(pathValue);\n const fallback = fallbackValue === null ? null : requestPath(fallbackValue);\n const load = async path => {\n const target = await realpath(resolve(root, path));\n if (!inside(root, target)) throw new StaticNotFound();\n const metadata = await stat(target);\n if (!metadata.isFile() || metadata.size > maxServeFileBytes) throw new StaticNotFound();\n return {target, metadata, contentType: contentTypes[extname(target).toLowerCase()] ?? \"application/octet-stream\"};\n };\n try { return await load(relativePath); }\n catch (error) {\n if ((error instanceof StaticNotFound || missing(error) || error?.code === \"EISDIR\") && fallback !== null) return load(fallback);\n throw error;\n }\n}\n\nfunction staticEtag(metadata) {\n const modified = Number.isFinite(metadata.mtimeMs) ? Math.floor(metadata.mtimeMs) : 0;\n return 'W/\"' + metadata.size.toString(16) + \"-\" + modified.toString(16) + '\"';\n}\n\nfunction staticNotModified(request, metadata, etag) {\n const noneMatch = request.headers[\"if-none-match\"];\n if (typeof noneMatch === \"string\") {\n for (const candidate of noneMatch.split(\",\")) if (candidate.trim() === \"*\" || candidate.trim() === etag) return true;\n return false;\n }\n const modifiedSince = request.headers[\"if-modified-since\"];\n if (typeof modifiedSince !== \"string\") return false;\n const time = Date.parse(modifiedSince);\n return Number.isFinite(time) && Math.floor(metadata.mtimeMs / 1000) * 1000 <= time;\n}\n\nfunction staticRange(request, metadata, etag) {\n const value = request.headers.range;\n if (typeof value !== \"string\") return null;\n const ifRange = request.headers[\"if-range\"];\n if (typeof ifRange === \"string\" && ifRange !== etag) {\n const time = Date.parse(ifRange);\n if (!Number.isFinite(time) || Math.floor(metadata.mtimeMs / 1000) * 1000 > time) return null;\n }\n const match = /^bytes=(\\d*)-(\\d*)$/u.exec(value.trim());\n if (!match || match[1] === \"\" && match[2] === \"\" || metadata.size === 0) return false;\n let start;\n let end;\n if (match[1] === \"\") {\n const suffix = Number(match[2]);\n if (!Number.isSafeInteger(suffix) || suffix < 1) return false;\n start = Math.max(0, metadata.size - suffix);\n end = metadata.size - 1;\n } else {\n start = Number(match[1]);\n end = match[2] === \"\" ? metadata.size - 1 : Number(match[2]);\n if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 0 || start >= metadata.size || end < start) return false;\n if (end >= metadata.size) end = metadata.size - 1;\n }\n return {start, end};\n}\n\nasync function writeStaticRange(task, file, start, end) {\n if (end < start) return;\n const source = createReadStream(file.target, {start, end, highWaterMark: 64 * 1024});\n try {\n for await (const chunk of source) {\n const bytes = chunk.byteLength;\n reserveTransientServeBytes(bytes);\n try {\n await new Promise((resolveWrite, rejectWrite) => {\n let settled = false;\n const cleanup = () => { task.response.off(\"error\", failed); task.response.off(\"close\", closed); };\n const finish = action => { if (settled) return; settled = true; cleanup(); action(); };\n const failed = error => finish(() => rejectWrite(error));\n const closed = () => finish(() => rejectWrite(new Error(\"ServeResponse client connection is closed\")));\n task.response.once(\"error\", failed);\n task.response.once(\"close\", closed);\n task.response.write(chunk, error => error ? failed(error) : finish(resolveWrite));\n });\n } finally { releaseTransientServeBytes(bytes); }\n }\n } finally { source.destroy(); }\n}\n\nasync function testStaticFile(rootValue, pathValue, fallbackValue) {\n const root = await staticRoot(rootValue);\n const relativePath = requestPath(pathValue);\n const fallback = fallbackValue === null ? null : requestPath(fallbackValue);\n const load = async path => {\n const target = await realpath(resolve(root, path));\n if (!inside(root, target)) throw new StaticNotFound();\n const metadata = await stat(target);\n if (!metadata.isFile() || metadata.size > maxServeBodyBytes) throw new StaticNotFound();\n let reserved = metadata.size * 2;\n reserveTransientServeBytes(reserved);\n try {\n const source = await readFile(target);\n if (source.byteLength > maxServeBodyBytes) throw new StaticNotFound();\n if (source.byteLength > metadata.size) { const extra = (source.byteLength - metadata.size) * 2; reserveTransientServeBytes(extra); reserved += extra; }\n else if (source.byteLength < metadata.size) { const surplus = (metadata.size - source.byteLength) * 2; releaseTransientServeBytes(surplus); reserved -= surplus; }\n const data = new Uint8Array(source.byteLength);\n data.set(source);\n releaseTransientServeBytes(source.byteLength);\n reserved -= source.byteLength;\n return {data, contentType: contentTypes[extname(target).toLowerCase()] ?? \"application/octet-stream\"};\n } catch (error) { releaseTransientServeBytes(reserved); throw error; }\n };\n try { return await load(relativePath); }\n catch (error) {\n if ((error instanceof StaticNotFound || missing(error) || error?.code === \"EISDIR\") && fallback !== null) return load(fallback);\n throw error;\n }\n}"; /** * The privileged Node transport shared by the official Node standard modules. * This Worker loads only compiler-owned source and static Node built-ins; * VelarScript application code and npm dependencies remain in the application * Realm. */ export declare const VELAR_NODE_HOST_WORKER_SOURCE: string; /** * `velar/node-host-v1` — the application-facing proxy for the shared privileged * Node worker, carrying that worker's source as the string it constructs it * from. This module is a private compiler-extension dependency and has no * VelarScript interface. */ export declare const VELAR_SHARED_NODE_HOST_RUNTIME: string; /** `velar/path` — bounded path arithmetic, with no filesystem effect at all. */ export declare const VELAR_NODE_PATH_MODULE_SOURCE = "import { basename as nodeBasename, dirname as nodeDirname, extname, isAbsolute as nodeIsAbsolute, join as nodeJoin, normalize as nodeNormalize, relative as nodeRelative, resolve as nodeResolve } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\n\nconst maxPathCodeUnits = 4096;\nconst pathApply = Reflect.apply;\nconst pathArrayIsArray = Array.isArray;\nconst pathGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\nconst pathStringIncludes = String.prototype.includes;\nconst pathStringStartsWith = String.prototype.startsWith;\nconst pathSeparator = process.platform === \"win32\" ? \"\\\\\" : \"/\";\nfunction stringIncludes(value, search) { return pathApply(pathStringIncludes, value, [search]); }\nfunction stringStartsWith(value, search) { return pathApply(pathStringStartsWith, value, [search]); }\nfunction pathValue(value, operation) {\n if (typeof value !== \"string\" || value.length === 0) throw new TypeError(operation + \" requires a non-empty path string\");\n if (value.length > maxPathCodeUnits || stringIncludes(value, \"\\0\")) throw new RangeError(operation + \" path is outside the supported bounds\");\n return value;\n}\nfunction pathParts(values, operation) {\n if (!pathArrayIsArray(values) || values.length > 256) throw new TypeError(operation + \" requires a bounded List\");\n const output = [];\n for (let index = 0; index < values.length; index += 1) {\n const descriptor = pathGetOwnPropertyDescriptor(values, index);\n if (!descriptor?.enumerable || !(\"value\" in descriptor)) throw new TypeError(operation + \" path parts must contain enumerable data values\");\n output[output.length] = pathValue(descriptor.value, operation);\n }\n return output;\n}\nfunction bounded(value, operation) {\n if (value.length > maxPathCodeUnits) throw new RangeError(operation + \" result is outside the supported bounds\");\n return value;\n}\n\nexport function resolve(parts = []) { return bounded(pathApply(nodeResolve, undefined, pathParts(parts, \"resolve\")), \"resolve\"); }\nexport function join(parts = []) { return bounded(pathApply(nodeJoin, undefined, pathParts(parts, \"join\")), \"join\"); }\nexport function normalize(path) { return bounded(nodeNormalize(pathValue(path, \"normalize\")), \"normalize\"); }\nexport function relative(from, to) { return bounded(nodeRelative(pathValue(from, \"relative\"), pathValue(to, \"relative\")), \"relative\"); }\nexport function dirname(path) { return bounded(nodeDirname(pathValue(path, \"dirname\")), \"dirname\"); }\nexport function basename(path) { return nodeBasename(pathValue(path, \"basename\")); }\nexport function extension(path) { return extname(pathValue(path, \"extension\")); }\nexport function isAbsolute(path) { return nodeIsAbsolute(pathValue(path, \"isAbsolute\")); }\nexport function contains(root, target) {\n root = nodeResolve(pathValue(root, \"contains\"));\n target = nodeResolve(pathValue(target, \"contains\"));\n const path = nodeRelative(root, target);\n return path === \"\" || (path !== \"..\" && !stringStartsWith(path, \"..\" + pathSeparator) && !nodeIsAbsolute(path));\n}\nexport function toFileUrl(path) { return pathToFileURL(nodeResolve(pathValue(path, \"toFileUrl\"))).href; }\nexport function fromFileUrl(url) {\n url = pathValue(url, \"fromFileUrl\");\n if (!stringStartsWith(url, \"file:\")) throw new TypeError(\"fromFileUrl requires a file URL\");\n return bounded(fileURLToPath(url), \"fromFileUrl\");\n}\n"; /** * The canonical host-intrinsic boundary shared by the Node and Desktop targets * of velar/process. It is compiler-extension infrastructure, not a public Velar * module: target runtimes inline it before accepting application or bridge * values so later JavaScript prototype replacement cannot change validation. */ export declare const VELAR_PROCESS_HOST_RUNTIME = "const __velarProcessNativeArray = globalThis.Array;\nconst __velarProcessNativeError = globalThis.Error;\nconst __velarProcessNativeMap = globalThis.Map;\nconst __velarProcessNativeNumber = globalThis.Number;\nconst __velarProcessNativeObject = globalThis.Object;\nconst __velarProcessNativePromise = globalThis.Promise;\nconst __velarProcessNativeRangeError = globalThis.RangeError;\nconst __velarProcessNativeReflect = globalThis.Reflect;\nconst __velarProcessNativeSet = globalThis.Set;\nconst __velarProcessNativeString = globalThis.String;\nconst __velarProcessNativeTypeError = globalThis.TypeError;\nconst __velarProcessOwnDescriptor = __velarProcessNativeObject.getOwnPropertyDescriptor;\nconst __velarProcessApply = __velarProcessNativeReflect.apply;\nfunction __velarProcessDataOperation(target, name) {\n const descriptor = __velarProcessOwnDescriptor(target, name);\n if (!descriptor || !(\"value\" in descriptor) || typeof descriptor.value !== \"function\") {\n throw new __velarProcessNativeError(\"VelarScript process host operation '\" + name + \"' is unavailable\");\n }\n return descriptor.value;\n}\nconst __velarProcessArrayIsArray = __velarProcessDataOperation(__velarProcessNativeArray, \"isArray\");\nconst __velarProcessArrayShift = __velarProcessDataOperation(__velarProcessNativeArray.prototype, \"shift\");\nconst __velarProcessNumberIsSafeInteger = __velarProcessDataOperation(__velarProcessNativeNumber, \"isSafeInteger\");\nconst __velarProcessObjectCreate = __velarProcessDataOperation(__velarProcessNativeObject, \"create\");\nconst __velarProcessObjectFreeze = __velarProcessDataOperation(__velarProcessNativeObject, \"freeze\");\nconst __velarProcessObjectGetPrototypeOf = __velarProcessDataOperation(__velarProcessNativeObject, \"getPrototypeOf\");\nconst __velarProcessObjectSeal = __velarProcessDataOperation(__velarProcessNativeObject, \"seal\");\nconst __velarProcessOwnKeys = __velarProcessDataOperation(__velarProcessNativeReflect, \"ownKeys\");\nconst __velarProcessPromiseReject = __velarProcessDataOperation(__velarProcessNativePromise, \"reject\");\nconst __velarProcessPromiseResolve = __velarProcessDataOperation(__velarProcessNativePromise, \"resolve\");\nconst __velarProcessPromiseThen = __velarProcessDataOperation(__velarProcessNativePromise.prototype, \"then\");\nconst __velarProcessSetHas = __velarProcessDataOperation(__velarProcessNativeSet.prototype, \"has\");\nconst __velarProcessStringIncludes = __velarProcessDataOperation(__velarProcessNativeString.prototype, \"includes\");\nconst __velarProcessMapEntries = __velarProcessDataOperation(__velarProcessNativeMap.prototype, \"entries\");\nconst __velarProcessMapSize = __velarProcessOwnDescriptor(__velarProcessNativeMap.prototype, \"size\")?.get;\nconst __velarProcessMapIterator = __velarProcessApply(__velarProcessMapEntries, new __velarProcessNativeMap(), []);\nconst __velarProcessMapIteratorNext = __velarProcessDataOperation(__velarProcessObjectGetPrototypeOf(__velarProcessMapIterator), \"next\");\nconst __velarProcessEnvironmentPattern = /^[A-Za-z_][A-Za-z0-9_]*$/u;\nconst __velarProcessRegExpTest = __velarProcessDataOperation(globalThis.RegExp.prototype, \"test\");\nconst __velarProcessSetTimeout = globalThis.setTimeout;\nconst __velarProcessClearTimeout = globalThis.clearTimeout;\nfunction __velarProcessCall(operation, receiver, arguments_) {\n return __velarProcessApply(operation, receiver, arguments_);\n}\nfunction __velarProcessIsArray(value) {\n return __velarProcessCall(__velarProcessArrayIsArray, __velarProcessNativeArray, [value]);\n}\nfunction __velarProcessIsSafeInteger(value) {\n return __velarProcessCall(__velarProcessNumberIsSafeInteger, __velarProcessNativeNumber, [value]);\n}\nfunction __velarProcessIncludes(value, search) {\n return __velarProcessCall(__velarProcessStringIncludes, value, [search]);\n}\nfunction __velarProcessFreeze(value) {\n return __velarProcessCall(__velarProcessObjectFreeze, __velarProcessNativeObject, [value]);\n}\nfunction __velarProcessSeal(value) {\n return __velarProcessCall(__velarProcessObjectSeal, __velarProcessNativeObject, [value]);\n}\nfunction __velarProcessCreate(prototype) {\n return __velarProcessCall(__velarProcessObjectCreate, __velarProcessNativeObject, [prototype]);\n}\nfunction __velarProcessGetPrototypeOf(value) {\n return __velarProcessCall(__velarProcessObjectGetPrototypeOf, __velarProcessNativeObject, [value]);\n}\nfunction __velarProcessKeys(value) {\n return __velarProcessCall(__velarProcessOwnKeys, __velarProcessNativeReflect, [value]);\n}\nfunction __velarProcessSetContains(value, item) {\n return __velarProcessCall(__velarProcessSetHas, value, [item]);\n}\nfunction __velarProcessShift(value) {\n return __velarProcessCall(__velarProcessArrayShift, value, []);\n}\nfunction __velarProcessReject(error) {\n return __velarProcessCall(__velarProcessPromiseReject, __velarProcessNativePromise, [error]);\n}\nfunction __velarProcessResolve(value) {\n return __velarProcessCall(__velarProcessPromiseResolve, __velarProcessNativePromise, [value]);\n}\nfunction __velarProcessThen(value, fulfilled, rejected) {\n return __velarProcessCall(__velarProcessPromiseThen, value, [fulfilled, rejected]);\n}\nfunction __velarProcessObservedReject(error) {\n const result = __velarProcessReject(error);\n __velarProcessThen(result, undefined, () => null);\n return result;\n}\nasync function __velarProcessRetryableStop(owner, begin) {\n owner.stopRequested = true;\n let pending = owner.stopping;\n if (!pending) {\n pending = begin();\n owner.stopping = pending;\n }\n try { await pending; }\n catch (error) {\n if (owner.stopping === pending) owner.stopping = null;\n throw error;\n }\n return null;\n}\nfunction __velarProcessRetainRun(owner) {\n if (owner.cleanup !== null) return;\n const retry = async () => {\n try {\n await owner.stop();\n owner.cleanup = null;\n } catch {\n owner.cleanup = __velarProcessCall(__velarProcessSetTimeout, globalThis, [retry, 1000]);\n }\n };\n owner.cleanup = true;\n void retry();\n}\nfunction __velarProcessEnvironmentName(value) {\n return typeof value === \"string\" && __velarProcessCall(__velarProcessRegExpTest, __velarProcessEnvironmentPattern, [value]);\n}\nfunction __velarProcessMapSnapshot(value) {\n if (typeof __velarProcessMapSize !== \"function\") throw new __velarProcessNativeTypeError(\"Process env must be Map\");\n let size;\n let iterator;\n try {\n size = __velarProcessCall(__velarProcessMapSize, value, []);\n iterator = __velarProcessCall(__velarProcessMapEntries, value, []);\n } catch {\n throw new __velarProcessNativeTypeError(\"Process env must be Map\");\n }\n const entries = [];\n while (true) {\n let step;\n try { step = __velarProcessCall(__velarProcessMapIteratorNext, iterator, []); }\n catch { throw new __velarProcessNativeTypeError(\"Process env must be Map\"); }\n const done = __velarProcessOwnDescriptor(step, \"done\");\n if (!done || !(\"value\" in done) || typeof done.value !== \"boolean\") throw new __velarProcessNativeTypeError(\"Process env must be Map\");\n if (done.value) return {size, entries};\n const item = __velarProcessOwnDescriptor(step, \"value\");\n if (!item || !(\"value\" in item) || !__velarProcessIsArray(item.value) || item.value.length !== 2) throw new __velarProcessNativeTypeError(\"Process env must be Map\");\n const name = __velarProcessOwnDescriptor(item.value, \"0\");\n const valueDescriptor = __velarProcessOwnDescriptor(item.value, \"1\");\n if (!name || !(\"value\" in name) || !valueDescriptor || !(\"value\" in valueDescriptor)) throw new __velarProcessNativeTypeError(\"Process env must be Map\");\n entries[entries.length] = [name.value, valueDescriptor.value];\n }\n}\nfunction __velarProcessRecord(value, name, allowed) {\n if (!value || typeof value !== \"object\" || __velarProcessIsArray(value)) throw new __velarProcessNativeTypeError(name + \" must be a record\");\n const prototype = __velarProcessGetPrototypeOf(value);\n if (prototype !== __velarProcessNativeObject.prototype && prototype !== null) throw new __velarProcessNativeTypeError(name + \" must be a plain record\");\n const output = __velarProcessCreate(null);\n const keys = __velarProcessKeys(value);\n for (let index = 0; index < keys.length; index += 1) {\n const key = keys[index];\n if (typeof key !== \"string\") throw new __velarProcessNativeTypeError(name + \" fields must use string names\");\n if (!__velarProcessSetContains(allowed, key)) throw new __velarProcessNativeTypeError(name + \" has unknown field '\" + key + \"'\");\n const descriptor = __velarProcessOwnDescriptor(value, key);\n if (!descriptor?.enumerable || !(\"value\" in descriptor)) throw new __velarProcessNativeTypeError(name + \" fields must be enumerable data values\");\n output[key] = descriptor.value;\n }\n return output;\n}"; /** * Signalling one owned process group and confirming it is gone: the pair the * `velar/process` owner Realm reclaims a crashed Worker's children with. The * policy above it — how many attempts, how long between them, when to give up — * stays with the reaper in the target's own module text. * * It is composed in after the owner state it reads (`__velarNodeProcessKill`, * `__velarNodeProcessNativeProcess`, `__velarNodeProcessPlatform`), which is why * it is a run of that module rather than a module of its own. */ export declare const VELAR_PROCESS_GROUP_SIGNAL_RUNTIME = "function __velarNodeProcessSignal(pid, signal) {\n try {\n __velarProcessCall(__velarNodeProcessKill, __velarNodeProcessNativeProcess, [__velarNodeProcessPlatform === \"win32\" ? pid : -pid, signal]);\n } catch {\n try { __velarProcessCall(__velarNodeProcessKill, __velarNodeProcessNativeProcess, [pid, signal]); }\n catch {}\n }\n}\n// The predicate 'processGroupExitConfirmed' applies in the worker Realm, one\n// answer to \"is this owned process group gone?\". ESRCH is the ordinary proof.\n// EPERM is the same proof once the group's root child has exited: the group id\n// is then free, and a kernel that recycles process ids answers a poll of the\n// recycled group with EPERM instead of ESRCH. While the root child is live the\n// group is still ours, so EPERM there is a real permission failure and the\n// group stays alive.\n//\n// This Realm holds a pid, not a child handle, so 'exited' is not read off a\n// ChildProcess: the proof is this reaper's own delivered SIGKILL, which cannot\n// be caught. Before that first signal there is no proof, which is exactly the\n// live-child case the worker's predicate keeps as an error; after it, EPERM\n// means the freed id was recycled to a process this Realm never owned, and the\n// owner is released rather than signalled again.\nfunction __velarNodeProcessOwnerAlive(pid, exited) {\n try {\n __velarProcessCall(__velarNodeProcessKill, __velarNodeProcessNativeProcess, [__velarNodeProcessPlatform === \"win32\" ? pid : -pid, 0]);\n return true;\n } catch (error) {\n const code = error && typeof error === \"object\" ? __velarProcessOwnDescriptor(error, \"code\") : null;\n const value = code && \"value\" in code ? code.value : null;\n if (value === \"ESRCH\") return false;\n return !(exited === true && value === \"EPERM\");\n }\n}"; /** * The complete Node-only process host. It is evaluated in an eagerly * initialized Worker realm that never loads application dependencies, because * Node's own child_process implementation consults public EventEmitter/stream * prototypes while spawning and cannot be made post-initialization-stable in a * shared application realm by wrapping only the outer calls. */ export declare const VELAR_NODE_PROCESS_WORKER_SOURCE: string; /** * `velar/process` — the owner Realm: validation, handles, the reaper, and the * isolated worker's source as the string it is constructed from. */ export declare const VELAR_NODE_PROCESS_MODULE_SOURCE: string; /** * The listener adapter: the half of `velar/serve` that speaks to a Node * `http.Server` directly, for `velar/websocket.listen({http: app})` and for a * low-level `serve(handler)`. Its own file so that both halves stay inside D115 * §一.1's reading budget — it is one contiguous region of the emitted module, * composed back at exactly the position it occupied. * * It answers the same refusals the privileged host transport answers, in the * same wire form (SV-I1), because an application must not be able to tell which * transport is under it from the shape of a 404. */ export declare const VELAR_NODE_SERVE_LISTENER_RUNTIME = "function __velarServeNativeHeaders(request) {\n const output = new __velarServeMap();\n let units = 0;\n for (const [name, value] of __velarServeObject.entries(request.headers)) {\n if (value === undefined) continue;\n const text = __velarServeIsArray(value) ? value.join(\", \") : __velarServeString(value);\n units += name.length + text.length;\n if (units > 64 * 1024) throw new __velarServeRangeError(\"ServeRequest headers cannot exceed 64 KiB\");\n output.set(name, text);\n }\n return output;\n}\n\nfunction __velarServeNativeRequest(request, maximum = __velarServeMaxBodyBytes) {\n maximum = __velarServeBodyLimit(maximum);\n const method = request.method ?? \"GET\";\n if (typeof method !== \"string\" || !__velarServeCall(__velarServeRegExpTest, __velarServeMethodPattern, [method])) throw new __velarServeTypeError(\"Native HTTP method is invalid\");\n const target = request.url ?? \"/\";\n if (typeof target !== \"string\" || target.length === 0 || __velarUtf8ByteLength(target) > 64 * 1024) throw new __velarServeRangeError(\"Native HTTP request target is too long\");\n const targetParts = __velarServeTargetParts(target, \"Native HTTP request target\");\n const path = targetParts.path;\n const query = __velarServePairsMaps(targetParts.query, \"Native ServeRequest.query\");\n const cancellation = __velarServeCancellation.__velarCreate();\n let bodyPromise = null;\n let reservedBodyBytes = 0;\n const rawBody = async () => {\n if (bodyPromise === null) bodyPromise = (async () => {\n const chunks = []; let total = 0;\n try {\n for await (const chunk of request) {\n const data = chunk instanceof __velarServeUint8Array ? chunk : __velarServeCall(__velarServeTextEncode, __velarServeUtf8Encoder, [__velarServeString(chunk)]);\n if (total + data.byteLength > maximum) { request.resume(); throw new RequestBodyTooLargeError(maximum); }\n __velarServeReserveOutbound(data.byteLength);\n total += data.byteLength;\n reservedBodyBytes += data.byteLength;\n chunks[chunks.length] = data;\n }\n __velarServeReserveOutbound(total);\n try {\n const output = new __velarServeUint8Array(total);\n let offset = 0;\n for (let index = 0; index < chunks.length; index += 1) { __velarServeCall(__velarServeUint8Set, output, [chunks[index], offset]); offset += chunks[index].byteLength; }\n chunks.length = 0;\n return output;\n }\n finally { __velarServeReleaseOutbound(total); }\n } catch (error) {\n __velarServeReleaseOutbound(reservedBodyBytes);\n reservedBodyBytes = 0;\n throw error;\n }\n })();\n return await bodyPromise;\n };\n const bytes = async (maxBytes = maximum) => {\n if (!__velarServeIsSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > __velarServeMaxBodyBytes) throw new __velarServeRangeError(\"Request body maxBytes must be an integer from 1 through 16777216\");\n const data = await rawBody();\n const effective = maxBytes > maximum ? maximum : maxBytes;\n if (data.byteLength > effective) throw new RequestBodyTooLargeError(effective);\n return data;\n };\n const body = async (maxBytes = maximum) => {\n const data = await bytes(maxBytes);\n try { return __velarServeCall(__velarServeTextDecode, __velarServeUtf8Decoder, [data]); }\n catch { throw new __velarServeTypeError(\"Request body must be valid UTF-8 text\"); }\n };\n const json = async (maxBytes = maximum) => __velarJsonParse(await body(maxBytes), \"ServeRequest JSON text\");\n return {\n request: __velarServeCall(__velarServeObjectFreeze, __velarServeObject, [{method, path, query: query.values, queryAll: query.all, headers: __velarServeNativeHeaders(request), cancellation, text: body, bytes, json, parse: async (Type, maxBytes = maximum) => { Type = __velarRequireRuntimeType(Type, \"ServeRequest.parse\"); return Type.parse(await json(maxBytes)); }}]),\n cancellation,\n cleanup() { if (reservedBodyBytes > 0) { __velarServeReleaseOutbound(reservedBodyBytes); reservedBodyBytes = 0; } return null; },\n };\n}\n\nfunction __velarServeNativeSetHeaders(response, headers, cookies = []) {\n const allCookies = [];\n for (const [name, value] of headers) {\n if (__velarServeCall(__velarServeStringToLowerCase, name, []) === \"set-cookie\") allCookies[allCookies.length] = value;\n else response.setHeader(name, value);\n }\n for (let index = 0; index < cookies.length; index += 1) allCookies[allCookies.length] = cookies[index];\n if (allCookies.length > 0) response.setHeader(\"Set-Cookie\", allCookies);\n}\n// Every error branch of __velarServeHandleNative answers with a body of its own,\n// so it has to start from an empty header set: a content-length staged for the\n// response that failed makes the client wait for bytes that will never arrive,\n// and a Set-Cookie staged by a handler whose request was never served hands out\n// a session for nothing. The isolated-host transport gets this for free \u2014 it\n// sheds before the host ever sets a header \u2014 so this is the native transport\n// reaching the same state.\n// SV-I1: the listener adapter answers its own refusals in the framework's one\n// wire form, so a static miss reads the same through either transport.\nfunction __velarServeNativeProblem(status, reason, title, path) {\n return __velarJsonStringify(__velarServeProblemDocument(__velarServeProblem(status, reason, title), path === null ? null : {path}));\n}\n\nfunction __velarServeNativeResetHeaders(response) {\n const names = response.getHeaderNames();\n for (let index = 0; index < names.length; index += 1) response.removeHeader(names[index]);\n}\nclass __velarServeNativeNotFound extends __velarServeError {}\nfunction __velarServeNativeMissing(error) {\n const code = error?.code;\n return code === \"ENOENT\" || code === \"ENOTDIR\" || code === \"EISDIR\";\n}\n// A relative path carries .. only as a whole segment, so a bare two-dot prefix\n// test also refuses an ordinary top-level file whose own name begins with two\n// dots \u2014 the same over-strict form the host worker's containment check carried.\n// The operations bag has no separator to consult and may come from a bridge\n// embedding, so both separators are refused: fail closed on Windows rather than\n// trust a default.\nfunction __velarServeNativeEscapes(path, operations) {\n return path === \"..\" || path.startsWith(\"../\") || path.startsWith(\"..\\\\\") || operations.isAbsolute(path);\n}\n// D114 F9-node-cli (audit NO-D1): one root arrives, already settled. This\n// transport used to repeat the privileged host's choice between two candidates\n// by which directory existed, and existence was never identity \u2014 see\n// `staticRoot` in the host worker for the copy of `dist/` that published a\n// stranger's `public/`. `velar/serve` answers who the project directory belongs\n// to once, before any request, and both transports resolve what it decided.\nasync function __velarServeNativeRoot(value, operations) {\n return operations.realpath(operations.resolve(value.root));\n}\nasync function __velarServeNativeFile(value, operations) {\n let root;\n // A static root that does not exist is the same miss as a file that does not\n // exist: reporting it as a failure would answer 500 and write the absolute\n // deployment path to stderr, which the host transport never does.\n try { root = await __velarServeNativeRoot(value, operations); }\n catch (error) { if (__velarServeNativeMissing(error)) throw new __velarServeNativeNotFound(\"fileResponse root does not name a directory\"); throw error; }\n const load = async path => {\n let target;\n try { target = await operations.realpath(operations.resolve(root, path.startsWith(\"/\") ? \".\" + path : path)); }\n catch (error) { if (__velarServeNativeMissing(error)) throw new __velarServeNativeNotFound(\"fileResponse path does not name a file\"); throw error; }\n const relative = operations.relative(root, target);\n if (__velarServeNativeEscapes(relative, operations)) throw new __velarServeNativeNotFound(\"fileResponse path escapes its root\");\n let info;\n try { info = await operations.stat(target); }\n catch (error) { if (__velarServeNativeMissing(error)) throw new __velarServeNativeNotFound(\"fileResponse path does not name a file\"); throw error; }\n if (!info.isFile()) throw new __velarServeNativeNotFound(\"fileResponse path does not name a file\");\n if (info.size > 64 * 1024 * 1024) throw new __velarServeRangeError(\"fileResponse file exceeds 64 MiB\");\n return {target, info};\n };\n try { return await load(value.path); } catch (error) { if (value.fallback === null) throw error; return load(value.fallback); }\n}\nfunction __velarServeNativeContentType(path, operations) {\n if (typeof operations.extname !== \"function\") return \"application/octet-stream\";\n const extension = operations.extname(path).toLowerCase();\n return ({\".css\":\"text/css; charset=utf-8\",\".gif\":\"image/gif\",\".html\":\"text/html; charset=utf-8\",\".ico\":\"image/x-icon\",\".jpeg\":\"image/jpeg\",\".jpg\":\"image/jpeg\",\".js\":\"text/javascript; charset=utf-8\",\".json\":\"application/json; charset=utf-8\",\".map\":\"application/json; charset=utf-8\",\".mjs\":\"text/javascript; charset=utf-8\",\".png\":\"image/png\",\".svg\":\"image/svg+xml\",\".txt\":\"text/plain; charset=utf-8\",\".wasm\":\"application/wasm\",\".webp\":\"image/webp\",\".woff\":\"font/woff\",\".woff2\":\"font/woff2\"})[extension] ?? \"application/octet-stream\";\n}\nasync function __velarServeNativeSendFile(request, response, value, operations, path = null) {\n const file = await __velarServeNativeFile(value, operations);\n const modified = __velarServeCall(__velarServeMathFloor, __velarServeMath, [file.info.mtimeMs]);\n const etag = 'W/\"' + __velarServeCall(__velarServeNumberToString, file.info.size, [16]) + \"-\" + __velarServeCall(__velarServeNumberToString, modified, [16]) + '\"';\n response.setHeader(\"content-type\", __velarServeNativeContentType(file.target, operations));\n response.setHeader(\"accept-ranges\", \"bytes\");\n response.setHeader(\"etag\", etag);\n response.setHeader(\"last-modified\", file.info.mtime.toUTCString());\n const noneMatch = request.headers[\"if-none-match\"];\n const modifiedSince = request.headers[\"if-modified-since\"];\n if (typeof noneMatch === \"string\" && noneMatch.split(\",\").some(item => item.trim() === \"*\" || item.trim() === etag)\n || typeof noneMatch !== \"string\" && typeof modifiedSince === \"string\" && __velarServeCall(__velarServeNumberIsFinite, __velarServeNumber, [__velarServeCall(__velarServeDateParse, __velarServeDate, [modifiedSince])])\n && __velarServeCall(__velarServeMathFloor, __velarServeMath, [file.info.mtimeMs / 1000]) * 1000 <= __velarServeCall(__velarServeDateParse, __velarServeDate, [modifiedSince])) {\n response.statusCode = 304;\n return __velarServeNativeEnd(response);\n }\n let start = 0;\n let end = file.info.size - 1;\n let range = request.headers.range;\n const ifRange = request.headers[\"if-range\"];\n if (typeof range === \"string\" && typeof ifRange === \"string\" && ifRange !== etag) {\n const time = __velarServeCall(__velarServeDateParse, __velarServeDate, [ifRange]);\n if (!__velarServeCall(__velarServeNumberIsFinite, __velarServeNumber, [time]) || __velarServeCall(__velarServeMathFloor, __velarServeMath, [file.info.mtimeMs / 1000]) * 1000 > time) range = undefined;\n }\n if (typeof range === \"string\") {\n const match = /^bytes=(\\d*)-(\\d*)$/u.exec(range.trim());\n if (!match || match[1] === \"\" && match[2] === \"\" || file.info.size === 0) {\n response.statusCode = 416; response.setHeader(\"content-range\", \"bytes */\" + file.info.size); response.setHeader(\"content-type\", \"application/problem+json; charset=utf-8\"); return __velarServeNativeEnd(response, request.method === \"HEAD\" ? undefined : __velarServeNativeProblem(416, \"static.range_not_satisfiable\", \"Range not satisfiable\", path));\n }\n if (match[1] === \"\") { const suffix = __velarServeCall(__velarServeNumber, undefined, [match[2]]); if (!__velarServeCall(__velarServeNumberIsSafeInteger, __velarServeNumber, [suffix]) || suffix < 1) { response.statusCode = 416; response.setHeader(\"content-range\", \"bytes */\" + file.info.size); return __velarServeNativeEnd(response); } start = __velarServeCall(__velarServeMathMax, __velarServeMath, [0, file.info.size - suffix]); }\n else { start = __velarServeCall(__velarServeNumber, undefined, [match[1]]); end = match[2] === \"\" ? end : __velarServeCall(__velarServeNumber, undefined, [match[2]]); }\n if (!__velarServeCall(__velarServeNumberIsSafeInteger, __velarServeNumber, [start]) || !__velarServeCall(__velarServeNumberIsSafeInteger, __velarServeNumber, [end]) || start < 0 || start >= file.info.size || end < start) { response.statusCode = 416; response.setHeader(\"content-range\", \"bytes */\" + file.info.size); return __velarServeNativeEnd(response); }\n if (end >= file.info.size) end = file.info.size - 1;\n response.statusCode = 206;\n response.setHeader(\"content-range\", \"bytes \" + start + \"-\" + end + \"/\" + file.info.size);\n } else response.statusCode = 200;\n response.setHeader(\"content-length\", __velarServeCall(__velarServeMathMax, __velarServeMath, [0, end - start + 1]));\n if (request.method === \"HEAD\") return __velarServeNativeEnd(response);\n if (typeof operations.createReadStream !== \"function\") {\n const data = await operations.readFile(file.target);\n if (!(data instanceof __velarServeUint8Array) || data.byteLength > 64 * 1024 * 1024) throw new __velarServeRangeError(\"fileResponse file exceeds 64 MiB\");\n return __velarServeWithOutbound(end - start + 1, () => __velarServeNativeEnd(response, data.subarray(start, end + 1)));\n }\n const source = operations.createReadStream(file.target, {start, end, highWaterMark: 64 * 1024});\n try { for await (const chunk of source) await __velarServeWithOutbound(chunk.byteLength, () => __velarServeNativeWrite(response, chunk)); }\n finally { source.destroy(); }\n return __velarServeNativeEnd(response);\n}\nasync function __velarServeNativeEnd(response, value) { await new __velarServePromise((resolve, reject) => { response.once(\"error\", reject); response.end(value, () => { response.off(\"error\", reject); resolve(null); }); }); }\nasync function __velarServeNativeWrite(response, value) { if (response.write(value)) return; await new __velarServePromise((resolve, reject) => { const failed = error => { response.off(\"drain\", ready); reject(error); }; const ready = () => { response.off(\"error\", failed); resolve(null); }; response.once(\"error\", failed); response.once(\"drain\", ready); }); }\nasync function __velarServeNativeBody(response, value, checked, suppressBody, operations) {\n if (suppressBody) return __velarServeNativeEnd(response);\n const bytes = typeof value === \"string\" ? __velarUtf8ByteLength(value) : value.byteLength;\n if (checked.compression == null || typeof operations.compress !== \"function\") return __velarServeWithOutbound(bytes, () => __velarServeNativeEnd(response, value));\n const compressed = await __velarServeWithOutbound(bytes * 2, () => operations.compress(checked.compression, value));\n if (!(compressed instanceof __velarServeUint8Array) || compressed.byteLength > __velarServeMaxBodyBytes) throw new __velarServeRangeError(\"Compressed ServeResponse exceeds 16 MiB\");\n response.setHeader(\"content-encoding\", checked.compression);\n if (!response.hasHeader(\"vary\")) response.setHeader(\"vary\", \"Accept-Encoding\");\n return __velarServeWithOutbound(compressed.byteLength, () => __velarServeNativeEnd(response, compressed));\n}\nasync function __velarServeHandleNative(handler, request, response, operations, maxBodyBytes = __velarServeMaxBodyBytes) {\n let cleanup = null;\n let backgroundTasks = null;\n let incoming = null;\n let disconnected = null;\n try {\n incoming = __velarServeNativeRequest(request, maxBodyBytes);\n disconnected = () => { if (!response.writableFinished) __velarServeCancellation.__velarCancel(incoming.cancellation, \"client_disconnect\"); };\n request.once(\"aborted\", disconnected);\n response.once(\"close\", disconnected);\n let value = await handler(incoming.request);\n const managed = value && typeof value === \"object\" ? __velarServeOwnDescriptor(value, __velarServeManagedResponseMarker) : null;\n if (managed?.enumerable === true && \"value\" in managed && managed.value === true) { cleanup = value.cleanup; value = value.response; }\n if (__velarServeIsFileResponse(value)) { __velarServeNativeSetHeaders(response, __velarServeResponseHeaders(value.headers)); await __velarServeNativeSendFile(request, response, value, operations, incoming.request.path); return null; }\n const checked = __velarServeResponse(value); backgroundTasks = checked.background ?? null; response.statusCode = checked.status; __velarServeNativeSetHeaders(response, __velarServeResponseHeaders(checked.headers), __velarServeCookies(checked));\n const suppressBody = request.method === \"HEAD\" || checked.status >= 100 && checked.status < 200 || checked.status === 204 || checked.status === 304;\n if (__velarServeOwnDescriptor(checked, \"json\")) { if (request.method === \"HEAD\" || !suppressBody) response.setHeader(\"content-type\", checked.contentType ?? \"application/json; charset=utf-8\"); await __velarServeNativeBody(response, __velarServeCall(__velarServeWeakMapGet, __velarServeSerializedJson, [checked]), checked, suppressBody, operations); return null; }\n if (__velarServeOwnDescriptor(checked, \"text\")) { if (request.method === \"HEAD\" || !suppressBody) response.setHeader(\"content-type\", checked.contentType ?? \"text/plain; charset=utf-8\"); await __velarServeNativeBody(response, checked.text, checked, suppressBody, operations); return null; }\n let writing = false;\n const write = async chunk => { if (writing) throw new __velarServeError(\"ServeResponse allows only one active stream write\"); writing = true; try { if (typeof chunk !== \"string\" || __velarUtf8ByteLength(chunk) > 1024 * 1024) throw new __velarServeTypeError(\"ServeResponse.stream chunks must be text of at most 1 MiB\"); if (!suppressBody) await __velarServeWithOutbound(__velarUtf8ByteLength(chunk), () => __velarServeNativeWrite(response, chunk)); return null; } finally { writing = false; } };\n const result = await checked.stream(write); if (result !== null) throw new __velarServeTypeError(\"ServeResponse.stream producer must resolve to null\"); if (writing) throw new __velarServeError(\"ServeResponse stream producer returned before its write completed\"); await __velarServeNativeEnd(response); return null;\n } catch (error) {\n if (error instanceof RequestBodyTooLargeError && !response.headersSent) {\n __velarServeNativeResetHeaders(response);\n response.statusCode = 413;\n response.setHeader(\"content-type\", \"application/json; charset=utf-8\");\n response.end(request.method === \"HEAD\" ? undefined : '{\"error\":\"request_too_large\"}');\n return null;\n }\n if (error instanceof __velarServeNativeNotFound && !response.headersSent) {\n // SV-I1: the two transports answer a static miss with one wire form.\n __velarServeNativeResetHeaders(response);\n response.statusCode = 404;\n response.setHeader(\"content-type\", \"application/problem+json; charset=utf-8\");\n response.end(request.method === \"HEAD\" ? undefined : __velarServeNativeProblem(404, \"static.not_found\", \"Not found\", incoming === null ? null : incoming.request.path));\n return null;\n }\n if (error instanceof __velarServeOutboundBudgetError && !response.headersSent) {\n __velarServeNativeResetHeaders(response);\n response.statusCode = 503;\n response.setHeader(\"retry-after\", \"1\");\n response.setHeader(\"content-type\", \"application/json; charset=utf-8\");\n response.end(request.method === \"HEAD\" ? undefined : '{\"error\":\"outbound_budget_exhausted\"}');\n return null;\n }\n __velarServeReportFailure(error);\n if (!response.headersSent) { __velarServeNativeResetHeaders(response); response.statusCode = 500; response.setHeader(\"content-type\", \"application/problem+json; charset=utf-8\"); response.end(__velarServeNativeProblem(500, \"server.internal\", \"Internal server error\", incoming === null ? null : incoming.request.path)); }\n else response.destroy();\n return null;\n }\n finally {\n if (disconnected !== null) { request.off(\"aborted\", disconnected); response.off(\"close\", disconnected); }\n await __velarServeRunBackground(backgroundTasks);\n if (typeof cleanup === \"function\") { try { await cleanup(); } catch (error) { __velarServeReportFailure(error); } }\n if (incoming !== null) incoming.cleanup();\n }\n}"; /** * The `velar/server-test` client, its own file so that both halves of * `velar/serve` stay inside D115 §一.1's reading budget. It is one contiguous * region of the emitted `velar/serve` module — `velar/server-test` reaches it * through `ServeApp.__velarCompilerBridge.testClient` — composed back at exactly * the position it occupied. */ export declare const VELAR_NODE_SERVE_TEST_RUNTIME = "function __velarServeTestOverrides(value) {\n if (value == null) return new __velarServeMap();\n let size;\n let iterator;\n try { size = __velarServeCall(__velarServeMapSize, value, []); iterator = __velarServeCall(__velarServeMapEntries, value, []); }\n catch { throw new __velarServeTypeError(\"server-test overrides must be a Map\"); }\n if (!__velarServeIsSafeInteger(size) || size < 0 || size > 128) throw new __velarServeRangeError(\"server-test overrides cannot contain more than 128 providers\");\n const output = new __velarServeMap();\n while (true) {\n const step = __velarServeCall(__velarServeMapIteratorNext, iterator, []);\n if (step.done) break;\n if (!__velarServeIsArray(step.value) || step.value.length !== 2 || !__velarServeIsProvider(step.value[0])) throw new __velarServeTypeError(\"server-test override keys must be Providers\");\n __velarServeCall(__velarServeMapSet, output, [step.value[0], step.value[1]]);\n }\n return output;\n}\n\nfunction __velarServeTestHeaders(value) {\n if (value == null) return new __velarServeMap();\n const pairs = __velarServeMapSnapshot(value, \"server-test headers\");\n const output = new __velarServeMap();\n for (let index = 0; index < pairs.length; index += 1) __velarServeCall(__velarServeMapSet, output, [__velarServeCall(__velarServeStringToLowerCase, pairs[index][0], []), pairs[index][1]]);\n return output;\n}\n\nfunction __velarServeTestUploadEntries(value) {\n if (value == null) return [];\n let size;\n let iterator;\n try { size = __velarServeCall(__velarServeMapSize, value, []); iterator = __velarServeCall(__velarServeMapEntries, value, []); }\n catch { throw new __velarServeTypeError(\"server-test files must be a Map\"); }\n if (!__velarServeIsSafeInteger(size) || size < 0 || size > 128) throw new __velarServeRangeError(\"server-test files cannot contain more than 128 uploads\");\n const output = [];\n while (true) {\n const step = __velarServeCall(__velarServeMapIteratorNext, iterator, []);\n if (step.done) break;\n if (!__velarServeIsArray(step.value) || step.value.length !== 2) throw new __velarServeTypeError(\"server-test files must be a Map\");\n const field = step.value[0];\n const file = __velarServeRecord(step.value[1], __velarServeTestUploadFields, \"server-test upload\");\n if (typeof field !== \"string\" || field.length === 0 || field.length > 256 || /[\\0\\r\\n\"]/u.test(field)\n || typeof file.filename !== \"string\" || file.filename.length === 0 || file.filename.length > 1024 || /[\\0\\r\\n\"]/u.test(file.filename)\n || file.contentType !== undefined && (typeof file.contentType !== \"string\" || file.contentType.length === 0 || file.contentType.length > 1024 || /[\\0\\r\\n]/u.test(file.contentType))) {\n throw new __velarServeTypeError(\"server-test upload names and content types must be bounded HTTP text\");\n }\n const data = typeof file.data === \"string\"\n ? __velarServeCall(__velarServeTextEncode, __velarServeUtf8Encoder, [file.data])\n : __velarServeBytesType.parse(file.data);\n output[output.length] = {field, filename: file.filename, contentType: file.contentType ?? \"application/octet-stream\", data};\n }\n if (output.length !== size) throw new __velarServeTypeError(\"server-test files changed while they were being read\");\n return output;\n}\n\nfunction __velarServeBytesContain(source, pattern) {\n if (pattern.byteLength === 0 || pattern.byteLength > source.byteLength) return false;\n for (let offset = 0; offset <= source.byteLength - pattern.byteLength; offset += 1) {\n let equal = true;\n for (let index = 0; index < pattern.byteLength; index += 1) if (source[offset + index] !== pattern[index]) { equal = false; break; }\n if (equal) return true;\n }\n return false;\n}\n\nfunction __velarServeTestMultipart(form, files) {\n const fields = form == null ? [] : __velarServeMapSnapshot(form, \"server-test form\", 256);\n for (let index = 0; index < fields.length; index += 1) if (fields[index][0].length === 0 || /[\\0\\r\\n\"]/u.test(fields[index][0])) throw new __velarServeTypeError(\"server-test form field names must be bounded HTTP text\");\n const uploads = __velarServeTestUploadEntries(files);\n const values = [];\n for (let index = 0; index < fields.length; index += 1) values[values.length] = __velarServeCall(__velarServeTextEncode, __velarServeUtf8Encoder, [fields[index][1]]);\n for (let index = 0; index < uploads.length; index += 1) values[values.length] = uploads[index].data;\n let boundary = null;\n for (let attempt = 0; attempt < 32; attempt += 1) {\n if (!__velarServeIsSafeInteger(__velarServeNextTestBoundary)) __velarServeNextTestBoundary = 1;\n const candidate = \"velar-test-\" + __velarServeCall(__velarServeDateNow, __velarServeDate, []) + \"-\" + __velarServeNextTestBoundary++;\n const encoded = __velarServeCall(__velarServeTextEncode, __velarServeUtf8Encoder, [candidate]);\n let collision = false;\n for (let index = 0; index < values.length; index += 1) if (__velarServeBytesContain(values[index], encoded)) { collision = true; break; }\n if (!collision) { boundary = candidate; break; }\n }\n if (boundary === null) throw new __velarServeRangeError(\"server-test could not choose a collision-free multipart boundary\");\n const parts = [];\n let total = 0;\n const appendText = text => { const data = __velarServeCall(__velarServeTextEncode, __velarServeUtf8Encoder, [text]); total += data.byteLength; parts[parts.length] = data; };\n const appendData = data => { total += data.byteLength; parts[parts.length] = data; };\n for (let index = 0; index < fields.length; index += 1) {\n appendText(\"--\" + boundary + \"\\r\\nContent-Disposition: form-data; name=\\\"\" + fields[index][0] + \"\\\"\\r\\n\\r\\n\");\n appendData(values[index]);\n appendText(\"\\r\\n\");\n }\n for (let index = 0; index < uploads.length; index += 1) {\n const upload = uploads[index];\n appendText(\"--\" + boundary + \"\\r\\nContent-Disposition: form-data; name=\\\"\" + upload.field + \"\\\"; filename=\\\"\" + upload.filename + \"\\\"\\r\\nContent-Type: \" + upload.contentType + \"\\r\\n\\r\\n\");\n appendData(upload.data);\n appendText(\"\\r\\n\");\n }\n appendText(\"--\" + boundary + \"--\\r\\n\");\n if (total > __velarServeMaxBodyBytes) throw new __velarServeRangeError(\"server-test multipart body exceeds 16 MiB\");\n const data = new __velarServeUint8Array(total);\n let offset = 0;\n for (let index = 0; index < parts.length; index += 1) { __velarServeCall(__velarServeUint8Set, data, [parts[index], offset]); offset += parts[index].byteLength; }\n return {data, contentType: \"multipart/form-data; boundary=\" + boundary};\n}\n\nfunction __velarServeTestRequest(method, target, options, cookies) {\n if (typeof method !== \"string\" || !__velarServeCall(__velarServeRegExpTest, __velarServeMethodPattern, [method])) throw new __velarServeTypeError(\"server-test method is invalid\");\n if (typeof target !== \"string\" || target.length === 0 || __velarUtf8ByteLength(target) > 64 * 1024 || !__velarServeCall(__velarServeStringStartsWith, target, [\"/\"])) throw new __velarServeTypeError(\"server-test target must be a bounded absolute URL path\");\n options = options == null ? {} : __velarServePlainRecord(options, \"server-test request options\");\n const keys = __velarServeCall(__velarServeOwnKeys, __velarServeReflect, [options]);\n for (let index = 0; index < keys.length; index += 1) if (!__velarServeCall(__velarServeArrayIncludes, [\"headers\", \"json\", \"text\", \"form\", \"files\"], [keys[index]])) throw new __velarServeTypeError(\"server-test request options have an unknown field\");\n const structuredBody = __velarServeOwnDescriptor(options, \"form\") || __velarServeOwnDescriptor(options, \"files\");\n if ((__velarServeOwnDescriptor(options, \"json\") ? 1 : 0) + (__velarServeOwnDescriptor(options, \"text\") ? 1 : 0) + (structuredBody ? 1 : 0) > 1) throw new __velarServeTypeError(\"server-test request accepts one body source: json, text, or form/files\");\n const targetParts = __velarServeTargetParts(target, \"server-test target\");\n const path = targetParts.path;\n const query = __velarServePairsMaps(targetParts.query, \"server-test query\");\n const headers = __velarServeTestHeaders(options.headers);\n if (!__velarServeCall(__velarServeMapHas, headers, [\"cookie\"]) && __velarServeCall(__velarServeMapSize, cookies, []) > 0) {\n const values = [];\n const iterator = __velarServeCall(__velarServeMapEntries, cookies, []);\n while (true) { const step = __velarServeCall(__velarServeMapIteratorNext, iterator, []); if (step.done) break; values[values.length] = step.value[0] + \"=\" + step.value[1]; }\n __velarServeCall(__velarServeMapSet, headers, [\"cookie\", __velarServeCall(__velarServeArrayJoin, values, [\"; \"])]);\n }\n let bodyText = \"\";\n let bodyData = __velarServeCall(__velarServeTextEncode, __velarServeUtf8Encoder, [bodyText]);\n if (__velarServeOwnDescriptor(options, \"json\")) {\n bodyText = __velarJsonStringify(options.json);\n if (!__velarServeCall(__velarServeMapHas, headers, [\"content-type\"])) __velarServeCall(__velarServeMapSet, headers, [\"content-type\", \"application/json\"]);\n } else if (__velarServeOwnDescriptor(options, \"text\")) {\n if (typeof options.text !== \"string\") throw new __velarServeTypeError(\"server-test text body must be string\");\n bodyText = options.text;\n } else if (structuredBody) {\n const multipart = __velarServeTestMultipart(options.form, options.files);\n bodyData = multipart.data;\n __velarServeCall(__velarServeMapSet, headers, [\"content-type\", multipart.contentType]);\n }\n if (__velarUtf8ByteLength(bodyText) > __velarServeMaxBodyBytes) throw new __velarServeRangeError(\"server-test request body exceeds 16 MiB\");\n if (!structuredBody) bodyData = __velarServeCall(__velarServeTextEncode, __velarServeUtf8Encoder, [bodyText]);\n const bytes = async maxBytes => {\n const maximum = maxBytes ?? __velarServeMaxBodyBytes;\n if (!__velarServeIsSafeInteger(maximum) || maximum < 1 || maximum > __velarServeMaxBodyBytes || bodyData.byteLength > maximum) throw new RequestBodyTooLargeError(maximum);\n return bodyData;\n };\n const textBody = async maxBytes => { const data = await bytes(maxBytes); if (!structuredBody) return bodyText; try { return __velarServeCall(__velarServeTextDecode, __velarServeUtf8Decoder, [data]); } catch { throw new __velarServeTypeError(\"server-test request body is not UTF-8 text\"); } };\n const jsonBody = async maxBytes => __velarJsonParse(await textBody(maxBytes), \"server-test JSON text\");\n const cancellation = __velarServeCancellation.__velarCreate();\n return __velarServeCall(__velarServeObjectFreeze, __velarServeObject, [{\n method, path, query: query.values, queryAll: query.all, headers, cancellation, text: textBody, bytes, json: jsonBody,\n parse: async (Type, maxBytes = __velarServeMaxBodyBytes) => { Type = __velarRequireRuntimeType(Type, \"server-test request parse\"); return Type.parse(await jsonBody(maxBytes)); },\n }]);\n}\n\nasync function __velarServeTestResponse(value, cookies) {\n let cleanup = null;\n const managed = value && typeof value === \"object\" ? __velarServeOwnDescriptor(value, __velarServeManagedResponseMarker) : null;\n if (managed?.enumerable === true && \"value\" in managed && managed.value === true) { cleanup = value.cleanup; value = value.response; }\n let backgroundTasks = null;\n try {\n if (__velarServeIsFileResponse(value)) {\n const loaded = __velarServeRecord(await __velarNodeHostInvoke(\"serve.readFile\", [value.root, value.path, value.fallback]), __velarServeTestFileFields, \"server-test file result\");\n if (!__velarServeBytesType.is(loaded.data) || loaded.data.byteLength > __velarServeMaxBodyBytes || typeof loaded.contentType !== \"string\" || loaded.contentType.length === 0 || loaded.contentType.length > 1024 || /[\\0\\r\\n]/u.test(loaded.contentType)) {\n throw new __velarServeTypeError(\"Node host returned an invalid server-test file result\");\n }\n const headers = __velarServeHeaders(value.headers, \"content-type\", loaded.contentType);\n let textValue = null;\n const readText = async () => {\n if (textValue === null) {\n try { textValue = __velarServeCall(__velarServeTextDecode, __velarServeUtf8Decoder, [loaded.data]); }\n catch { throw new __velarServeTypeError(\"server-test file response is not UTF-8 text\"); }\n }\n return textValue;\n };\n return __velarServeCall(__velarServeObjectFreeze, __velarServeObject, [{status: 200, headers, text: readText, json: async () => __velarJsonParse(await readText(), \"server-test file response JSON\")}]);\n }\n const response = __velarServeResponse(value);\n backgroundTasks = response.background ?? null;\n const headers = __velarServeHeaders(response.headers);\n const checkedCookies = __velarServeCookies(response);\n const responseCookies = [];\n for (let index = 0; index < checkedCookies.length; index += 1) responseCookies[index] = checkedCookies[index];\n if (__velarServeCall(__velarServeMapHas, headers, [\"set-cookie\"])) responseCookies[responseCookies.length] = __velarServeCall(__velarServeMapGet, headers, [\"set-cookie\"]);\n for (let cookieIndex = 0; cookieIndex < responseCookies.length; cookieIndex += 1) {\n const cookie = responseCookies[cookieIndex];\n const first = __velarServeCall(__velarServeStringSplit, cookie, [\";\"])[0];\n const separator = __velarServeCall(__velarServeStringIndexOf, first, [\"=\"]);\n if (separator > 0) {\n const name = __velarServeCall(__velarServeStringSlice, first, [0, separator]);\n const content = __velarServeCall(__velarServeStringSlice, first, [separator + 1]);\n if (__velarServeCall(__velarServeStringIncludes, __velarServeCall(__velarServeStringToLowerCase, cookie, []), [\"max-age=0\"])) __velarServeCall(__velarServeMapDelete, cookies, [name]);\n else __velarServeCall(__velarServeMapSet, cookies, [name, content]);\n }\n }\n let jsonValue = __velarServeMissing;\n let textValue = \"\";\n if (__velarServeOwnDescriptor(response, \"json\")) {\n jsonValue = response.json;\n textValue = __velarServeCall(__velarServeWeakMapGet, __velarServeSerializedJson, [response]);\n }\n else if (__velarServeOwnDescriptor(response, \"text\")) textValue = response.text;\n else {\n const chunks = [];\n let size = 0;\n const result = await response.stream(async chunk => { if (typeof chunk !== \"string\") throw new __velarServeTypeError(\"server-test stream chunks must be strings\"); size += __velarUtf8ByteLength(chunk); if (size > __velarServeMaxBodyBytes) throw new __velarServeRangeError(\"server-test response exceeds 16 MiB\"); chunks[chunks.length] = chunk; return null; });\n if (result !== null) throw new __velarServeTypeError(\"ServeResponse.stream producer must resolve to null\");\n textValue = __velarServeCall(__velarServeArrayJoin, chunks, [\"\"]);\n }\n return __velarServeCall(__velarServeObjectFreeze, __velarServeObject, [{\n status: response.status,\n headers,\n text: async () => textValue,\n json: async () => jsonValue === __velarServeMissing ? __velarJsonParse(textValue, \"server-test response JSON\") : jsonValue,\n }]);\n } finally {\n try {\n await __velarServeRunBackground(backgroundTasks);\n } finally {\n if (typeof cleanup === \"function\") await cleanup();\n }\n }\n}\n\nasync function __velarServeTestClient(app, overrides = null) {\n if (!__velarServeIsApp(app)) throw new __velarServeTypeError(\"server-test client requires a ServeApp\");\n const appState = __velarServeAppState(app, __velarServeTestOverrides(overrides));\n const cookies = new __velarServeMap();\n let closing = null;\n let closed = null;\n try { await __velarServeRunStartup(app, appState); await __velarServeInitializeEagerProviders(app, __velarServeMaxBodyBytes, appState); }\n catch (error) { try { await __velarServeCleanupAppState(appState); } catch {} try { await __velarServeRunShutdown(app, appState); } catch {} throw error; }\n const request = async (method, target, options = null) => {\n if (closed !== null || closing !== null) throw new __velarServeError(\"server-test client is closed\");\n const incoming = __velarServeTestRequest(method, target, options, cookies);\n return await __velarServeTestResponse(await __velarServeHandleApp(app, incoming, __velarServeMaxBodyBytes, appState), cookies);\n };\n const close = async (grace = __velarServeDefaultShutdownGrace) => {\n if (closed !== null) return closed;\n if (closing !== null) return closing;\n const pending = (async () => {\n try { await __velarServeDrainAppState(appState, grace); }\n catch (error) {\n closed = __velarServeFinishAppAfterDrain(app, appState);\n __velarServeCall(__velarServePromiseThen, closed, [() => null, failure => __velarServeReportFailure(failure)]);\n throw error;\n }\n closed = __velarServeFinishApp(app, appState);\n return await closed;\n })();\n closing = pending;\n try { return await pending; }\n finally { if (closing === pending) closing = null; }\n };\n return __velarServeCall(__velarServeObjectFreeze, __velarServeObject, [{\n request,\n get: (target, options = null) => request(\"GET\", target, options),\n post: (target, options = null) => request(\"POST\", target, options),\n put: (target, options = null) => request(\"PUT\", target, options),\n patch: (target, options = null) => request(\"PATCH\", target, options),\n delete: (target, options = null) => request(\"DELETE\", target, options),\n close,\n }]);\n}"; /** * `velar/serve` above the route-shape rule it closes over. The application-facing * contract: HTTP sockets, request streams, backpressure and static-file effects * live in the shared isolated Node host, and this Realm owns only Velar values, * handlers and strict JSON/type boundaries. */ export declare const VELAR_NODE_SERVE_PREFIX: string; /** `velar/serve` below the route-shape rule: routing, the listener, the test client. */ export declare const VELAR_NODE_SERVE_BODY: string; /** `velar/server-test` — the test client, reached through the serve bridge. */ export declare const VELAR_NODE_SERVER_TEST_MODULE_SOURCE = "import { ServeApp as __velarServerTestApp } from \"velar/serve\";\nconst __velarServerTestBridge = __velarServerTestApp.__velarCompilerBridge;\nexport async function client(app, overrides = null) { return await __velarServerTestBridge.testClient(app, overrides); }\nexport const TestClient = Object.freeze({is(value) { return !!value && typeof value === \"object\" && typeof value.request === \"function\" && typeof value.close === \"function\"; }, parse(value) { if (!TestClient.is(value)) throw new TypeError(\"Value does not match TestClient\"); return value; }});\nexport const TestResponse = Object.freeze({is(value) { return !!value && typeof value === \"object\" && Number.isSafeInteger(value.status) && typeof value.text === \"function\" && typeof value.json === \"function\"; }, parse(value) { if (!TestResponse.is(value)) throw new TypeError(\"Value does not match TestResponse\"); return value; }});\n"; /** * Owns the inherited stdin handle and forwards it to the worker over IPC. The * last record it sends is the one the worker waits for, so it must survive the * channel teardown that follows it. */ export declare const VELAR_NODE_TERMINAL_INPUT_SOURCE = "process.stdin.pause();\nprocess.on(\"error\", () => process.exit(0));\nconst send = value => {\n if (process.connected && typeof process.send === \"function\") {\n process.send(value, error => { if (error) process.exit(0); });\n }\n};\n// process.disconnect() discards every record the channel has accepted but not\n// yet written, so the terminating record and the input queued ahead of it are\n// flushed first. Disconnecting in the same turn as the send dropped both, and\n// the worker then saw a host that exited cleanly without ever ending its input.\nlet finished = false;\nconst finish = value => {\n if (finished) return;\n finished = true;\n if (!process.connected || typeof process.send !== \"function\") { process.exit(0); return; }\n process.send(value, error => { if (error) process.exit(0); else process.disconnect(); });\n};\nprocess.stdin.on(\"data\", data => send({kind: \"input-data\", data}));\nprocess.stdin.on(\"end\", () => finish({kind: \"input-end\"}));\nprocess.stdin.on(\"error\", () => finish({kind: \"input-error\"}));\nprocess.on(\"message\", value => {\n if (!value || typeof value !== \"object\") return;\n if (value.kind === \"input-state\" && typeof value.active === \"boolean\") {\n if (value.active) process.stdin.resume();\n else process.stdin.pause();\n } else if (value.kind === \"close\") {\n process.stdin.pause();\n process.exit(0);\n }\n});\nprocess.on(\"disconnect\", () => process.exit(0));\nsend({kind: \"ready\"});\n"; /** * The isolated terminal host. The Worker never loads application code or * packages; an on-demand child owns the inherited stdin handle so a blocking * pipe read is cancellable without exposing application-Realm stream prototypes. */ export declare const VELAR_NODE_TERMINAL_WORKER_SOURCE: string; /** * The application-facing proxy for the isolated terminal host, carrying that * host's source as the string it constructs it from. It captures all validation, * MessagePort and Worker operations before application code runs; stdin * ownership, decoding, and fd writes live in the worker. */ export declare const VELAR_NODE_TERMINAL_RUNTIME: string; /** `velar/terminal` — the terminal proxy over the compiler's UTF-8 runtime. */ export declare const VELAR_NODE_TERMINAL_MODULE_SOURCE: string; /** `velar/websocket` — frames, connections and the upgrade path over `velar/serve`. */ export declare const VELAR_NODE_WEBSOCKET_RUNTIME = "import __VelarWebSocket, { WebSocketServer as __VelarWebSocketServer } from \"ws\";\nimport { createServer as __velarCreateHttpServer } from \"node:http\";\nimport { createReadStream as __velarServeCreateReadStream } from \"node:fs\";\nimport { readFile as __velarServeReadFile, realpath as __velarServeRealpath, stat as __velarServeStat } from \"node:fs/promises\";\nimport { extname as __velarServeExtname, isAbsolute as __velarServeIsAbsolute, relative as __velarServeRelative, resolve as __velarServeResolve } from \"node:path\";\nimport { brotliCompress as __velarServeBrotliNode, gzip as __velarServeGzipNode } from \"node:zlib\";\nimport { promisify as __velarServePromisify } from \"node:util\";\nimport { ServeRequest as __velarServeRuntime, ServeApp as __velarServeApp } from \"velar/serve\";\nimport { onShutdown as __velarWsOnShutdown } from \"velar/host\";\n\nconst __velarWebSocketConnections = new WeakMap();\nconst __velarWebSocketServers = new WeakMap();\nconst __velarWebSocketPreparedRequests = new WeakMap();\nconst __velarWsPromise = globalThis.Promise;\nconst __velarWsPromiseAll = __velarWsPromise.all.bind(__velarWsPromise);\nconst __velarWsReflectApply = globalThis.Reflect.apply;\nconst __velarWsReflectConstruct = globalThis.Reflect.construct;\nconst __velarWsFinalizationRegistry = globalThis.FinalizationRegistry;\nconst __velarWsFinalizerRegister = __velarWsFinalizationRegistry.prototype.register;\nconst __velarWsSetTimeout = globalThis.setTimeout;\nconst __velarWsClearTimeout = globalThis.clearTimeout;\nconst __velarWsArrayIsArray = globalThis.Array.isArray;\nconst __velarWsObjectGetOwnPropertyDescriptor = globalThis.Object.getOwnPropertyDescriptor;\nconst __velarWsObjectFreeze = globalThis.Object.freeze;\nconst __velarWsStringIncludes = globalThis.String.prototype.includes;\nconst __velarWsSet = globalThis.Set;\nconst __velarWsSetHas = __velarWsSet.prototype.has;\nconst __velarWsSetAdd = __velarWsSet.prototype.add;\nconst __velarWsURL = globalThis.URL;\nconst __velarWsURLOriginGet = __velarWsObjectGetOwnPropertyDescriptor(__velarWsURL.prototype, \"origin\").get;\nconst __velarServeGzip = __velarServePromisify(__velarServeGzipNode);\nconst __velarServeBrotli = __velarServePromisify(__velarServeBrotliNode);\nconst __velarWsAggregateByteLimit = 128 * 1024 * 1024;\nconst __velarWsAggregateQueuedMessageLimit = 65536;\nconst __velarWsAggregatePendingSendLimit = 8192;\nconst __velarWsActiveConnectionLimit = 4096;\nconst __velarWsPendingConnectionLimit = 4096;\nlet __velarWsAggregateBytes = 0;\nlet __velarWsAggregateQueuedMessages = 0;\nlet __velarWsAggregatePendingSends = 0;\nlet __velarWsActiveConnections = 0;\nlet __velarWsPendingConnections = 0;\nlet __velarWsActiveHttpSockets = 0;\nconst __velarServeNativeOperations = Object.freeze({readFile: __velarServeReadFile, createReadStream: __velarServeCreateReadStream, realpath: __velarServeRealpath, stat: __velarServeStat, extname: __velarServeExtname, isAbsolute: __velarServeIsAbsolute, relative: __velarServeRelative, resolve: __velarServeResolve, compress: (encoding, value) => encoding === \"br\" ? __velarServeBrotli(value) : __velarServeGzip(value)});\nfunction __velarWsInteger(value, fallback, minimum, maximum, name) { if (value === undefined || value === null) return fallback; if (!Number.isSafeInteger(value) || value < minimum || value > maximum) throw new RangeError(name + \" must be an integer from \" + minimum + \" through \" + maximum); return value; }\nfunction __velarWsDuration(value, fallback) { if (value === undefined || value === null) return fallback; if (typeof value !== \"string\") throw new TypeError(\"WebSocket timeout must be Duration\"); const match = /^([+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+))(ms|s)$/.exec(value); if (!match) throw new TypeError(\"WebSocket timeout must be Duration such as 5s\"); const result = Number(match[1]) * (match[2] === \"s\" ? 1000 : 1); if (!Number.isFinite(result) || result < 0 || result > 2147483647) throw new RangeError(\"WebSocket timeout is outside the supported range\"); return result; }\nfunction __velarWsOption(options, name) { const descriptor = __velarWsObjectGetOwnPropertyDescriptor(options, name); if (descriptor === undefined) return undefined; if (!(\"value\" in descriptor)) throw new TypeError(\"WebSocket option '\" + name + \"' must be a data value\"); return descriptor.value; }\nfunction __velarWsOptions(options = {}) { if (options === null || typeof options !== \"object\" || __velarWsArrayIsArray(options)) throw new TypeError(\"WebSocket options must be a record\"); return { maxMessageBytes: __velarWsInteger(__velarWsOption(options, \"maxMessageBytes\"), 16 * 1024 * 1024, 1, 64 * 1024 * 1024, \"maxMessageBytes\"), maxQueuedMessages: __velarWsInteger(__velarWsOption(options, \"maxQueuedMessages\"), 256, 1, 10000, \"maxQueuedMessages\"), maxQueuedBytes: __velarWsInteger(__velarWsOption(options, \"maxQueuedBytes\"), 16 * 1024 * 1024, 1, 64 * 1024 * 1024, \"maxQueuedBytes\"), maxPendingSendBytes: __velarWsInteger(__velarWsOption(options, \"maxPendingSendBytes\"), 16 * 1024 * 1024, 1, 64 * 1024 * 1024, \"maxPendingSendBytes\") }; }\nfunction __velarWsOrigins(value) {\n if (value === undefined || value === null) value = [];\n if (!__velarWsArrayIsArray(value)) throw new TypeError(\"WebSocket origins must be a List\");\n if (value.length > 256) throw new RangeError(\"WebSocket origins cannot contain more than 256 entries\");\n const exact = new __velarWsSet(); let exactCount = 0; let wildcard = false;\n for (let index = 0; index < value.length; index += 1) {\n const descriptor = __velarWsObjectGetOwnPropertyDescriptor(value, index);\n if (!descriptor?.enumerable || !(\"value\" in descriptor) || typeof descriptor.value !== \"string\") throw new TypeError(\"WebSocket origins must contain enumerable text data values\");\n const origin = descriptor.value;\n if (origin === \"*\") { if (wildcard || exactCount !== 0 || value.length !== 1) throw new TypeError(\"WebSocket origin '*' must be the only whitelist entry\"); wildcard = true; continue; }\n if (origin.length === 0 || origin.length > 2048 || !/^https?:\\/\\//iu.test(origin)) throw new TypeError(\"WebSocket origins must be exact HTTP or HTTPS origins\");\n let normalized;\n try { normalized = __velarWsReflectApply(__velarWsURLOriginGet, __velarWsReflectConstruct(__velarWsURL, [origin]), []); }\n catch { throw new TypeError(\"WebSocket origins must be exact HTTP or HTTPS origins\"); }\n if (normalized !== origin) throw new TypeError(\"WebSocket origins must not contain paths, credentials, queries, fragments, or non-canonical text\");\n if (__velarWsReflectApply(__velarWsSetHas, exact, [origin])) throw new TypeError(\"WebSocket origins cannot contain duplicates\");\n __velarWsReflectApply(__velarWsSetAdd, exact, [origin]); exactCount += 1;\n }\n return __velarWsObjectFreeze({exact, wildcard});\n}\n// The Origin an accepted connection was upgraded from, canonicalized through the\n// same URL origin getter the whitelist is canonicalized with, or null when the\n// client sent none, sent the opaque null a sandboxed document sends, or sent\n// something that is not exactly one HTTP or HTTPS origin. The scheme test is\n// case-insensitive because a scheme is case-insensitive and the origin getter\n// canonicalizes it anyway; a canonical origin that still contains a comma came\n// from a header carrying more than one, which is not an origin at all. This is\n// the only upgrade header Vel code can read: nothing else about the request\n// crosses into the connection.\nfunction __velarWsRequestOrigin(request) {\n const headers = request === null || typeof request !== \"object\" ? undefined : request.headers;\n if (headers === null || typeof headers !== \"object\") return null;\n const descriptor = __velarWsObjectGetOwnPropertyDescriptor(headers, \"origin\");\n if (descriptor === undefined || !(\"value\" in descriptor)) return null;\n const header = descriptor.value;\n if (typeof header !== \"string\" || header.length === 0 || header.length > 2048 || !/^https?:\\/\\//iu.test(header)) return null;\n let origin;\n try { origin = __velarWsReflectApply(__velarWsURLOriginGet, __velarWsReflectConstruct(__velarWsURL, [header]), []); }\n catch { return null; }\n return typeof origin !== \"string\" || origin.length === 0 || /,/u.test(origin) ? null : origin;\n}\nfunction __velarWsBytes(value) { if (value instanceof Uint8Array) { const output = new Uint8Array(value.byteLength); output.set(value); return output; } return null; }\nfunction __velarWsMessageBytes(value) { if (typeof value === \"string\") return Buffer.byteLength(value, \"utf8\"); if (value instanceof Uint8Array) return value.byteLength; throw new TypeError(\"WebSocket.send requires text or Bytes\"); }\nfunction __velarWsSend(connection, message, copyBytes) {\n const state = __velarWebSocketConnections.get(connection);\n if (!state) throw new TypeError(\"WebSocket.send requires a connection\");\n if (state.socket.readyState !== __VelarWebSocket.OPEN) return Promise.reject(new WebSocketClosedError());\n const size = __velarWsMessageBytes(message);\n if (size > state.options.maxMessageBytes) return Promise.reject(new RangeError(\"WebSocket message exceeds maxMessageBytes\"));\n if (state.pendingSendBytes + size > state.options.maxPendingSendBytes || !__velarWsReserveSend(size)) return Promise.reject(new WebSocketBackpressureError());\n let bytes;\n try { bytes = typeof message === \"string\" ? null : copyBytes ? __velarWsBytes(message) : message; }\n catch (error) { __velarWsReleaseSend(size); throw error; }\n state.pendingSendBytes += size;\n return new Promise((resolve, reject) => {\n let completed = false;\n const complete = error => {\n if (completed) return;\n completed = true;\n state.pendingSends.delete(complete);\n state.pendingSendBytes -= size;\n __velarWsReleaseSend(size);\n if (error) reject(new WebSocketClosedError(error.message));\n else resolve(null);\n };\n state.pendingSends.add(complete);\n try { state.socket.send(bytes ?? message, {binary: bytes !== null}, complete); }\n catch (error) { complete(error instanceof Error ? error : new Error(\"WebSocket send failed\")); }\n });\n}\n\n// \u53EA\u4F9B\u5B98\u65B9 realtime \u5355\u5199\u8005\u4F7F\u7528\u7684\u5185\u90E8 ABI\u3002realtime \u5728\u5165\u961F\u65F6\u5DF2\u7ECF\n// \u590D\u5236 Bytes \u5E76\u53D6\u5F97\u552F\u4E00\u6240\u6709\u6743\uFF0C\u56E0\u6B64\u4F20\u8F93\u5C42\u53EF\u4EE5\u76F4\u63A5\u53D1\u9001\u8FD9\u4EFD\u526F\u672C\u3002\n// \u8BE5\u540D\u79F0\u4E0D\u5728\u7F16\u8BD1\u5668\u6A21\u5757\u63A5\u53E3\u4E2D\uFF0CVelarScript \u5E94\u7528\u65E0\u6CD5\u5BFC\u5165\uFF1B\u516C\u5F00 send\n// \u4ECD\u5728\u8C03\u7528\u5F53\u4E0B\u590D\u5236 Bytes\uFF0C\u4FDD\u6301\u539F\u6709\u7684\u9632\u7BE1\u6539\u8BED\u4E49\u3002\nexport function __velarWebSocketSendOwned(connection, message) { return __velarWsSend(connection, message, false); }\nfunction __velarWsReserve(size) { if (!Number.isSafeInteger(size) || size < 0 || __velarWsAggregateBytes + size > __velarWsAggregateByteLimit) return false; __velarWsAggregateBytes += size; return true; }\nfunction __velarWsRelease(size) { __velarWsAggregateBytes -= size; if (__velarWsAggregateBytes < 0) __velarWsAggregateBytes = 0; }\nfunction __velarWsReserveQueue(size) { if (__velarWsAggregateQueuedMessages >= __velarWsAggregateQueuedMessageLimit || !__velarWsReserve(size)) return false; __velarWsAggregateQueuedMessages += 1; return true; }\nfunction __velarWsReleaseQueue(size, count = 1) { __velarWsRelease(size); __velarWsAggregateQueuedMessages -= count; if (__velarWsAggregateQueuedMessages < 0) __velarWsAggregateQueuedMessages = 0; }\nfunction __velarWsReserveSend(size) { if (__velarWsAggregatePendingSends >= __velarWsAggregatePendingSendLimit || !__velarWsReserve(size)) return false; __velarWsAggregatePendingSends += 1; return true; }\nfunction __velarWsReleaseSend(size) { __velarWsRelease(size); __velarWsAggregatePendingSends -= 1; if (__velarWsAggregatePendingSends < 0) __velarWsAggregatePendingSends = 0; }\nfunction __velarWsReleaseActive(state) { if (!state.active) return; state.active = false; __velarWsActiveConnections -= 1; if (__velarWsActiveConnections < 0) __velarWsActiveConnections = 0; }\nfunction __velarWsDiscardQueue(state) { if (state.queueReleased) return; state.queueReleased = true; __velarWsReleaseQueue(state.queuedBytes, state.queue.length); state.queue.length = 0; state.queuedBytes = 0; }\nexport class WebSocketBackpressureError extends Error { constructor(message = \"WebSocket backpressure limit exceeded\") { super(message); this.name = \"WebSocketBackpressureError\"; } }\nexport class WebSocketClosedError extends Error { constructor(message = \"WebSocket is closed\") { super(message); this.name = \"WebSocketClosedError\"; } }\nexport class WebSocketProtocolError extends Error { constructor(message = \"WebSocket protocol error\") { super(message); this.name = \"WebSocketProtocolError\"; } }\nexport class WebSocketTimeoutError extends Error { constructor(message = \"WebSocket timed out\") { super(message); this.name = \"WebSocketTimeoutError\"; } }\nfunction __velarWsReleasePendingSends(state) { for (const complete of state.pendingSends) complete(new Error(\"WebSocket is closed\")); state.pendingSends.clear(); }\nconst __velarWsFinalizer = new __velarWsFinalizationRegistry(state => { __velarWsAbort(state); try { state.socket.terminate(); } catch {} });\nfunction __velarWsResolveClose(state, code = 1006, reason = \"\") { if (state.closeInfo !== null) return; state.closeInfo = __velarWsObjectFreeze({code, reason}); state.resolveCloseInfo(state.closeInfo); }\nfunction __velarWsFinish(state, code = 1000, reason = \"\") { __velarWsResolveClose(state, code, reason); if (state.finished) return; state.finished = true; __velarWsReleaseActive(state); if (state.queue.length === 0) __velarWsDiscardQueue(state); __velarWsReleasePendingSends(state); if (state.waiter) { const waiter = state.waiter; state.waiter = null; waiter.resolve(null); } }\nfunction __velarWsAbort(state, code = 1006, reason = \"\") { __velarWsResolveClose(state, code, reason); state.finished = true; __velarWsReleaseActive(state); __velarWsDiscardQueue(state); __velarWsReleasePendingSends(state); if (state.waiter) { const waiter = state.waiter; state.waiter = null; waiter.resolve(null); } }\nfunction __velarWsRejectReceive(state, socket, code, reason) { __velarWsAbort(state, code, reason); socket.close(code, reason); }\nfunction __velarWsReceive(state, socket, data, binary) {\n if (state.finished) return;\n let source = null; let message = null; let size;\n if (binary) { source = data instanceof Uint8Array ? data : new Uint8Array(data); size = source.byteLength; }\n else { message = typeof data === \"string\" ? data : data.toString(\"utf8\"); size = Buffer.byteLength(message, \"utf8\"); }\n if (size > state.options.maxMessageBytes) { __velarWsRejectReceive(state, socket, 1009, \"Message too large\"); return; }\n if (state.waiter) { if (source) { message = new Uint8Array(size); message.set(source); } const waiter = state.waiter; state.waiter = null; waiter.resolve(message); return; }\n if (state.queue.length >= state.options.maxQueuedMessages || state.queuedBytes + size > state.options.maxQueuedBytes || !__velarWsReserveQueue(size)) { __velarWsRejectReceive(state, socket, 1009, \"Unread message queue full\"); return; }\n try { if (source) { message = new Uint8Array(size); message.set(source); } state.queue.push(message); state.queuedBytes += size; }\n catch (error) { __velarWsReleaseQueue(size); throw error; }\n}\nfunction __velarWsWrap(socket, options, origin = null) {\n __velarWsActiveConnections += 1;\n let resolveCloseInfo; const closeInfoPromise = new __velarWsPromise(resolve => { resolveCloseInfo = resolve; });\n const value = Object.create(__velarWsConnectionPrototype); value.origin = origin; const state = { socket, options, queue: [], queuedBytes: 0, queueReleased: false, waiter: null, pendingSendBytes: 0, pendingSends: new Set(), finished: false, active: true, closePromise: null, closeInfo: null, closeInfoPromise, resolveCloseInfo }; __velarWebSocketConnections.set(value, state);\n __velarWsReflectApply(__velarWsFinalizerRegister, __velarWsFinalizer, [value, state]);\n socket.binaryType = \"arraybuffer\";\n socket.on(\"message\", (data, binary) => { try { __velarWsReceive(state, socket, data, binary); } catch { __velarWsRejectReceive(state, socket, 1011, \"Message handling failed\"); } });\n socket.on(\"close\", (code, reason) => __velarWsFinish(state, code, reason.toString(\"utf8\"))); socket.on(\"error\", error => { if (state.waiter) { const waiter = state.waiter; state.waiter = null; waiter.reject(new WebSocketProtocolError(error instanceof Error ? error.message : \"WebSocket error\")); } __velarWsAbort(state); });\n return Object.freeze(value);\n}\nfunction __velarWsCloseForStop(connection) {\n const state = __velarWebSocketConnections.get(connection);\n if (!state || state.finished) return new __velarWsPromise(resolve => resolve(null));\n __velarWsAbort(state, 1001, \"Server stopping\");\n return new __velarWsPromise(resolve => {\n let settled = false; let timer = null;\n const finish = () => { if (settled) return; settled = true; if (timer !== null) __velarWsClearTimeout(timer); state.socket.off(\"close\", finish); resolve(null); };\n state.socket.once(\"close\", finish);\n try { state.socket.close(1001, \"Server stopping\"); }\n catch { try { state.socket.terminate(); } catch {} finish(); return; }\n if (!settled) timer = __velarWsSetTimeout(() => { try { state.socket.terminate(); } catch {} finish(); }, 5000);\n });\n}\nfunction __velarWsCompactPendingConnections(state) { if (state.queue.length <= state.pendingConnections.size * 2 + 64) return; const compact = []; for (const connection of state.queue) if (state.pendingConnections.has(connection)) compact.push(connection); state.queue = compact; }\nfunction __velarWsCloseHttpServer(state, grace = 30000) {\n return new __velarWsPromise((resolve, reject) => {\n let settled = false; let forceTimer = null; let finalTimer = null;\n const finish = action => { if (settled) return; settled = true; if (forceTimer !== null) __velarWsClearTimeout(forceTimer); if (finalTimer !== null) __velarWsClearTimeout(finalTimer); action(); };\n try { state.httpServer.close(error => error ? finish(() => reject(error)) : finish(() => resolve(null))); }\n catch (error) { finish(() => reject(error)); return; }\n try { state.httpServer.closeIdleConnections?.(); } catch {}\n forceTimer = __velarWsSetTimeout(() => {\n try { state.httpServer.closeAllConnections?.(); } catch {}\n for (const socket of state.sockets) try { socket.destroy(); } catch {}\n finalTimer = __velarWsSetTimeout(() => finish(() => reject(new Error(\"WebSocket HTTP transport did not stop within its graceful shutdown deadline\"))), 1000);\n finalTimer.unref?.();\n }, grace);\n forceTimer.unref?.();\n });\n}\nfunction __velarWsStopState(state) {\n if (state.stopPromise !== null) return state.stopPromise;\n state.stopped = true;\n if (state.waiter) { state.waiter.resolve(null); state.waiter = null; }\n __velarWsPendingConnections -= state.pendingConnections.size;\n if (__velarWsPendingConnections < 0) __velarWsPendingConnections = 0;\n state.pendingConnections.clear(); state.queue.length = 0;\n const httpClose = __velarWsCloseHttpServer(state);\n const pending = (async () => {\n let failure = null;\n try {\n const aborting = [];\n for (const prepared of state.preparedSessions) aborting.push(prepared.abort());\n state.preparedSessions.clear();\n try { await __velarWsPromiseAll(aborting); } catch (error) { failure = error; }\n // \u5148\u901A\u77E5\u5DF2\u7ECF\u8FDB\u5165\u5904\u7406\u5668\u7684\u4F1A\u8BDD\u53D6\u6D88\uFF0C\u518D\u5173\u95ED\u8FDE\u63A5\u3002\u5E94\u7528 close \u4F1A\u6CBF\u540C\u4E00\n // Cancellation \u518D\u6B21\u5E7F\u64AD\u5E76\u63D0\u4F9B 30 \u79D2\u6709\u754C\u7B49\u5F85\uFF1B\u5904\u7406\u5668\u6210\u529F\u7ED3\u675F\u4E4B\u524D\uFF0C\n // ServeApp \u4E0D\u4F1A\u91CA\u653E\u8BF7\u6C42\u7EA7\u4F9D\u8D56\u3002\n for (const session of state.activeSessions) session.cancel(\"Server is stopping\");\n const applicationClose = state.application ? state.application.close(30000) : new __velarWsPromise(resolve => resolve(null));\n const closing = [];\n for (const connection of state.connections) closing.push(__velarWsCloseForStop(connection));\n try { await __velarWsPromiseAll(closing); } catch (error) { if (failure === null) failure = error; }\n try { await new __velarWsPromise((resolve, reject) => state.server.close(error => error ? reject(error) : resolve(null))); }\n catch (error) { if (failure === null) failure = error; }\n try { await httpClose; } catch (error) { if (failure === null) failure = error; }\n try { await applicationClose; } catch (error) { if (failure === null) failure = error; }\n if (failure !== null) throw failure;\n } finally { state.connections.clear(); state.preparedSessions.clear(); }\n return null;\n })();\n state.stopPromise = pending;\n return pending;\n}\nconst __velarWsConnectionPrototype = Object.freeze({\n state() { const state = __velarWebSocketConnections.get(this); if (!state) throw new TypeError(\"WebSocket state requires a connection\"); return state.socket.readyState === __VelarWebSocket.CONNECTING ? \"connecting\" : state.socket.readyState === __VelarWebSocket.OPEN ? \"open\" : state.socket.readyState === __VelarWebSocket.CLOSING ? \"closing\" : \"closed\"; },\n send(message) { return __velarWsSend(this, message, true); },\n next() { const state = __velarWebSocketConnections.get(this); if (!state) throw new TypeError(\"WebSocket.next requires a connection\"); if (state.queue.length) { const message = state.queue.shift(); const size = __velarWsMessageBytes(message); state.queuedBytes -= size; __velarWsReleaseQueue(size); if (state.finished && state.queue.length === 0) __velarWsDiscardQueue(state); return Promise.resolve(message); } if (state.finished) return Promise.resolve(null); if (state.waiter) return Promise.reject(new WebSocketBackpressureError(\"Only one WebSocket.next call may wait at a time\")); return new Promise((resolve, reject) => { state.waiter = { resolve, reject }; }); },\n closeInfo() { const state = __velarWebSocketConnections.get(this); if (!state) throw new TypeError(\"WebSocket.closeInfo requires a connection\"); return state.closeInfoPromise; },\n close(code = 1000, reason = \"\") { const state = __velarWebSocketConnections.get(this); if (!state) throw new TypeError(\"WebSocket.close requires a connection\"); if (!Number.isSafeInteger(code) || code < 1000 || code > 4999) return Promise.reject(new RangeError(\"WebSocket close code must be from 1000 through 4999\")); if (typeof reason !== \"string\" || Buffer.byteLength(reason, \"utf8\") > 123) return Promise.reject(new RangeError(\"WebSocket close reason cannot exceed 123 UTF-8 bytes\")); if (state.finished) return Promise.resolve(null); if (!state.closePromise) { state.closePromise = new Promise(resolve => { let settled = false; let timer = null; const finish = () => { if (settled) return; settled = true; if (timer !== null) __velarWsClearTimeout(timer); state.socket.off(\"close\", finish); resolve(null); }; state.socket.once(\"close\", finish); try { state.socket.close(code, reason); } catch { try { state.socket.terminate(); } catch {} finish(); return; } timer = __velarWsSetTimeout(() => { try { state.socket.terminate(); } catch {} finish(); }, 5000); }); } return state.closePromise; },\n});\nconst __velarWsServerPrototype = Object.freeze({\n next() { const state = __velarWebSocketServers.get(this); if (!state) throw new TypeError(\"WebSocketServer.next requires a server\"); if (state.declarative) return Promise.reject(new TypeError(\"Connections are owned by @websocket routes and cannot be pulled with server.next()\")); while (state.queue.length) { const connection = state.queue.shift(); if (!state.pendingConnections.delete(connection)) continue; __velarWsPendingConnections -= 1; if (__velarWsPendingConnections < 0) __velarWsPendingConnections = 0; return Promise.resolve(connection); } if (state.stopped) return Promise.resolve(null); if (state.waiter) return Promise.reject(new WebSocketBackpressureError(\"Only one WebSocketServer.next call may wait at a time\")); return new Promise((resolve, reject) => { state.waiter = { resolve, reject }; }); },\n stop() { const state = __velarWebSocketServers.get(this); if (!state) throw new TypeError(\"WebSocketServer.stop requires a server\"); return __velarWsStopState(state); },\n});\nconst __velarWsCloseType = Object.freeze({ is(value) { return value !== null && typeof value === \"object\" && Number.isSafeInteger(value.code) && typeof value.reason === \"string\"; }, parse(value) { if (!this.is(value)) throw new TypeError(\"Value does not match WebSocketClose\"); return value; } });\nconst __velarWsConnectionType = Object.freeze({ is(value) { return __velarWebSocketConnections.has(value); }, parse(value) { if (!this.is(value)) throw new TypeError(\"Value does not match WebSocketConnection\"); return value; } });\nconst __velarWsServerType = Object.freeze({ is(value) { return __velarWebSocketServers.has(value); }, parse(value) { if (!this.is(value)) throw new TypeError(\"Value does not match WebSocketServer\"); return value; } });\nexport const WebSocketConnection = __velarWsConnectionType; export const WebSocketClose = __velarWsCloseType; export const WebSocketServer = __velarWsServerType;\nexport function connect(url, options = {}) { if (typeof url !== \"string\" || !/^wss?:\\/\\//u.test(url)) return __velarWsPromise.reject(new TypeError(\"WebSocket URL must start with ws:// or wss://\")); const limits = __velarWsOptions(options); const timeout = __velarWsDuration(__velarWsOption(options, \"timeout\"), 10000); return new __velarWsPromise((resolve, reject) => { const socket = new __VelarWebSocket(url, { maxPayload: limits.maxMessageBytes }); let settled = false; const finish = (action) => { if (settled) return false; settled = true; __velarWsClearTimeout(timer); socket.off(\"open\", opened); socket.off(\"error\", failed); action(); return true; }; const absorbTerminalError = () => socket.once(\"error\", () => {}); const opened = () => { if (__velarWsActiveConnections >= __velarWsActiveConnectionLimit) { if (finish(() => reject(new WebSocketBackpressureError(\"WebSocket connection limit exceeded\")))) { absorbTerminalError(); socket.close(1013, \"Client connection limit reached\"); } return; } finish(() => resolve(__velarWsWrap(socket, limits))); }; const failed = error => finish(() => reject(new WebSocketProtocolError(error instanceof Error ? error.message : \"WebSocket connection failed\"))); const timer = __velarWsSetTimeout(() => { if (finish(() => reject(new WebSocketTimeoutError(\"WebSocket connection timed out\")))) { absorbTerminalError(); socket.terminate(); } }, timeout); socket.once(\"open\", opened); socket.once(\"error\", failed); }); }\nexport async function listen(options) {\n if (options === null || typeof options !== \"object\" || __velarWsArrayIsArray(options)) throw new TypeError(\"listen requires an options record\");\n const limits = __velarWsOptions(options);\n const port = __velarWsInteger(__velarWsOption(options, \"port\"), 0, 0, 65535, \"port\");\n const maxConnections = __velarWsInteger(__velarWsOption(options, \"maxConnections\"), 1024, 1, 4096, \"maxConnections\");\n const maxPendingConnections = __velarWsInteger(__velarWsOption(options, \"maxPendingConnections\"), 128, 1, 4096, \"maxPendingConnections\");\n const maxBodyBytes = __velarWsInteger(__velarWsOption(options, \"maxBodyBytes\"), 16 * 1024 * 1024, 1, 16 * 1024 * 1024, \"maxBodyBytes\");\n const host = __velarWsOption(options, \"host\");\n const path = __velarWsOption(options, \"path\");\n const http = __velarWsOption(options, \"http\");\n const origins = __velarWsOrigins(__velarWsOption(options, \"origins\"));\n if (host !== undefined && (typeof host !== \"string\" || host.length === 0 || host.length > 255 || __velarWsReflectApply(__velarWsStringIncludes, host, [\"\\0\"]))) {\n throw new TypeError(\"WebSocket host must be bounded non-empty text\");\n }\n if (path !== undefined && (typeof path !== \"string\" || !path.startsWith(\"/\"))) throw new TypeError(\"WebSocket path must start with '/'\");\n const application = __velarServeApp.is(http) ? await __velarServeApp.__velarCompilerBridge.nativeApp(http, maxBodyBytes) : null;\n const declarative = application !== null && application.webSocketRoutes > 0;\n // SR-U2: declarative @websocket routes own their own paths, so a listener\n // path would be a second, silent route table over the same app. The refusal\n // names the path it refused so the author can see which one to remove.\n if (declarative && path !== undefined) { await application.close(); throw new TypeError(\"listen path '\" + path + \"' is unavailable when the ServeApp declares @websocket routes; those routes own their own paths\"); }\n const handler = application ? application.handle : http;\n if (handler !== undefined && typeof handler !== \"function\") { if (application) await application.close(); throw new TypeError(\"WebSocket http must be a ServeApp or velar/serve handler\"); }\n try {\n return await new __velarWsPromise((resolve, reject) => {\n const httpServer = __velarCreateHttpServer({maxHeaderSize: 64 * 1024, headersTimeout: 10000, requestTimeout: 60000, keepAliveTimeout: 5000, connectionsCheckingInterval: 1000}, (request, response) => {\n if (handler) void __velarServeRuntime.__velarHandleNative(handler, request, response, __velarServeNativeOperations, maxBodyBytes);\n else { response.statusCode = 404; response.setHeader(\"content-type\", \"text/plain; charset=utf-8\"); response.end(request.method === \"HEAD\" ? undefined : \"Not found\"); }\n });\n httpServer.maxConnections = 2048;\n httpServer.maxRequestsPerSocket = 1000;\n let state = null;\n const server = new __VelarWebSocketServer({server: httpServer, path: declarative ? undefined : path, maxPayload: limits.maxMessageBytes, perMessageDeflate: false, clientTracking: true, verifyClient(info, complete) {\n const origin = info.origin;\n const allowed = origin === undefined || origins.wildcard || __velarWsReflectApply(__velarWsSetHas, origins.exact, [origin]);\n if (!allowed) { complete(false, 403, \"Origin not allowed\"); return; }\n if (!declarative) { complete(true); return; }\n if (state === null || state.stopped || state.preparing >= maxPendingConnections\n || state.connections.size + state.preparedSessions.size + state.preparing >= maxConnections) {\n complete(false, 503, \"Server busy\");\n return;\n }\n state.preparing += 1;\n void application.prepareWebSocket(info.req).then(prepared => {\n state.preparing -= 1;\n if (!prepared.accepted) { complete(false, prepared.status, \"WebSocket route rejected\"); return; }\n if (state.stopped) { void prepared.abort(); complete(false, 503, \"Server stopping\"); return; }\n __velarWebSocketPreparedRequests.set(info.req, prepared);\n state.preparedSessions.add(prepared);\n complete(true);\n }, () => {\n state.preparing -= 1;\n complete(false, 500, \"WebSocket route failed\");\n });\n }});\n const value = Object.create(__velarWsServerPrototype);\n state = {server, httpServer, application, declarative, preparing: 0, preparedSessions: new Set(), activeSessions: new Set(), handlers: new Set(), queue: [], pendingConnections: new Set(), waiter: null, stopped: false, stopPromise: null, connections: new Set(), sockets: new Set()};\n __velarWebSocketServers.set(value, state);\n httpServer.on(\"connection\", socket => {\n if (state.stopped || state.sockets.size >= 2048 || __velarWsActiveHttpSockets >= 4096) { socket.destroy(); return; }\n state.sockets.add(socket); __velarWsActiveHttpSockets += 1; socket.setNoDelay(true); socket.setKeepAlive(true, 5000);\n socket.once(\"close\", () => { if (!state.sockets.delete(socket)) return; __velarWsActiveHttpSockets -= 1; if (__velarWsActiveHttpSockets < 0) __velarWsActiveHttpSockets = 0; });\n });\n server.on(\"connection\", (socket, request) => {\n const prepared = declarative ? __velarWebSocketPreparedRequests.get(request) : null;\n if (prepared !== null && prepared !== undefined) { __velarWebSocketPreparedRequests.delete(request); state.preparedSessions.delete(prepared); }\n const willQueue = !declarative && !state.waiter;\n if (state.stopped || state.connections.size >= maxConnections || __velarWsActiveConnections >= __velarWsActiveConnectionLimit || (willQueue && (state.pendingConnections.size >= maxPendingConnections || __velarWsPendingConnections >= __velarWsPendingConnectionLimit))) {\n if (prepared) void prepared.abort();\n socket.close(1013, \"Server busy\");\n return;\n }\n if (declarative && !prepared) { socket.close(1008, \"WebSocket route unavailable\"); return; }\n const connection = __velarWsWrap(socket, limits, __velarWsRequestOrigin(request)); state.connections.add(connection);\n socket.once(\"close\", () => {\n state.connections.delete(connection);\n if (prepared) prepared.cancel(\"WebSocket connection closed\");\n if (state.pendingConnections.delete(connection)) { __velarWsPendingConnections -= 1; if (__velarWsPendingConnections < 0) __velarWsPendingConnections = 0; __velarWsCompactPendingConnections(state); }\n });\n if (declarative) {\n state.activeSessions.add(prepared);\n let running = null;\n running = prepared.run(connection).catch(async () => { try { await connection.close(1011, \"WebSocket handler failed\"); } catch {} }).finally(() => { state.handlers.delete(running); state.activeSessions.delete(prepared); });\n state.handlers.add(running);\n } else if (state.waiter) { const waiter = state.waiter; state.waiter = null; waiter.resolve(connection); }\n else { state.queue.push(connection); state.pendingConnections.add(connection); __velarWsPendingConnections += 1; }\n });\n let settled = false;\n const fail = error => {\n if (settled) { void __velarWsStopState(state).catch(() => {}); return; }\n settled = true;\n try { server.close(); } catch {}\n try { httpServer.close(); } catch {}\n reject(error);\n };\n server.on(\"error\", fail);\n httpServer.on(\"error\", fail);\n httpServer.listen({port, host: host ?? \"127.0.0.1\"}, () => {\n if (settled) return;\n const address = httpServer.address();\n if (!address || typeof address === \"string\") { fail(new Error(\"WebSocket server could not determine its bound port\")); return; }\n settled = true;\n Object.defineProperty(value, \"port\", {value: address.port, enumerable: true});\n resolve(Object.freeze(value));\n });\n });\n } catch (error) { if (application) await application.close(); throw error; }\n}\nexport async function run(server) {\n server = __velarWsServerType.parse(server);\n __velarWsOnShutdown(async () => await server.stop());\n return null;\n}\n"; /** `velar/worker` — the worker pool, its cancellation protocol and backpressure. */ export declare const VELAR_NODE_WORKER_RUNTIME = "import { Worker as __VelarNodeWorker, isMainThread as __velarWorkerIsMainThread, parentPort as __velarWorkerParentPort } from \"node:worker_threads\";\nimport { workerEntries as __velarWorkerEntries } from \"velar/worker-manifest\";\nimport { Cancellation, CancellationError, TaskTimeoutError } from \"velar/task\";\nimport { Bytes as __velarWorkerBinaryRuntime } from \"velar/binary\";\n\nconst __velarWorkerStates = new WeakMap();\nconst __velarWorkerPoolStates = new WeakMap();\nlet __velarWorkerServerInstalled = false;\nconst __velarWorkerStructuredClone = globalThis.structuredClone;\nconst __velarWorkerCancelGrace = 1000;\nfunction __velarWorkerInteger(value, minimum, maximum, name) {\n if (!Number.isSafeInteger(value) || value < minimum || value > maximum) throw new RangeError(name + \" must be an integer from \" + minimum + \" through \" + maximum);\n return value;\n}\nfunction __velarWorkerRuntimeType(value, name) {\n if ((typeof value !== \"object\" && typeof value !== \"function\") || value === null || typeof value.parse !== \"function\" || typeof value.is !== \"function\") throw new TypeError(name + \" must be a runtime Type\");\n return value;\n}\nfunction __velarWorkerDuration(value) {\n if (value === null) return 0;\n if (typeof value !== \"string\") throw new TypeError(\"Worker timeout must be Duration or null\");\n const match = /^([+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+))(ms|s)$/.exec(value);\n if (!match) throw new TypeError(\"Worker timeout must be Duration such as 200ms or 2s\");\n const milliseconds = Number(match[1]) * (match[2] === \"s\" ? 1000 : 1);\n if (!Number.isFinite(milliseconds) || milliseconds < 0 || milliseconds > 2147483647) throw new RangeError(\"Worker timeout is outside the supported range\");\n return milliseconds;\n}\nfunction __velarWorkerTransfer(value, adopt = false) {\n const transfers = [];\n const buffers = new Set();\n const objects = new Set();\n const pending = [{ value, depth: 0 }];\n let visited = 0;\n let transferBytes = 0;\n while (pending.length > 0 && visited < 10000 && transfers.length < 1024) {\n const current = pending.pop();\n const item = current.value;\n visited += 1;\n if (item === null || (typeof item !== \"object\" && typeof item !== \"function\")) continue;\n if (objects.has(item)) continue;\n objects.add(item);\n if (ArrayBuffer.isView(item)) {\n const supported = item instanceof Uint8Array || item instanceof Uint16Array || item instanceof Uint32Array || item instanceof Float32Array;\n const buffer = item.buffer;\n if (supported && buffer instanceof ArrayBuffer && item.byteOffset === 0 && item.byteLength === buffer.byteLength\n && transferBytes + buffer.byteLength <= 64 * 1024 * 1024) {\n if (adopt) __velarWorkerBinaryRuntime.__velarAdoptTransferredBuffer(item);\n if (buffer.byteLength > 0 && !buffers.has(buffer)) {\n buffers.add(buffer);\n transfers.push(buffer);\n transferBytes += buffer.byteLength;\n }\n }\n continue;\n }\n if (current.depth >= 32) continue;\n const depth = current.depth + 1;\n if (item instanceof Map) { for (const [key, nested] of item) { pending.push({ value: key, depth }, { value: nested, depth }); } continue; }\n if (item instanceof Set) { for (const nested of item) pending.push({ value: nested, depth }); continue; }\n for (const key of Object.keys(item)) pending.push({ value: item[key], depth });\n }\n return transfers;\n}\nfunction __velarWorkerOutbound(value, source) {\n const transfers = __velarWorkerTransfer(value);\n if (transfers.length === 0) return { value, transfers };\n const sourceTransfers = new Set(__velarWorkerTransfer(source));\n if (!transfers.some(buffer => sourceTransfers.has(buffer))) return { value, transfers };\n if (typeof __velarWorkerStructuredClone !== \"function\") throw new Error(\"The structured clone API is unavailable\");\n const snapshot = __velarWorkerStructuredClone(value);\n return { value: snapshot, transfers: __velarWorkerTransfer(snapshot) };\n}\nfunction __velarWorkerInbound(Type, value) {\n if (!Type.is(value)) return Type.parse(value);\n __velarWorkerTransfer(value, true);\n return value;\n}\nfunction __velarWorkerFailure(error) {\n return { name: typeof error?.name === \"string\" ? error.name : \"Error\", message: typeof error?.message === \"string\" ? error.message : String(error), stack: typeof error?.stack === \"string\" ? error.stack : \"\" };\n}\nexport class WorkerBackpressureError extends Error { constructor(message = \"Worker queue is full\") { super(message); this.name = \"WorkerBackpressureError\"; } }\nexport class WorkerCallError extends Error { constructor(message = \"Worker call failed\") { super(message); this.name = \"WorkerCallError\"; } }\nexport class WorkerCrashedError extends Error { constructor(message = \"Worker crashed\") { super(message); this.name = \"WorkerCrashedError\"; } }\nexport class WorkerClosedError extends Error { constructor(message = \"Worker is closed\") { super(message); this.name = \"WorkerClosedError\"; } }\n\nfunction __velarWorkerRejectAll(state, failure) {\n if (state.closed) return;\n state.closed = true;\n for (const pending of state.pending.values()) { if (pending.timer) clearTimeout(pending.timer); pending.unsubscribe(); pending.reject(failure); }\n state.pending.clear();\n for (const timer of state.abandoned.values()) clearTimeout(timer);\n state.abandoned.clear();\n}\nfunction __velarWorkerCrash(state, failure) { __velarWorkerRejectAll(state, failure); state.instance.terminate(); }\nfunction __velarWorkerClient(name, RequestType, ResponseType, capacity) {\n if (!__velarWorkerIsMainThread) throw new Error(\"worker() can only be called outside a worker entry\");\n if (typeof name !== \"string\" || !Object.hasOwn(__velarWorkerEntries, name)) throw new RangeError(\"Unknown worker entry '\" + String(name) + \"'\");\n RequestType = __velarWorkerRuntimeType(RequestType, \"Worker request Type\"); ResponseType = __velarWorkerRuntimeType(ResponseType, \"Worker response Type\");\n capacity = __velarWorkerInteger(capacity, 1, 10000, \"Worker capacity\");\n const entry = __velarWorkerEntries[name];\n const instance = new __VelarNodeWorker(new URL(\"../../\" + entry, import.meta.url), { type: \"module\" });\n const value = Object.create(__velarWorkerPrototype);\n const state = { instance, RequestType, ResponseType, capacity, nextId: 1, pending: new Map(), abandoned: new Map(), closed: false };\n __velarWorkerStates.set(value, state);\n instance.on(\"message\", message => {\n if (!message || !Number.isSafeInteger(message.id)) { __velarWorkerCrash(state, new WorkerCrashedError(\"Worker returned an invalid message\")); return; }\n const grace = state.abandoned.get(message.id);\n if (grace !== undefined) { clearTimeout(grace); state.abandoned.delete(message.id); }\n if (message.kind === \"cancel-ack\") return;\n const pending = state.pending.get(message.id); if (!pending) return;\n state.pending.delete(message.id); if (pending.timer) clearTimeout(pending.timer); pending.unsubscribe();\n if (pending.cancel === \"cancel\") { pending.reject(new CancellationError(pending.reason)); return; }\n if (!message.ok) { const remote = message.error ?? {}; const failure = new WorkerCallError((remote.name ? remote.name + \": \" : \"\") + (remote.message ?? \"Worker call failed\")); if (typeof remote.stack === \"string\" && remote.stack) failure.stack = failure.stack + \"\\nRemote worker:\\n\" + remote.stack; pending.reject(failure); return; }\n try { pending.resolve(__velarWorkerInbound(state.ResponseType, message.value)); } catch (error) { pending.reject(error); }\n });\n instance.on(\"error\", error => __velarWorkerCrash(state, new WorkerCrashedError(error instanceof Error ? error.message : \"Worker crashed\")));\n instance.on(\"exit\", code => { if (!state.closed) __velarWorkerCrash(state, new WorkerCrashedError(\"Worker exited unexpectedly with code \" + code)); });\n return Object.freeze(value);\n}\nconst __velarWorkerPrototype = Object.freeze({\n call(request, cancellation = null, timeout = null) {\n const state = __velarWorkerStates.get(this); if (!state) throw new TypeError(\"Worker.call requires a Worker receiver\");\n if (state.closed) return Promise.reject(new WorkerClosedError());\n if (state.pending.size >= state.capacity) return Promise.reject(new WorkerBackpressureError(\"Worker queue capacity \" + state.capacity + \" is full\"));\n if (cancellation !== null && !Cancellation.is(cancellation)) return Promise.reject(new TypeError(\"Worker cancellation must be Cancellation or null\"));\n let validated; try { validated = state.RequestType.parse(request); } catch (error) { return Promise.reject(error); }\n let outbound; try { outbound = __velarWorkerOutbound(validated, request); } catch (error) { return Promise.reject(error); }\n const milliseconds = __velarWorkerDuration(timeout); const id = state.nextId++;\n return new Promise((resolve, reject) => {\n const pending = { resolve, reject, cancel: null, reason: \"Worker call cancelled\", timeout, timer: null, unsubscribe: () => null };\n state.pending.set(id, pending);\n state.instance.postMessage({ kind: \"call\", id, value: outbound.value }, outbound.transfers);\n if (cancellation !== null) pending.unsubscribe = Cancellation.__velarOn(cancellation, reason => { if (!state.pending.has(id) || pending.cancel) return; pending.cancel = \"cancel\"; pending.reason = reason ?? pending.reason; state.instance.postMessage({ kind: \"cancel\", id, reason: pending.reason }); });\n if (milliseconds > 0) pending.timer = setTimeout(() => { if (!state.pending.has(id) || pending.cancel) return; state.pending.delete(id); pending.unsubscribe(); state.instance.postMessage({ kind: \"cancel\", id, reason: \"Worker call timed out\" }); state.abandoned.set(id, setTimeout(() => __velarWorkerCrash(state, new WorkerCrashedError(\"Worker did not acknowledge a cancelled call within \" + __velarWorkerCancelGrace + \"ms\")), __velarWorkerCancelGrace)); reject(new TaskTimeoutError(\"Worker call timed out after \" + timeout)); }, milliseconds);\n });\n },\n async close() {\n const state = __velarWorkerStates.get(this); if (!state) throw new TypeError(\"Worker.close requires a Worker receiver\");\n if (state.closed) return null;\n __velarWorkerRejectAll(state, new WorkerClosedError());\n await state.instance.terminate(); return null;\n },\n});\nconst __velarWorkerPoolPrototype = Object.freeze({\n call(request, cancellation = null, timeout = null) {\n const state = __velarWorkerPoolStates.get(this); if (!state) throw new TypeError(\"WorkerPool.call requires a WorkerPool receiver\");\n if (state.closed) return Promise.reject(new WorkerClosedError(\"Worker pool is closed\"));\n let total = 0; let selected = null; let pending = 0;\n for (const item of state.workers) { const member = __velarWorkerStates.get(item); if (member.closed) continue; total += member.pending.size; if (selected === null || member.pending.size < pending) { selected = item; pending = member.pending.size; } }\n if (selected === null) return Promise.reject(new WorkerCrashedError(\"Worker pool has no live workers\"));\n if (total >= state.capacity) return Promise.reject(new WorkerBackpressureError(\"Worker pool queue capacity \" + state.capacity + \" is full\"));\n return selected.call(request, cancellation, timeout);\n },\n broadcast(request, cancellation = null, timeout = null) {\n const state = __velarWorkerPoolStates.get(this); if (!state) throw new TypeError(\"WorkerPool.broadcast requires a WorkerPool receiver\");\n if (state.closed) return Promise.reject(new WorkerClosedError(\"Worker pool is closed\"));\n const live = []; let total = 0;\n for (const item of state.workers) { const member = __velarWorkerStates.get(item); if (member.closed) continue; live.push(item); total += member.pending.size; if (member.pending.size >= member.capacity) return Promise.reject(new WorkerBackpressureError(\"Worker pool member queue capacity \" + member.capacity + \" is full\")); }\n if (live.length === 0) return Promise.reject(new WorkerCrashedError(\"Worker pool has no live workers\"));\n if (total + live.length > state.capacity) return Promise.reject(new WorkerBackpressureError(\"Worker pool queue capacity \" + state.capacity + \" cannot accept a broadcast to \" + live.length + \" workers\"));\n return Promise.all(live.map(item => item.call(request, cancellation, timeout)));\n },\n async close() { const state = __velarWorkerPoolStates.get(this); if (!state) throw new TypeError(\"WorkerPool.close requires a WorkerPool receiver\"); if (state.closed) return null; state.closed = true; await Promise.all(state.workers.map(worker => worker.close())); return null; },\n});\nconst __velarWorkerType = Object.freeze({ is(value) { return __velarWorkerStates.has(value); }, parse(value) { if (!this.is(value)) throw new TypeError(\"Value does not match Worker\"); return value; } });\nconst __velarWorkerPoolType = Object.freeze({ is(value) { return __velarWorkerPoolStates.has(value); }, parse(value) { if (!this.is(value)) throw new TypeError(\"Value does not match WorkerPool\"); return value; } });\nexport const Worker = Object.freeze({ ...__velarWorkerType, of() { return __velarWorkerType; } });\nexport const WorkerPool = Object.freeze({ ...__velarWorkerPoolType, of() { return __velarWorkerPoolType; } });\nexport function worker(name, RequestType, ResponseType, capacity = 64) { return __velarWorkerClient(name, RequestType, ResponseType, capacity); }\nexport function workerPool(name, RequestType, ResponseType, size, capacity = 256) {\n size = __velarWorkerInteger(size, 1, 32, \"Worker pool size\"); capacity = __velarWorkerInteger(capacity, size, 10000, \"Worker pool capacity\");\n const workers = Array.from({ length: size }, () => __velarWorkerClient(name, RequestType, ResponseType, Math.ceil(capacity / size)));\n const value = Object.create(__velarWorkerPoolPrototype); __velarWorkerPoolStates.set(value, { workers, capacity, closed: false }); return Object.freeze(value);\n}\nexport function serveWorker(RequestType, ResponseType, handler, capacity = 64) {\n if (__velarWorkerIsMainThread || !__velarWorkerParentPort) throw new Error(\"serveWorker() can only run in a declared worker entry\");\n if (__velarWorkerServerInstalled) throw new Error(\"A worker entry may call serveWorker() only once\");\n RequestType = __velarWorkerRuntimeType(RequestType, \"Worker request Type\"); ResponseType = __velarWorkerRuntimeType(ResponseType, \"Worker response Type\");\n if (typeof handler !== \"function\") throw new TypeError(\"serveWorker handler must be an async function\"); capacity = __velarWorkerInteger(capacity, 1, 10000, \"Worker capacity\");\n __velarWorkerServerInstalled = true; const queue = []; const active = new Map(); let running = false;\n const drain = async () => { if (running) return; running = true; while (queue.length) { const message = queue.shift(); const cancellation = Cancellation.__velarCreate(); active.set(message.id, cancellation); try { const request = __velarWorkerInbound(RequestType, message.value); const handled = await handler(request, cancellation); const result = ResponseType.parse(handled); const outbound = __velarWorkerOutbound(result, handled); __velarWorkerParentPort.postMessage({ id: message.id, ok: true, value: outbound.value }, outbound.transfers); } catch (error) { __velarWorkerParentPort.postMessage({ id: message.id, ok: false, error: __velarWorkerFailure(error) }); } finally { active.delete(message.id); } } running = false; };\n __velarWorkerParentPort.on(\"message\", message => { if (!message || !Number.isSafeInteger(message.id)) return; if (message.kind === \"cancel\") { __velarWorkerParentPort.postMessage({ id: message.id, kind: \"cancel-ack\" }); const cancellation = active.get(message.id); if (cancellation) Cancellation.__velarCancel(cancellation, typeof message.reason === \"string\" ? message.reason : \"Worker call cancelled\"); else { const index = queue.findIndex(item => item.id === message.id); if (index >= 0) { queue.splice(index, 1); __velarWorkerParentPort.postMessage({ id: message.id, ok: false, error: __velarWorkerFailure(new CancellationError(typeof message.reason === \"string\" ? message.reason : \"Worker call cancelled\")) }); } } return; } if (message.kind !== \"call\") return; if (queue.length + active.size >= capacity) { __velarWorkerParentPort.postMessage({ id: message.id, ok: false, error: __velarWorkerFailure(new WorkerBackpressureError()) }); return; } queue.push(message); drain(); });\n return null;\n}\n"; //# sourceMappingURL=runtime-sources.generated.d.ts.map