@sm-lab/keys 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.mjs","names":["#body","#init","#eventInitDict","realMakeDepositKeys"],"sources":["../../../node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/helper/websocket/index.js","../../../node_modules/.pnpm/@hono+node-server@2.0.6_hono@4.12.27/node_modules/@hono/node-server/dist/index.mjs","../../../packages/core/src/admin.ts","../../../packages/core/src/cli.ts","../../../packages/core/src/completion.ts","../src/cli/program.ts","../src/cli/index.ts"],"sourcesContent":["// src/helper/websocket/index.ts\nvar WSContext = class {\n #init;\n constructor(init) {\n this.#init = init;\n this.raw = init.raw;\n this.url = init.url ? new URL(init.url) : null;\n this.protocol = init.protocol ?? null;\n }\n send(source, options) {\n this.#init.send(source, options ?? {});\n }\n raw;\n binaryType = \"arraybuffer\";\n get readyState() {\n return this.#init.readyState;\n }\n url;\n protocol;\n close(code, reason) {\n this.#init.close(code, reason);\n }\n};\nvar createWSMessageEvent = (source) => {\n return new MessageEvent(\"message\", {\n data: source\n });\n};\nvar defineWebSocketHelper = (handler) => {\n return ((...args) => {\n if (typeof args[0] === \"function\") {\n const [createEvents, options] = args;\n return async function upgradeWebSocket(c, next) {\n const events = await createEvents(c);\n const result = await handler(c, events, options);\n if (result) {\n return result;\n }\n await next();\n };\n } else {\n const [c, events, options] = args;\n return (async () => {\n const upgraded = await handler(c, events, options);\n if (!upgraded) {\n throw new Error(\"Failed to upgrade WebSocket\");\n }\n return upgraded;\n })();\n }\n });\n};\nexport {\n WSContext,\n createWSMessageEvent,\n defineWebSocketHelper\n};\n","import { t as X_ALREADY_SENT } from \"./constants-BLSFu_RU.mjs\";\nimport { STATUS_CODES, createServer } from \"node:http\";\nimport { Http2ServerRequest, constants } from \"node:http2\";\nimport { Readable } from \"node:stream\";\nimport { defineWebSocketHelper } from \"hono/ws\";\n\n//#region src/error.ts\nvar RequestError = class extends Error {\n\tconstructor(message, options) {\n\t\tsuper(message, options);\n\t\tthis.name = \"RequestError\";\n\t}\n};\n\n//#endregion\n//#region src/url.ts\nconst reValidRequestUrl = /^\\/[!#$&-;=?-\\[\\]_a-z~]*$/;\nconst reDotSegment = /\\/\\.\\.?(?:[/?#]|$)/;\nconst reValidHost = /^[a-z0-9._-]+(?::(?:[1-5]\\d{3,4}|[6-9]\\d{3}))?$/;\nconst buildUrl = (scheme, host, incomingUrl) => {\n\tconst url = `${scheme}://${host}${incomingUrl}`;\n\tif (!reValidHost.test(host)) {\n\t\tconst urlObj = new URL(url);\n\t\tif (urlObj.hostname.length !== host.length && urlObj.hostname !== (host.includes(\":\") ? host.replace(/:\\d+$/, \"\") : host).toLowerCase()) throw new RequestError(\"Invalid host header\");\n\t\treturn urlObj.href;\n\t} else if (incomingUrl.length === 0) return url + \"/\";\n\telse {\n\t\tif (incomingUrl.charCodeAt(0) !== 47) throw new RequestError(\"Invalid URL\");\n\t\tif (!reValidRequestUrl.test(incomingUrl) || reDotSegment.test(incomingUrl)) return new URL(url).href;\n\t\treturn url;\n\t}\n};\n\n//#endregion\n//#region src/request.ts\nconst toRequestError = (e) => {\n\tif (e instanceof RequestError) return e;\n\treturn new RequestError(e.message, { cause: e });\n};\nconst GlobalRequest = global.Request;\nvar Request$1 = class extends GlobalRequest {\n\tconstructor(input, options) {\n\t\tif (typeof input === \"object\" && getRequestCache in input) {\n\t\t\tconst hasReplacementBody = options !== void 0 && \"body\" in options && options.body != null;\n\t\t\tif (input[bodyConsumedDirectlyKey] && !hasReplacementBody) throw new TypeError(\"Cannot construct a Request with a Request object that has already been used.\");\n\t\t\tinput = input[getRequestCache]();\n\t\t}\n\t\tif (typeof (options?.body)?.getReader !== \"undefined\") options.duplex ??= \"half\";\n\t\tsuper(input, options);\n\t}\n};\nconst newHeadersFromIncoming = (incoming) => {\n\tconst headerRecord = [];\n\tconst rawHeaders = incoming.rawHeaders;\n\tfor (let i = 0, len = rawHeaders.length; i < len; i += 2) {\n\t\tconst key = rawHeaders[i];\n\t\tif (key.charCodeAt(0) !== 58) headerRecord.push([key, rawHeaders[i + 1]]);\n\t}\n\treturn new Headers(headerRecord);\n};\nconst wrapBodyStream = Symbol(\"wrapBodyStream\");\nconst newRequestFromIncoming = (method, url, headers, incoming, abortController) => {\n\tconst init = {\n\t\tmethod,\n\t\theaders,\n\t\tsignal: abortController.signal\n\t};\n\tif (method === \"TRACE\") {\n\t\tinit.method = \"GET\";\n\t\tconst req = new Request$1(url, init);\n\t\tObject.defineProperty(req, \"method\", { get() {\n\t\t\treturn \"TRACE\";\n\t\t} });\n\t\treturn req;\n\t}\n\tif (!(method === \"GET\" || method === \"HEAD\")) if (\"rawBody\" in incoming && incoming.rawBody instanceof Buffer) init.body = new ReadableStream({ start(controller) {\n\t\tcontroller.enqueue(incoming.rawBody);\n\t\tcontroller.close();\n\t} });\n\telse if (incoming[wrapBodyStream]) {\n\t\tlet reader;\n\t\tinit.body = new ReadableStream({ async pull(controller) {\n\t\t\ttry {\n\t\t\t\treader ||= Readable.toWeb(incoming).getReader();\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) controller.close();\n\t\t\t\telse controller.enqueue(value);\n\t\t\t} catch (error) {\n\t\t\t\tcontroller.error(error);\n\t\t\t}\n\t\t} });\n\t} else init.body = Readable.toWeb(incoming);\n\treturn new Request$1(url, init);\n};\nconst getRequestCache = Symbol(\"getRequestCache\");\nconst requestCache = Symbol(\"requestCache\");\nconst incomingKey = Symbol(\"incomingKey\");\nconst urlKey = Symbol(\"urlKey\");\nconst methodKey = Symbol(\"methodKey\");\nconst headersKey = Symbol(\"headersKey\");\nconst abortControllerKey = Symbol(\"abortControllerKey\");\nconst getAbortController = Symbol(\"getAbortController\");\nconst abortRequest = Symbol(\"abortRequest\");\nconst bodyBufferKey = Symbol(\"bodyBuffer\");\nconst bodyReadPromiseKey = Symbol(\"bodyReadPromise\");\nconst bodyConsumedDirectlyKey = Symbol(\"bodyConsumedDirectly\");\nconst bodyLockReaderKey = Symbol(\"bodyLockReader\");\nconst abortReasonKey = Symbol(\"abortReason\");\nconst newBodyUnusableError = () => {\n\treturn /* @__PURE__ */ new TypeError(\"Body is unusable\");\n};\nconst rejectBodyUnusable = () => {\n\treturn Promise.reject(newBodyUnusableError());\n};\nconst textDecoder = new TextDecoder();\nconst consumeBodyDirectOnce = (request) => {\n\tif (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();\n\trequest[bodyConsumedDirectlyKey] = true;\n};\nconst toArrayBuffer = (buf) => {\n\treturn buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);\n};\nconst contentType = (request) => {\n\treturn (request[headersKey] ||= newHeadersFromIncoming(request[incomingKey])).get(\"content-type\") || \"\";\n};\nconst methodTokenRegExp = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/;\nconst normalizeIncomingMethod = (method) => {\n\tif (typeof method !== \"string\" || method.length === 0) return \"GET\";\n\tswitch (method) {\n\t\tcase \"DELETE\":\n\t\tcase \"GET\":\n\t\tcase \"HEAD\":\n\t\tcase \"OPTIONS\":\n\t\tcase \"POST\":\n\t\tcase \"PUT\": return method;\n\t}\n\tconst upper = method.toUpperCase();\n\tswitch (upper) {\n\t\tcase \"DELETE\":\n\t\tcase \"GET\":\n\t\tcase \"HEAD\":\n\t\tcase \"OPTIONS\":\n\t\tcase \"POST\":\n\t\tcase \"PUT\": return upper;\n\t\tdefault: return method;\n\t}\n};\nconst validateDirectReadMethod = (method) => {\n\tif (!methodTokenRegExp.test(method)) return /* @__PURE__ */ new TypeError(`'${method}' is not a valid HTTP method.`);\n\tconst normalized = method.toUpperCase();\n\tif (normalized === \"CONNECT\" || normalized === \"TRACK\" || normalized === \"TRACE\" && method !== \"TRACE\") return /* @__PURE__ */ new TypeError(`'${method}' HTTP method is unsupported.`);\n};\nconst readBodyWithFastPath = (request, method, fromBuffer) => {\n\tif (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();\n\tconst methodName = request.method;\n\tif (methodName === \"GET\" || methodName === \"HEAD\") return request[getRequestCache]()[method]();\n\tconst methodValidationError = validateDirectReadMethod(methodName);\n\tif (methodValidationError) return Promise.reject(methodValidationError);\n\tif (request[requestCache]) {\n\t\tif (methodName !== \"TRACE\") return request[requestCache][method]();\n\t}\n\tconst alreadyUsedError = consumeBodyDirectOnce(request);\n\tif (alreadyUsedError) return alreadyUsedError;\n\tconst raw = readRawBodyIfAvailable(request);\n\tif (raw) {\n\t\tconst result = Promise.resolve(fromBuffer(raw, request));\n\t\trequest[bodyBufferKey] = void 0;\n\t\treturn result;\n\t}\n\treturn readBodyDirect(request).then((buf) => {\n\t\tconst result = fromBuffer(buf, request);\n\t\trequest[bodyBufferKey] = void 0;\n\t\treturn result;\n\t});\n};\nconst readRawBodyIfAvailable = (request) => {\n\tconst incoming = request[incomingKey];\n\tif (\"rawBody\" in incoming && incoming.rawBody instanceof Buffer) return incoming.rawBody;\n};\nconst readBodyDirect = (request) => {\n\tif (request[bodyBufferKey]) return Promise.resolve(request[bodyBufferKey]);\n\tif (request[bodyReadPromiseKey]) return request[bodyReadPromiseKey];\n\tconst incoming = request[incomingKey];\n\tif (Readable.isDisturbed(incoming)) return rejectBodyUnusable();\n\tconst promise = new Promise((resolve, reject) => {\n\t\tconst chunks = [];\n\t\tlet settled = false;\n\t\tconst finish = (callback) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\tcallback();\n\t\t};\n\t\tconst onData = (chunk) => {\n\t\t\tchunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n\t\t};\n\t\tconst onEnd = () => {\n\t\t\tfinish(() => {\n\t\t\t\tconst buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks);\n\t\t\t\trequest[bodyBufferKey] = buffer;\n\t\t\t\tresolve(buffer);\n\t\t\t});\n\t\t};\n\t\tconst onError = (error) => {\n\t\t\tfinish(() => {\n\t\t\t\treject(error);\n\t\t\t});\n\t\t};\n\t\tconst onClose = () => {\n\t\t\tif (incoming.readableEnded) {\n\t\t\t\tonEnd();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfinish(() => {\n\t\t\t\tif (incoming.errored) {\n\t\t\t\t\treject(incoming.errored);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst reason = request[abortReasonKey];\n\t\t\t\tif (reason !== void 0) {\n\t\t\t\t\treject(reason instanceof Error ? reason : new Error(String(reason)));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\treject(/* @__PURE__ */ new Error(\"Client connection prematurely closed.\"));\n\t\t\t});\n\t\t};\n\t\tconst cleanup = () => {\n\t\t\tincoming.off(\"data\", onData);\n\t\t\tincoming.off(\"end\", onEnd);\n\t\t\tincoming.off(\"error\", onError);\n\t\t\tincoming.off(\"close\", onClose);\n\t\t\trequest[bodyReadPromiseKey] = void 0;\n\t\t};\n\t\tincoming.on(\"data\", onData);\n\t\tincoming.on(\"end\", onEnd);\n\t\tincoming.on(\"error\", onError);\n\t\tincoming.on(\"close\", onClose);\n\t\tqueueMicrotask(() => {\n\t\t\tif (settled) return;\n\t\t\tif (incoming.readableEnded) onEnd();\n\t\t\telse if (incoming.errored) onError(incoming.errored);\n\t\t\telse if (incoming.destroyed) onClose();\n\t\t});\n\t});\n\trequest[bodyReadPromiseKey] = promise;\n\treturn promise;\n};\nconst requestPrototype = {\n\tget method() {\n\t\treturn this[methodKey];\n\t},\n\tget url() {\n\t\treturn this[urlKey];\n\t},\n\tget headers() {\n\t\treturn this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);\n\t},\n\t[abortRequest](reason) {\n\t\tif (this[abortReasonKey] === void 0) this[abortReasonKey] = reason;\n\t\tconst abortController = this[abortControllerKey];\n\t\tif (abortController && !abortController.signal.aborted) abortController.abort(reason);\n\t},\n\t[getAbortController]() {\n\t\tthis[abortControllerKey] ||= new AbortController();\n\t\tif (this[abortReasonKey] !== void 0 && !this[abortControllerKey].signal.aborted) this[abortControllerKey].abort(this[abortReasonKey]);\n\t\treturn this[abortControllerKey];\n\t},\n\t[getRequestCache]() {\n\t\tconst abortController = this[getAbortController]();\n\t\tif (this[requestCache]) return this[requestCache];\n\t\tconst method = this.method;\n\t\tif (this[bodyConsumedDirectlyKey] && !(method === \"GET\" || method === \"HEAD\")) {\n\t\t\tthis[bodyBufferKey] = void 0;\n\t\t\tconst init = {\n\t\t\t\tmethod: method === \"TRACE\" ? \"GET\" : method,\n\t\t\t\theaders: this.headers,\n\t\t\t\tsignal: abortController.signal\n\t\t\t};\n\t\t\tif (method !== \"TRACE\") {\n\t\t\t\tinit.body = new ReadableStream({ start(c) {\n\t\t\t\t\tc.close();\n\t\t\t\t} });\n\t\t\t\tinit.duplex = \"half\";\n\t\t\t}\n\t\t\tconst req = new Request$1(this[urlKey], init);\n\t\t\tif (method === \"TRACE\") Object.defineProperty(req, \"method\", { get() {\n\t\t\t\treturn \"TRACE\";\n\t\t\t} });\n\t\t\treturn this[requestCache] = req;\n\t\t}\n\t\treturn this[requestCache] = newRequestFromIncoming(this.method, this[urlKey], this.headers, this[incomingKey], abortController);\n\t},\n\tget body() {\n\t\tif (!this[bodyConsumedDirectlyKey]) return this[getRequestCache]().body;\n\t\tconst request = this[getRequestCache]();\n\t\tif (!this[bodyLockReaderKey] && request.body) this[bodyLockReaderKey] = request.body.getReader();\n\t\treturn request.body;\n\t},\n\tget bodyUsed() {\n\t\tif (this[bodyConsumedDirectlyKey]) return true;\n\t\tif (this[requestCache]) return this[requestCache].bodyUsed;\n\t\treturn false;\n\t}\n};\nObject.defineProperty(requestPrototype, \"signal\", { get() {\n\treturn this[getAbortController]().signal;\n} });\n[\n\t\"cache\",\n\t\"credentials\",\n\t\"destination\",\n\t\"integrity\",\n\t\"mode\",\n\t\"redirect\",\n\t\"referrer\",\n\t\"referrerPolicy\",\n\t\"keepalive\"\n].forEach((k) => {\n\tObject.defineProperty(requestPrototype, k, { get() {\n\t\treturn this[getRequestCache]()[k];\n\t} });\n});\n[\"clone\", \"formData\"].forEach((k) => {\n\tObject.defineProperty(requestPrototype, k, { value: function() {\n\t\tif (this[bodyConsumedDirectlyKey]) {\n\t\t\tif (k === \"clone\") throw newBodyUnusableError();\n\t\t\treturn rejectBodyUnusable();\n\t\t}\n\t\treturn this[getRequestCache]()[k]();\n\t} });\n});\nObject.defineProperty(requestPrototype, \"text\", { value: function() {\n\treturn readBodyWithFastPath(this, \"text\", (buf) => textDecoder.decode(buf));\n} });\nObject.defineProperty(requestPrototype, \"arrayBuffer\", { value: function() {\n\treturn readBodyWithFastPath(this, \"arrayBuffer\", (buf) => toArrayBuffer(buf));\n} });\nObject.defineProperty(requestPrototype, \"blob\", { value: function() {\n\treturn readBodyWithFastPath(this, \"blob\", (buf, request) => {\n\t\tconst type = contentType(request);\n\t\tconst init = type ? { headers: { \"content-type\": type } } : void 0;\n\t\treturn new Response(buf, init).blob();\n\t});\n} });\nObject.defineProperty(requestPrototype, \"json\", { value: function() {\n\tif (this[bodyConsumedDirectlyKey]) return rejectBodyUnusable();\n\treturn this.text().then(JSON.parse);\n} });\nObject.defineProperty(requestPrototype, Symbol.for(\"nodejs.util.inspect.custom\"), { value: function(depth, options, inspectFn) {\n\treturn `Request (lightweight) ${inspectFn({\n\t\tmethod: this.method,\n\t\turl: this.url,\n\t\theaders: this.headers,\n\t\tnativeRequest: this[requestCache]\n\t}, {\n\t\t...options,\n\t\tdepth: depth == null ? null : depth - 1\n\t})}`;\n} });\nObject.setPrototypeOf(requestPrototype, Request$1.prototype);\nconst newRequest = (incoming, defaultHostname) => {\n\tconst req = Object.create(requestPrototype);\n\treq[incomingKey] = incoming;\n\treq[methodKey] = normalizeIncomingMethod(incoming.method);\n\tconst incomingUrl = incoming.url || \"\";\n\tif (incomingUrl[0] !== \"/\" && (incomingUrl.startsWith(\"http://\") || incomingUrl.startsWith(\"https://\"))) {\n\t\tif (incoming instanceof Http2ServerRequest) throw new RequestError(\"Absolute URL for :path is not allowed in HTTP/2\");\n\t\ttry {\n\t\t\treq[urlKey] = new URL(incomingUrl).href;\n\t\t} catch (e) {\n\t\t\tthrow new RequestError(\"Invalid absolute URL\", { cause: e });\n\t\t}\n\t\treturn req;\n\t}\n\tconst host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;\n\tif (!host) throw new RequestError(\"Missing host header\");\n\tlet scheme;\n\tif (incoming instanceof Http2ServerRequest) {\n\t\tscheme = incoming.scheme;\n\t\tif (!(scheme === \"http\" || scheme === \"https\")) throw new RequestError(\"Unsupported scheme\");\n\t} else scheme = incoming.socket && incoming.socket.encrypted ? \"https\" : \"http\";\n\ttry {\n\t\treq[urlKey] = buildUrl(scheme, host, incomingUrl);\n\t} catch (e) {\n\t\tif (e instanceof RequestError) throw e;\n\t\telse throw new RequestError(\"Invalid URL\", { cause: e });\n\t}\n\treturn req;\n};\n\n//#endregion\n//#region src/response.ts\nconst defaultContentType = \"text/plain; charset=UTF-8\";\nconst responseCache = Symbol(\"responseCache\");\nconst getResponseCache = Symbol(\"getResponseCache\");\nconst cacheKey = Symbol(\"cache\");\nconst GlobalResponse = global.Response;\nvar Response$1 = class Response$1 {\n\t#body;\n\t#init;\n\t[getResponseCache]() {\n\t\tconst cache = this[cacheKey];\n\t\tconst liveHeaders = cache && cache[2] instanceof Headers ? cache[2] : void 0;\n\t\tdelete this[cacheKey];\n\t\treturn this[responseCache] ||= new GlobalResponse(this.#body, liveHeaders ? {\n\t\t\tstatus: this.#init?.status,\n\t\t\tstatusText: this.#init?.statusText,\n\t\t\theaders: liveHeaders\n\t\t} : this.#init);\n\t}\n\tconstructor(body, init) {\n\t\tlet headers;\n\t\tthis.#body = body;\n\t\tif (init instanceof Response$1) {\n\t\t\tconst cachedGlobalResponse = init[responseCache];\n\t\t\tif (cachedGlobalResponse) {\n\t\t\t\tthis.#init = cachedGlobalResponse;\n\t\t\t\tthis[getResponseCache]();\n\t\t\t\treturn;\n\t\t\t} else {\n\t\t\t\tthis.#init = init.#init;\n\t\t\t\theaders = new Headers(init.headers);\n\t\t\t}\n\t\t} else this.#init = init;\n\t\tif (body == null || typeof body === \"string\" || typeof body?.getReader !== \"undefined\" || body instanceof Blob || body instanceof Uint8Array) this[cacheKey] = [\n\t\t\tinit?.status || 200,\n\t\t\tbody ?? null,\n\t\t\theaders || init?.headers\n\t\t];\n\t}\n\tget headers() {\n\t\tconst cache = this[cacheKey];\n\t\tif (cache) {\n\t\t\tif (!(cache[2] instanceof Headers)) cache[2] = new Headers(cache[2] || (cache[1] === null ? void 0 : { \"content-type\": defaultContentType }));\n\t\t\treturn cache[2];\n\t\t}\n\t\treturn this[getResponseCache]().headers;\n\t}\n\tget status() {\n\t\treturn this[cacheKey]?.[0] ?? this[getResponseCache]().status;\n\t}\n\tget ok() {\n\t\tconst status = this.status;\n\t\treturn status >= 200 && status < 300;\n\t}\n};\n[\n\t\"body\",\n\t\"bodyUsed\",\n\t\"redirected\",\n\t\"statusText\",\n\t\"trailers\",\n\t\"type\",\n\t\"url\"\n].forEach((k) => {\n\tObject.defineProperty(Response$1.prototype, k, { get() {\n\t\treturn this[getResponseCache]()[k];\n\t} });\n});\n[\n\t\"arrayBuffer\",\n\t\"blob\",\n\t\"clone\",\n\t\"formData\",\n\t\"json\",\n\t\"text\"\n].forEach((k) => {\n\tObject.defineProperty(Response$1.prototype, k, { value: function() {\n\t\treturn this[getResponseCache]()[k]();\n\t} });\n});\nObject.defineProperty(Response$1.prototype, Symbol.for(\"nodejs.util.inspect.custom\"), { value: function(depth, options, inspectFn) {\n\treturn `Response (lightweight) ${inspectFn({\n\t\tstatus: this.status,\n\t\theaders: this.headers,\n\t\tok: this.ok,\n\t\tnativeResponse: this[responseCache]\n\t}, {\n\t\t...options,\n\t\tdepth: depth == null ? null : depth - 1\n\t})}`;\n} });\nObject.setPrototypeOf(Response$1, GlobalResponse);\nObject.setPrototypeOf(Response$1.prototype, GlobalResponse.prototype);\nconst validRedirectUrl = /^https?:\\/\\/[!#-;=?-[\\]_a-z~A-Z]+$/;\nconst parseRedirectUrl = (url) => {\n\tif (url instanceof URL) return url.href;\n\tif (validRedirectUrl.test(url)) return url;\n\treturn new URL(url).href;\n};\nconst validRedirectStatuses = new Set([\n\t301,\n\t302,\n\t303,\n\t307,\n\t308\n]);\nObject.defineProperty(Response$1, \"redirect\", {\n\tvalue: function redirect(url, status = 302) {\n\t\tif (!validRedirectStatuses.has(status)) throw new RangeError(\"Invalid status code\");\n\t\treturn new Response$1(null, {\n\t\t\tstatus,\n\t\t\theaders: { location: parseRedirectUrl(url) }\n\t\t});\n\t},\n\twritable: true,\n\tconfigurable: true\n});\nObject.defineProperty(Response$1, \"json\", {\n\tvalue: function json(data, init) {\n\t\tconst body = JSON.stringify(data);\n\t\tif (body === void 0) throw new TypeError(\"The data is not JSON serializable\");\n\t\tconst initHeaders = init?.headers;\n\t\tlet headers;\n\t\tif (initHeaders) {\n\t\t\theaders = new Headers(initHeaders);\n\t\t\tif (!headers.has(\"content-type\")) headers.set(\"content-type\", \"application/json\");\n\t\t} else headers = { \"content-type\": \"application/json\" };\n\t\treturn new Response$1(body, {\n\t\t\tstatus: init?.status ?? 200,\n\t\t\tstatusText: init?.statusText,\n\t\t\theaders\n\t\t});\n\t},\n\twritable: true,\n\tconfigurable: true\n});\n\n//#endregion\n//#region src/utils.ts\nasync function readWithoutBlocking(readPromise) {\n\treturn Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);\n}\nfunction writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {\n\tconst cancel = (error) => {\n\t\treader.cancel(error).catch(() => {});\n\t};\n\twritable.on(\"close\", cancel);\n\twritable.on(\"error\", cancel);\n\t(currentReadPromise ?? reader.read()).then(flow, handleStreamError);\n\treturn reader.closed.finally(() => {\n\t\twritable.off(\"close\", cancel);\n\t\twritable.off(\"error\", cancel);\n\t});\n\tfunction handleStreamError(error) {\n\t\tif (error) writable.destroy(error);\n\t}\n\tfunction onDrain() {\n\t\treader.read().then(flow, handleStreamError);\n\t}\n\tfunction flow({ done, value }) {\n\t\ttry {\n\t\t\tif (done) writable.end();\n\t\t\telse if (!writable.write(value)) writable.once(\"drain\", onDrain);\n\t\t\telse return reader.read().then(flow, handleStreamError);\n\t\t} catch (e) {\n\t\t\thandleStreamError(e);\n\t\t}\n\t}\n}\nfunction writeFromReadableStream(stream, writable) {\n\tif (stream.locked) throw new TypeError(\"ReadableStream is locked.\");\n\telse if (writable.destroyed) return;\n\treturn writeFromReadableStreamDefaultReader(stream.getReader(), writable);\n}\nconst buildOutgoingHttpHeaders = (headers, defaultContentType) => {\n\tconst res = {};\n\tif (!(headers instanceof Headers)) headers = new Headers(headers ?? void 0);\n\tif (headers.has(\"set-cookie\")) {\n\t\tconst cookies = [];\n\t\tfor (const [k, v] of headers) if (k === \"set-cookie\") cookies.push(v);\n\t\telse res[k] = v;\n\t\tif (cookies.length > 0) res[\"set-cookie\"] = cookies;\n\t} else for (const [k, v] of headers) res[k] = v;\n\tif (defaultContentType) res[\"content-type\"] ??= defaultContentType;\n\treturn res;\n};\n\n//#endregion\n//#region src/listener.ts\nconst outgoingEnded = Symbol(\"outgoingEnded\");\nconst incomingDraining = Symbol(\"incomingDraining\");\nconst DRAIN_TIMEOUT_MS = 500;\nconst MAX_DRAIN_BYTES = 64 * 1024 * 1024;\nconst drainIncoming = (incoming) => {\n\tconst incomingWithDrainState = incoming;\n\tif (incoming.destroyed || incomingWithDrainState[incomingDraining]) return;\n\tincomingWithDrainState[incomingDraining] = true;\n\tif (incoming instanceof Http2ServerRequest) {\n\t\ttry {\n\t\t\tincoming.stream?.close?.(constants.NGHTTP2_NO_ERROR);\n\t\t} catch {}\n\t\treturn;\n\t}\n\tlet bytesRead = 0;\n\tconst cleanup = () => {\n\t\tclearTimeout(timer);\n\t\tincoming.off(\"data\", onData);\n\t\tincoming.off(\"end\", cleanup);\n\t\tincoming.off(\"error\", cleanup);\n\t};\n\tconst forceClose = () => {\n\t\tcleanup();\n\t\tconst socket = incoming.socket;\n\t\tif (socket && !socket.destroyed) socket.destroySoon();\n\t};\n\tconst timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);\n\ttimer.unref?.();\n\tconst onData = (chunk) => {\n\t\tbytesRead += chunk.length;\n\t\tif (bytesRead > MAX_DRAIN_BYTES) forceClose();\n\t};\n\tincoming.on(\"data\", onData);\n\tincoming.on(\"end\", cleanup);\n\tincoming.on(\"error\", cleanup);\n\tincoming.resume();\n};\nconst makeCloseHandler = (req, incoming, outgoing, needsBodyCleanup) => () => {\n\tif (incoming.errored) req[abortRequest](incoming.errored.toString());\n\telse if (!outgoing.writableFinished) req[abortRequest](\"Client connection prematurely closed.\");\n\tif (needsBodyCleanup && !incoming.readableEnded) setTimeout(() => {\n\t\tif (!incoming.readableEnded) setTimeout(() => {\n\t\t\tdrainIncoming(incoming);\n\t\t});\n\t});\n};\nconst isImmediateCacheableResponse = (res) => {\n\tif (!(cacheKey in res)) return false;\n\tconst body = res[cacheKey][1];\n\treturn body === null || typeof body === \"string\" || body instanceof Uint8Array;\n};\nconst handleRequestError = () => new Response(null, { status: 400 });\nconst handleFetchError = (e) => new Response(null, { status: e instanceof Error && (e.name === \"TimeoutError\" || e.constructor.name === \"TimeoutError\") ? 504 : 500 });\nconst handleResponseError = (e, outgoing) => {\n\tconst err = e instanceof Error ? e : new Error(\"unknown error\", { cause: e });\n\tif (err.code === \"ERR_STREAM_PREMATURE_CLOSE\") console.info(\"The user aborted a request.\");\n\telse {\n\t\tconsole.error(e);\n\t\tif (!outgoing.headersSent) outgoing.writeHead(500, { \"Content-Type\": \"text/plain\" });\n\t\toutgoing.end(`Error: ${err.message}`);\n\t\toutgoing.destroy(err);\n\t}\n};\nconst flushHeaders = (outgoing) => {\n\tif (\"flushHeaders\" in outgoing && outgoing.writable) outgoing.flushHeaders();\n};\nconst responseViaCache = async (res, outgoing) => {\n\tlet [status, body, header] = res[cacheKey];\n\tif (!header) {\n\t\tif (body === null) {\n\t\t\toutgoing.writeHead(status);\n\t\t\toutgoing.end();\n\t\t} else if (typeof body === \"string\") {\n\t\t\toutgoing.writeHead(status, {\n\t\t\t\t\"Content-Type\": defaultContentType,\n\t\t\t\t\"Content-Length\": Buffer.byteLength(body)\n\t\t\t});\n\t\t\toutgoing.end(body);\n\t\t} else if (body instanceof Uint8Array) {\n\t\t\toutgoing.writeHead(status, {\n\t\t\t\t\"Content-Type\": defaultContentType,\n\t\t\t\t\"Content-Length\": body.byteLength\n\t\t\t});\n\t\t\toutgoing.end(body);\n\t\t} else if (body instanceof Blob) {\n\t\t\toutgoing.writeHead(status, {\n\t\t\t\t\"Content-Type\": defaultContentType,\n\t\t\t\t\"Content-Length\": body.size\n\t\t\t});\n\t\t\toutgoing.end(new Uint8Array(await body.arrayBuffer()));\n\t\t} else {\n\t\t\toutgoing.writeHead(status, { \"Content-Type\": defaultContentType });\n\t\t\tflushHeaders(outgoing);\n\t\t\tawait writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));\n\t\t}\n\t\toutgoing[outgoingEnded]?.();\n\t\treturn;\n\t}\n\tlet hasContentLength = false;\n\tif (header instanceof Headers) {\n\t\thasContentLength = header.has(\"content-length\");\n\t\theader = buildOutgoingHttpHeaders(header, body === null ? void 0 : defaultContentType);\n\t} else if (Array.isArray(header)) {\n\t\tconst headerObj = new Headers(header);\n\t\thasContentLength = headerObj.has(\"content-length\");\n\t\theader = buildOutgoingHttpHeaders(headerObj, body === null ? void 0 : defaultContentType);\n\t} else for (const key in header) if (key.length === 14 && key.toLowerCase() === \"content-length\") {\n\t\thasContentLength = true;\n\t\tbreak;\n\t}\n\tif (!hasContentLength) {\n\t\tif (typeof body === \"string\") header[\"Content-Length\"] = Buffer.byteLength(body);\n\t\telse if (body instanceof Uint8Array) header[\"Content-Length\"] = body.byteLength;\n\t\telse if (body instanceof Blob) header[\"Content-Length\"] = body.size;\n\t}\n\toutgoing.writeHead(status, header);\n\tif (body == null) outgoing.end();\n\telse if (typeof body === \"string\" || body instanceof Uint8Array) outgoing.end(body);\n\telse if (body instanceof Blob) outgoing.end(new Uint8Array(await body.arrayBuffer()));\n\telse {\n\t\tflushHeaders(outgoing);\n\t\tawait writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));\n\t}\n\toutgoing[outgoingEnded]?.();\n};\nconst isPromise = (res) => typeof res.then === \"function\";\nconst responseViaResponseObject = async (res, outgoing, options = {}) => {\n\tif (isPromise(res)) if (options.errorHandler) try {\n\t\tres = await res;\n\t} catch (err) {\n\t\tconst errRes = await options.errorHandler(err);\n\t\tif (!errRes) return;\n\t\tres = errRes;\n\t}\n\telse res = await res.catch(handleFetchError);\n\tif (cacheKey in res) return responseViaCache(res, outgoing);\n\tconst resHeaderRecord = buildOutgoingHttpHeaders(res.headers, res.body === null ? void 0 : defaultContentType);\n\tif (res.body) {\n\t\tconst reader = res.body.getReader();\n\t\tconst values = [];\n\t\tlet done = false;\n\t\tlet currentReadPromise = void 0;\n\t\tif (resHeaderRecord[\"transfer-encoding\"] !== \"chunked\") {\n\t\t\tlet maxReadCount = 2;\n\t\t\tfor (let i = 0; i < maxReadCount; i++) {\n\t\t\t\tcurrentReadPromise ||= reader.read();\n\t\t\t\tconst chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {\n\t\t\t\t\tconsole.error(e);\n\t\t\t\t\tdone = true;\n\t\t\t\t});\n\t\t\t\tif (!chunk) {\n\t\t\t\t\tif (i === 1) {\n\t\t\t\t\t\tawait new Promise((resolve) => setTimeout(resolve));\n\t\t\t\t\t\tmaxReadCount = 3;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcurrentReadPromise = void 0;\n\t\t\t\tif (chunk.value) values.push(chunk.value);\n\t\t\t\tif (chunk.done) {\n\t\t\t\t\tdone = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (done && !(\"content-length\" in resHeaderRecord)) resHeaderRecord[\"content-length\"] = values.reduce((acc, value) => acc + value.length, 0);\n\t\t}\n\t\toutgoing.writeHead(res.status, resHeaderRecord);\n\t\tvalues.forEach((value) => {\n\t\t\toutgoing.write(value);\n\t\t});\n\t\tif (done) outgoing.end();\n\t\telse {\n\t\t\tif (values.length === 0) flushHeaders(outgoing);\n\t\t\tawait writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);\n\t\t}\n\t} else if (resHeaderRecord[X_ALREADY_SENT]) {} else {\n\t\toutgoing.writeHead(res.status, resHeaderRecord);\n\t\toutgoing.end();\n\t}\n\toutgoing[outgoingEnded]?.();\n};\nconst getRequestListener = (fetchCallback, options = {}) => {\n\tconst autoCleanupIncoming = options.autoCleanupIncoming ?? true;\n\tif (options.overrideGlobalObjects !== false && global.Request !== Request$1) {\n\t\tObject.defineProperty(global, \"Request\", { value: Request$1 });\n\t\tObject.defineProperty(global, \"Response\", { value: Response$1 });\n\t}\n\treturn async (incoming, outgoing) => {\n\t\tlet res, req;\n\t\tlet needsBodyCleanup = false;\n\t\tlet closeHandlerAttached = false;\n\t\tconst ensureCloseHandler = () => {\n\t\t\tif (!req || closeHandlerAttached) return;\n\t\t\tcloseHandlerAttached = true;\n\t\t\toutgoing.on(\"close\", makeCloseHandler(req, incoming, outgoing, needsBodyCleanup));\n\t\t};\n\t\ttry {\n\t\t\treq = newRequest(incoming, options.hostname);\n\t\t\tneedsBodyCleanup = autoCleanupIncoming && !(incoming.method === \"GET\" || incoming.method === \"HEAD\");\n\t\t\tif (needsBodyCleanup) {\n\t\t\t\tincoming[wrapBodyStream] = true;\n\t\t\t\tif (incoming instanceof Http2ServerRequest) outgoing[outgoingEnded] = () => {\n\t\t\t\t\tif (!incoming.readableEnded) setTimeout(() => {\n\t\t\t\t\t\tif (!incoming.readableEnded) setTimeout(() => {\n\t\t\t\t\t\t\tincoming.destroy();\n\t\t\t\t\t\t\toutgoing.destroy();\n\t\t\t\t\t\t});\n\t\t\t\t\t});\n\t\t\t\t};\n\t\t\t}\n\t\t\tres = fetchCallback(req, {\n\t\t\t\tincoming,\n\t\t\t\toutgoing\n\t\t\t});\n\t\t\tif (!isPromise(res) && isImmediateCacheableResponse(res)) {\n\t\t\t\tif (needsBodyCleanup && !incoming.readableEnded) outgoing.once(\"finish\", () => {\n\t\t\t\t\tif (!incoming.readableEnded) drainIncoming(incoming);\n\t\t\t\t});\n\t\t\t\treturn responseViaCache(res, outgoing);\n\t\t\t}\n\t\t\tensureCloseHandler();\n\t\t} catch (e) {\n\t\t\tif (!res) if (options.errorHandler) {\n\t\t\t\tensureCloseHandler();\n\t\t\t\tres = await options.errorHandler(req ? e : toRequestError(e));\n\t\t\t\tif (!res) return;\n\t\t\t} else if (!req) res = handleRequestError();\n\t\t\telse res = handleFetchError(e);\n\t\t\telse return handleResponseError(e, outgoing);\n\t\t}\n\t\ttry {\n\t\t\treturn await responseViaResponseObject(res, outgoing, options);\n\t\t} catch (e) {\n\t\t\treturn handleResponseError(e, outgoing);\n\t\t}\n\t};\n};\n\n//#endregion\n//#region src/websocket.ts\n/**\n* @link https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent\n*/\nconst CloseEvent = globalThis.CloseEvent ?? class extends Event {\n\t#eventInitDict;\n\tconstructor(type, eventInitDict = {}) {\n\t\tsuper(type, eventInitDict);\n\t\tthis.#eventInitDict = eventInitDict;\n\t}\n\tget wasClean() {\n\t\treturn this.#eventInitDict.wasClean ?? false;\n\t}\n\tget code() {\n\t\treturn this.#eventInitDict.code ?? 0;\n\t}\n\tget reason() {\n\t\treturn this.#eventInitDict.reason ?? \"\";\n\t}\n};\nconst generateConnectionSymbol = () => Symbol(\"connection\");\nconst CONNECTION_SYMBOL_KEY = Symbol(\"CONNECTION_SYMBOL_KEY\");\nconst WAIT_FOR_WEBSOCKET_SYMBOL = Symbol(\"WAIT_FOR_WEBSOCKET_SYMBOL\");\nconst responseHeadersToSkip = new Set([\n\t\"connection\",\n\t\"content-length\",\n\t\"keep-alive\",\n\t\"proxy-authenticate\",\n\t\"proxy-authorization\",\n\t\"te\",\n\t\"trailer\",\n\t\"transfer-encoding\",\n\t\"upgrade\",\n\t\"sec-websocket-accept\",\n\t\"sec-websocket-extensions\",\n\t\"sec-websocket-protocol\"\n]);\nconst appendResponseHeaders = (headers, responseHeaders) => {\n\tif (!responseHeaders) return;\n\tresponseHeaders.forEach((value, key) => {\n\t\tif (responseHeadersToSkip.has(key.toLowerCase())) return;\n\t\theaders.push(`${key}: ${value}`);\n\t});\n};\nconst rejectUpgradeRequest = (socket, status, responseHeaders) => {\n\tconst responseLines = [\"Connection: close\", \"Content-Length: 0\"];\n\tappendResponseHeaders(responseLines, responseHeaders);\n\tsocket.end(`HTTP/1.1 ${status.toString()} ${STATUS_CODES[status] ?? \"\"}\\r\\n${responseLines.join(\"\\r\\n\")}\\r\\n\\r\n`);\n};\nconst createUpgradeRequest = (request) => {\n\tconst protocol = request.socket.encrypted ? \"https\" : \"http\";\n\tconst url = new URL(request.url ?? \"/\", `${protocol}://${request.headers.host ?? \"localhost\"}`);\n\tconst headers = new Headers();\n\tfor (const key in request.headers) {\n\t\tconst value = request.headers[key];\n\t\tif (!value) continue;\n\t\theaders.append(key, Array.isArray(value) ? value[0] : value);\n\t}\n\treturn new Request(url, { headers });\n};\nconst setupWebSocket = (options) => {\n\tconst { server, fetchCallback, wss } = options;\n\tconst waiterMap = /* @__PURE__ */ new Map();\n\twss.on(\"connection\", (ws, request) => {\n\t\tconst waiter = waiterMap.get(request);\n\t\tif (waiter) {\n\t\t\twaiter.resolve(ws);\n\t\t\twaiterMap.delete(request);\n\t\t}\n\t});\n\tconst waitForWebSocket = (request, connectionSymbol) => {\n\t\treturn new Promise((resolve) => {\n\t\t\twaiterMap.set(request, {\n\t\t\t\tresolve,\n\t\t\t\tconnectionSymbol\n\t\t\t});\n\t\t});\n\t};\n\tserver.on(\"upgrade\", async (request, socket, head) => {\n\t\tif (request.headers.upgrade?.toLowerCase() !== \"websocket\") return;\n\t\tconst env = {\n\t\t\tincoming: request,\n\t\t\toutgoing: void 0,\n\t\t\twss,\n\t\t\t[WAIT_FOR_WEBSOCKET_SYMBOL]: waitForWebSocket\n\t\t};\n\t\tlet status = 400;\n\t\tlet responseHeaders;\n\t\ttry {\n\t\t\tconst response = await fetchCallback(createUpgradeRequest(request), env);\n\t\t\tif (response instanceof Response) {\n\t\t\t\tstatus = response.status;\n\t\t\t\tresponseHeaders = response.headers;\n\t\t\t}\n\t\t} catch {\n\t\t\tif (server.listenerCount(\"upgrade\") === 1) rejectUpgradeRequest(socket, 500);\n\t\t\treturn;\n\t\t}\n\t\tconst waiter = waiterMap.get(request);\n\t\tif (!waiter || waiter.connectionSymbol !== env[CONNECTION_SYMBOL_KEY]) {\n\t\t\twaiterMap.delete(request);\n\t\t\tif (server.listenerCount(\"upgrade\") === 1) rejectUpgradeRequest(socket, status, responseHeaders);\n\t\t\treturn;\n\t\t}\n\t\tconst addResponseHeaders = (headers) => {\n\t\t\tappendResponseHeaders(headers, responseHeaders);\n\t\t};\n\t\twss.on(\"headers\", addResponseHeaders);\n\t\ttry {\n\t\t\twss.handleUpgrade(request, socket, head, (ws) => {\n\t\t\t\twss.emit(\"connection\", ws, request);\n\t\t\t});\n\t\t} finally {\n\t\t\twss.off(\"headers\", addResponseHeaders);\n\t\t}\n\t});\n\tserver.on(\"close\", () => {\n\t\twss.close();\n\t});\n};\nconst upgradeWebSocket = defineWebSocketHelper(async (c, events, options) => {\n\tif (c.req.header(\"upgrade\")?.toLowerCase() !== \"websocket\") return;\n\tconst env = c.env;\n\tconst waitForWebSocket = env[WAIT_FOR_WEBSOCKET_SYMBOL];\n\tif (!waitForWebSocket || !env.incoming) return new Response(null, { status: 500 });\n\tconst connectionSymbol = generateConnectionSymbol();\n\tenv[CONNECTION_SYMBOL_KEY] = connectionSymbol;\n\t(async () => {\n\t\tconst ws = await waitForWebSocket(env.incoming, connectionSymbol);\n\t\tconst messagesReceivedInStarting = [];\n\t\tconst bufferMessage = (data, isBinary) => {\n\t\t\tmessagesReceivedInStarting.push([data, isBinary]);\n\t\t};\n\t\tws.on(\"message\", bufferMessage);\n\t\tconst ctx = {\n\t\t\tbinaryType: \"arraybuffer\",\n\t\t\tclose(code, reason) {\n\t\t\t\tws.close(code, reason);\n\t\t\t},\n\t\t\tprotocol: ws.protocol,\n\t\t\traw: ws,\n\t\t\tget readyState() {\n\t\t\t\treturn ws.readyState;\n\t\t\t},\n\t\t\tsend(source, opts) {\n\t\t\t\tws.send(source, { compress: opts?.compress });\n\t\t\t},\n\t\t\turl: new URL(c.req.url)\n\t\t};\n\t\ttry {\n\t\t\tevents?.onOpen?.(new Event(\"open\"), ctx);\n\t\t} catch (e) {\n\t\t\t(options?.onError ?? console.error)(e);\n\t\t}\n\t\tconst handleMessage = (data, isBinary) => {\n\t\t\tconst datas = Array.isArray(data) ? data : [data];\n\t\t\tfor (const data of datas) try {\n\t\t\t\tevents?.onMessage?.(new MessageEvent(\"message\", { data: isBinary ? data instanceof ArrayBuffer ? data : data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength) : typeof data === \"string\" ? data : Buffer.from(data).toString(\"utf-8\") }), ctx);\n\t\t\t} catch (e) {\n\t\t\t\t(options?.onError ?? console.error)(e);\n\t\t\t}\n\t\t};\n\t\tws.off(\"message\", bufferMessage);\n\t\tfor (const message of messagesReceivedInStarting) handleMessage(...message);\n\t\tws.on(\"message\", (data, isBinary) => {\n\t\t\thandleMessage(data, isBinary);\n\t\t});\n\t\tws.on(\"close\", (code, reason) => {\n\t\t\ttry {\n\t\t\t\tevents?.onClose?.(new CloseEvent(\"close\", {\n\t\t\t\t\tcode,\n\t\t\t\t\treason: reason.toString()\n\t\t\t\t}), ctx);\n\t\t\t} catch (e) {\n\t\t\t\t(options?.onError ?? console.error)(e);\n\t\t\t}\n\t\t});\n\t\tws.on(\"error\", (error) => {\n\t\t\ttry {\n\t\t\t\tevents?.onError?.(new ErrorEvent(\"error\", { error }), ctx);\n\t\t\t} catch (e) {\n\t\t\t\t(options?.onError ?? console.error)(e);\n\t\t\t}\n\t\t});\n\t})();\n\treturn new Response();\n});\n\n//#endregion\n//#region src/server.ts\nconst createAdaptorServer = (options) => {\n\tconst fetchCallback = options.fetch;\n\tconst requestListener = getRequestListener(fetchCallback, {\n\t\thostname: options.hostname,\n\t\toverrideGlobalObjects: options.overrideGlobalObjects,\n\t\tautoCleanupIncoming: options.autoCleanupIncoming\n\t});\n\tconst server = (options.createServer || createServer)(options.serverOptions || {}, requestListener);\n\tif (options.websocket && options.websocket.server) {\n\t\tif (options.websocket.server.options.noServer !== true) throw new Error(\"WebSocket server must be created with { noServer: true } option\");\n\t\tsetupWebSocket({\n\t\t\tserver,\n\t\t\tfetchCallback,\n\t\t\twss: options.websocket.server\n\t\t});\n\t}\n\treturn server;\n};\nconst serve = (options, listeningListener) => {\n\tconst server = createAdaptorServer(options);\n\tserver.listen(options?.port ?? 3e3, options.hostname, () => {\n\t\tconst serverInfo = server.address();\n\t\tlisteningListener && listeningListener(serverInfo);\n\t});\n\treturn server;\n};\n\n//#endregion\nexport { RequestError, createAdaptorServer, getRequestListener, serve, upgradeWebSocket };","import { readFileSync } from 'node:fs';\nimport type { Hono } from 'hono';\n\n// Process start, captured once at module load (bundled into each consumer, so this is\n// effectively the consumer process's start time).\nconst START_TIME = Date.now();\n\nlet shutdownHandler: (() => void) | null = null;\n\n/** Register the graceful-shutdown closure that `POST /admin/shutdown` invokes. Called by startServer. */\nexport function setShutdownHandler(fn: () => void): void {\n shutdownHandler = fn;\n}\n\n/**\n * Read the consuming package's version from its package.json at runtime.\n *\n * Pass `import.meta.url` from the CONSUMER module. core is bundled into each consumer, so\n * after the build this code runs from the consumer's `dist/` and package.json sits one\n * level up (`../package.json`). Never throws — returns 'unknown' on any failure.\n */\nexport function readPackageVersion(metaUrl: string): string {\n try {\n const pkg = JSON.parse(readFileSync(new URL('../package.json', metaUrl), 'utf8')) as {\n version?: string;\n };\n return pkg.version ?? 'unknown';\n } catch {\n return 'unknown';\n }\n}\n\nexport interface BaseStatus {\n ok: true;\n version: string;\n startedAt: string;\n uptimeSeconds: number;\n}\n\nexport interface AdminRoutesOptions {\n /** Server version, typically `readPackageVersion(import.meta.url)`. */\n version: string;\n /** App-specific fields merged into the `/admin/status` payload (e.g. validator/pin counts). */\n getStatus?: () => Record<string, unknown>;\n}\n\n/**\n * Register the admin surface shared by every sm-lab service:\n * GET /admin/status → { ok, version, startedAt, uptimeSeconds, ...getStatus() }\n * POST /admin/shutdown → graceful shutdown (deferred 50ms so the response flushes first)\n */\nexport function registerAdminRoutes(app: Hono, opts: AdminRoutesOptions): void {\n app.get('/admin/status', (c) => {\n const base: BaseStatus = {\n ok: true,\n version: opts.version,\n startedAt: new Date(START_TIME).toISOString(),\n uptimeSeconds: Math.floor((Date.now() - START_TIME) / 1000),\n };\n return c.json({ ...base, ...opts.getStatus?.() });\n });\n\n app.post('/admin/shutdown', (c) => {\n if (shutdownHandler) setTimeout(shutdownHandler, 50);\n return c.json({ message: 'shutting down' });\n });\n}\n","import { Command } from 'commander';\n\n/** Climb to the root program so commands at any nesting depth can read root-level options (e.g. --url). */\nexport function findRoot(cmd: Command): Command {\n let c = cmd;\n while (c.parent) c = c.parent;\n return c;\n}\n\nexport interface ClientTarget {\n /** Env var holding the server URL (e.g. CL_MOCK_URL). */\n envVar: string;\n /** Default port when neither --url nor the env var is set. */\n defaultPort: number;\n}\n\n/** Resolve the target server URL: root `--url` option → env var → `http://127.0.0.1:<defaultPort>`. */\nexport function resolveUrl(cmd: Command, target: ClientTarget): string {\n const opts = findRoot(cmd).opts() as { url?: string };\n return opts.url ?? process.env[target.envVar] ?? `http://127.0.0.1:${target.defaultPort}`;\n}\n\n/** Format seconds as a compact `1h 2m 3s` string (omits leading zero units). */\nexport function formatUptime(seconds: number): string {\n const h = Math.floor(seconds / 3600);\n const m = Math.floor((seconds % 3600) / 60);\n const s = seconds % 60;\n const parts: string[] = [];\n if (h) parts.push(`${h}h`);\n if (m || h) parts.push(`${m}m`);\n parts.push(`${s}s`);\n return parts.join(' ');\n}\n\nexport interface BaseStatusResponse {\n ok: boolean;\n version: string;\n startedAt: string;\n uptimeSeconds: number;\n}\n\nexport interface StatusCommandOptions<T extends BaseStatusResponse> extends ClientTarget {\n /** App-specific help text; defaults to 'Show status of a running server'. */\n description?: string;\n /** Print app-specific lines after the shared header (URL/Status/Version/Started/Uptime). */\n render?: (data: T, url: string) => void;\n}\n\n/**\n * Build a `status` command: GET /admin/status, print the shared header, then app-specific\n * lines via `render`. `--json` dumps the raw payload. On connect failure prints\n * `Error: <url> offline (<reason>)` to stderr and exits 1 — offline is a legitimate answer, and\n * the `Error:` prefix + exit 1 keep the machine I/O contract uniform with the other commands.\n */\nexport function createStatusCommand<T extends BaseStatusResponse>(\n opts: StatusCommandOptions<T>,\n): Command {\n return new Command('status')\n .description(opts.description ?? 'Show status of a running server')\n .option('--json', 'output raw JSON')\n .action(async (cmdOpts: { json?: boolean }, cmd: Command) => {\n const url = resolveUrl(cmd, opts);\n let res: Response;\n try {\n res = await fetch(`${url}/admin/status`);\n } catch (err) {\n console.error(\n 'Error:',\n `${url} offline (${err instanceof Error ? err.message : String(err)})`,\n );\n process.exit(1);\n }\n if (!res.ok) {\n console.error(`Unexpected response: ${res.status}`);\n process.exit(1);\n }\n const data = (await res.json()) as T;\n if (cmdOpts.json) {\n console.log(JSON.stringify(data, null, 2));\n return;\n }\n console.log(`URL: ${url}`);\n console.log(`Status: ok`);\n console.log(`Version: ${data.version}`);\n console.log(`Started: ${data.startedAt}`);\n console.log(`Uptime: ${formatUptime(data.uptimeSeconds)}`);\n opts.render?.(data, url);\n });\n}\n\nexport interface StopCommandOptions extends ClientTarget {\n /** App-specific help text; defaults to 'Stop a running server'. */\n description?: string;\n}\n\n/** Build a `stop` command: POST /admin/shutdown to the resolved URL. */\nexport function createStopCommand(target: StopCommandOptions): Command {\n return new Command('stop')\n .description(target.description ?? 'Stop a running server')\n .action(async (_cmdOpts: unknown, cmd: Command) => {\n const url = resolveUrl(cmd, target);\n let res: Response;\n try {\n res = await fetch(`${url}/admin/shutdown`, { method: 'POST' });\n } catch (err) {\n console.error(\n `Failed to connect to ${url}: ${err instanceof Error ? err.message : String(err)}`,\n );\n process.exit(1);\n }\n if (res.ok) {\n console.log('Server shutting down');\n } else {\n console.error(`Unexpected response: ${res.status}`);\n process.exit(1);\n }\n });\n}\n","import { Argument, Command } from 'commander';\nimport type { Option } from 'commander';\nimport { findRoot } from './cli';\n\nexport type CompletionShell = 'bash' | 'zsh' | 'fish';\n\nconst SHELLS: readonly CompletionShell[] = ['bash', 'zsh', 'fish'];\n\n// -- Normalised command tree --------------------------------------------------\n// commander@15 has no completion support, so we snapshot the registered tree\n// into plain data and emit a fully static script per shell (no runtime hooks).\n\ninterface OptionNode {\n /** Short flag with dash, e.g. `-c`. */\n short?: string;\n /** Long flag with dashes, e.g. `--count`. */\n long?: string;\n description: string;\n /** True when the option consumes a value (`<x>` or `[x]`). */\n takesValue: boolean;\n choices?: string[];\n}\n\ninterface ArgNode {\n name: string;\n description: string;\n variadic: boolean;\n choices?: string[];\n}\n\ninterface CommandNode {\n name: string;\n aliases: string[];\n description: string;\n /** Canonical subcommand names from the root down to this node ([] for the root itself). */\n path: string[];\n options: OptionNode[];\n args: ArgNode[];\n children: CommandNode[];\n}\n\nfunction firstLine(text: string): string {\n return (text.split('\\n')[0] ?? '').trim();\n}\n\nfunction toNode(cmd: Command, path: string[]): CommandNode {\n return {\n name: cmd.name(),\n aliases: [...cmd.aliases()],\n description: firstLine(cmd.description()),\n path,\n options: cmd.options\n .filter((o: Option) => !o.hidden)\n .map((o: Option) => ({\n short: o.short,\n long: o.long,\n description: firstLine(o.description),\n takesValue: o.required || o.optional,\n choices: o.argChoices ? [...o.argChoices] : undefined,\n })),\n args: cmd.registeredArguments.map((a: Argument) => ({\n name: a.name(),\n description: firstLine(a.description),\n variadic: a.variadic,\n choices: a.argChoices ? [...a.argChoices] : undefined,\n })),\n children: cmd.commands.map((c) => toNode(c, [...path, c.name()])),\n };\n}\n\n/** Flatten in registration order — the emitters iterate this, so output is deterministic. */\nfunction walk(node: CommandNode): CommandNode[] {\n return [node, ...node.children.flatMap(walk)];\n}\n\nfunction namesOf(node: CommandNode): string[] {\n return [node.name, ...node.aliases];\n}\n\n// -- fish ---------------------------------------------------------------------\n\nfunction fishQuote(s: string): string {\n return `'${s.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`;\n}\n\nfunction emitFish(bin: string, root: CommandNode): string {\n const lines = [\n `# fish completion for ${bin}`,\n `# Load with: ${bin} completion fish | source`,\n `# Or install: ${bin} completion fish > ~/.config/fish/completions/${bin}.fish`,\n ];\n for (const node of walk(root)) {\n const seen = node.path.map((p) => `__fish_seen_subcommand_from ${p}`);\n const childNames = node.children.flatMap(namesOf);\n const hereParts = [...seen];\n // `-f` on subcommand candidates suppresses file completion at this position;\n // positions with no matching rule keep fish's default file completion.\n if (childNames.length > 0) {\n hereParts.push(`not __fish_seen_subcommand_from ${childNames.join(' ')}`);\n }\n const here = hereParts.length > 0 ? ` -n ${fishQuote(hereParts.join('; and '))}` : '';\n for (const child of node.children) {\n for (const name of namesOf(child)) {\n lines.push(`complete -c ${bin}${here} -f -a ${name} -d ${fishQuote(child.description)}`);\n }\n }\n for (const opt of node.options) {\n let line = `complete -c ${bin}${here}`;\n if (opt.short) line += ` -s ${opt.short.replace(/^-+/, '')}`;\n if (opt.long) line += ` -l ${opt.long.replace(/^-+/, '')}`;\n if (opt.takesValue) {\n line += opt.choices ? ` -x -a ${fishQuote(opt.choices.join(' '))}` : ' -r';\n }\n line += ` -d ${fishQuote(opt.description)}`;\n lines.push(line);\n }\n const atArgs = seen.length > 0 ? ` -n ${fishQuote(seen.join('; and '))}` : '';\n for (const arg of node.args) {\n if (arg.choices) {\n const desc = arg.description || arg.name;\n lines.push(\n `complete -c ${bin}${atArgs} -f -a ${fishQuote(arg.choices.join(' '))} -d ${fishQuote(desc)}`,\n );\n }\n }\n }\n return `${lines.join('\\n')}\\n`;\n}\n\n// -- bash ---------------------------------------------------------------------\n\nfunction sanitizeIdent(bin: string): string {\n return bin.replace(/[^A-Za-z0-9_]/g, '_');\n}\n\n/**\n * Case arms that descend the known subcommand tree token by token, normalising\n * aliases to the canonical path so a single lookup table serves both spellings.\n */\nfunction descentCases(root: CommandNode, indent: string): string[] {\n return walk(root)\n .filter((node) => node.path.length > 0)\n .map((node) => {\n const parent = node.path.slice(0, -1).join(' ');\n const patterns = namesOf(node)\n .map((name) => `\"${parent ? `${parent} ${name}` : name}\"`)\n .join('|');\n return `${indent}${patterns}) path=\"${node.path.join(' ')}\" ;;`;\n });\n}\n\nfunction emitBash(bin: string, root: CommandNode): string {\n const fn = `_${sanitizeIdent(bin)}_completions`;\n const optCases = walk(root).map((node) => {\n const subs = node.children.flatMap(namesOf).join(' ');\n const flags = node.options\n .flatMap((o) => [o.short, o.long])\n .filter((f): f is string => f !== undefined)\n .join(' ');\n const args = node.args.flatMap((a) => a.choices ?? []).join(' ');\n return ` \"${node.path.join(' ')}\") subs=\"${subs}\"; flags=\"${flags}\"; args=\"${args}\" ;;`;\n });\n return [\n `# bash completion for ${bin}`,\n `# Load with: source <(${bin} completion bash)`,\n `${fn}() {`,\n ' local cur path try w i subs flags args',\n ' cur=\"${COMP_WORDS[COMP_CWORD]}\"',\n ' path=\"\"',\n ' for ((i = 1; i < COMP_CWORD; i++)); do',\n ' w=\"${COMP_WORDS[i]}\"',\n ' [[ \"$w\" == -* ]] && continue',\n ' try=\"${path:+$path }$w\"',\n ' case \"$try\" in',\n ...descentCases(root, ' '),\n ' *) ;;',\n ' esac',\n ' done',\n ' subs=\"\"; flags=\"\"; args=\"\"',\n ' case \"$path\" in',\n ...optCases,\n ' esac',\n ' if [[ \"$cur\" == -* ]]; then',\n ' COMPREPLY=($(compgen -W \"$flags\" -- \"$cur\"))',\n ' elif [[ -n \"$subs\" ]]; then',\n ' COMPREPLY=($(compgen -W \"$subs\" -- \"$cur\"))',\n ' elif [[ -n \"$args\" ]]; then',\n ' COMPREPLY=($(compgen -W \"$args\" -- \"$cur\"))',\n ' else',\n ' COMPREPLY=($(compgen -f -- \"$cur\"))',\n ' fi',\n '}',\n `complete -F ${fn} ${bin}`,\n '',\n ].join('\\n');\n}\n\n// -- zsh ----------------------------------------------------------------------\n\nfunction zshItem(name: string, description: string): string {\n const entry = `${name}:${description}`.replace(/'/g, `'\\\\''`);\n return `'${entry}'`;\n}\n\nfunction emitZsh(bin: string, root: CommandNode): string {\n const fn = `_${sanitizeIdent(bin)}`;\n const optCases = walk(root).map((node) => {\n const subs = node.children\n .flatMap((child) => namesOf(child).map((name) => zshItem(name, child.description)))\n .join(' ');\n const flags = node.options\n .flatMap((o) =>\n [o.short, o.long]\n .filter((f): f is string => f !== undefined)\n .map((f) => zshItem(f, o.description)),\n )\n .join(' ');\n const args = node.args\n .flatMap((a) => (a.choices ?? []).map((c) => zshItem(c, a.description || a.name)))\n .join(' ');\n const body = [\n subs ? `subs=(${subs})` : undefined,\n flags ? `flags=(${flags})` : undefined,\n args ? `argwords=(${args})` : undefined,\n ]\n .filter((p) => p !== undefined)\n .join('; ');\n return ` \"${node.path.join(' ')}\") ${body ? `${body} ` : ''};;`;\n });\n return [\n `#compdef ${bin}`,\n `# zsh completion for ${bin}`,\n `# Install: ${bin} completion zsh > \"\\${fpath[1]}/_${bin}\" (then restart zsh)`,\n `${fn}() {`,\n ' local -a subs flags argwords',\n ' local path=\"\" try w',\n ' for w in \"${(@)words[2,CURRENT-1]}\"; do',\n ' [[ \"$w\" == -* ]] && continue',\n ' try=\"${path:+$path }$w\"',\n ' case \"$try\" in',\n ...descentCases(root, ' '),\n ' *) ;;',\n ' esac',\n ' done',\n ' case \"$path\" in',\n ...optCases,\n ' esac',\n ' if [[ \"$PREFIX\" == -* ]]; then',\n \" (( ${#flags[@]} )) && _describe -t options 'option' flags\",\n ' elif (( ${#subs[@]} )); then',\n \" _describe -t commands 'command' subs\",\n ' elif (( ${#argwords[@]} )); then',\n \" _describe -t values 'value' argwords\",\n ' else',\n ' _files',\n ' fi',\n '}',\n `if [[ \"\\${funcstack[1]}\" == \"${fn}\" ]]; then`,\n ` ${fn} \"$@\"`,\n 'else',\n ` compdef ${fn} ${bin}`,\n 'fi',\n '',\n ].join('\\n');\n}\n\n// -- public API -----------------------------------------------------------------\n\n/**\n * Build a fully static, self-contained shell-completion script for `root`'s command\n * tree (subcommands at any depth, aliases, flags, option/argument choices). Pure:\n * output depends only on the tree, iterated in registration order.\n */\nexport function buildCompletionScript(root: Command, shell: CompletionShell): string {\n const bin = root.name();\n const tree = toNode(root, []);\n switch (shell) {\n case 'fish':\n return emitFish(bin, tree);\n case 'bash':\n return emitBash(bin, tree);\n case 'zsh':\n return emitZsh(bin, tree);\n }\n}\n\n/**\n * Build a `completion <shell>` subcommand that prints the static completion script\n * for the ROOT program (resolved by walking `.parent`) to stdout.\n */\nexport function createCompletionCommand(): Command {\n return new Command('completion')\n .description(\n 'Print a static shell-completion script for bash, zsh or fish. ' +\n 'Load it in your shell, e.g. fish: `sm-cl completion fish | source`',\n )\n .addArgument(new Argument('<shell>', 'target shell').choices(SHELLS))\n .action((shell: CompletionShell, _opts: unknown, cmd: Command) => {\n process.stdout.write(buildCompletionScript(findRoot(cmd), shell));\n });\n}\n","import { Command, Option } from 'commander';\nimport { createCompletionCommand, readPackageVersion } from '@sm-lab/core';\nimport { makeDepositKeys as realMakeDepositKeys } from '../keys';\nimport { CHAINS } from '../constants';\nimport type { ChainName, WcType } from '../constants';\nimport { toDepositDataJson, writeDepositDataFile } from '../io';\n\nconst CHAIN_CHOICES = Object.keys(CHAINS) as ChainName[];\nconst WC_TYPE_CHOICES: WcType[] = ['0x01', '0x02'];\n\n/** Injectable seam: tests pass a fake keygen so CLI parsing is verified hermetically. */\nexport interface CliDeps {\n makeDepositKeys: typeof realMakeDepositKeys;\n}\n\n/** Serialize bigint values to decimal strings; all other values pass through. */\nexport const bigintReplacer = (_k: string, v: unknown): unknown =>\n typeof v === 'bigint' ? v.toString() : v;\n\n/** Run an async action; print thrown errors to stderr and exit 1. */\nfunction run(fn: () => Promise<void>): void {\n fn().catch((err: unknown) => {\n console.error('Error:', err instanceof Error ? err.message : String(err));\n process.exit(1);\n });\n}\n\nexport function buildProgram(deps: CliDeps = { makeDepositKeys: realMakeDepositKeys }): Command {\n return (\n new Command()\n .name('sm-keys')\n .description(\n 'Generate real BLS validator deposit data for Lido SM (mainnet/hoodi); ' +\n 'human mode: deposit_data.json to stdout (or --out), mnemonic to stderr',\n )\n .version(readPackageVersion(import.meta.url))\n .addOption(\n new Option('--chain <name>', 'target chain').choices(CHAIN_CHOICES).default('hoodi'),\n )\n .option('--count <n>', 'number of validators', '1')\n .addOption(\n new Option('--type <wc>', 'withdrawal credentials type')\n .choices(WC_TYPE_CHOICES)\n .default('0x01'),\n )\n .option('--mnemonic <phrase>', 'BIP-39 mnemonic (random if omitted)')\n .option('--wc <address>', 'override withdrawal address (default: Lido vault)')\n .option('--start-index <n>', 'first validator index', '0')\n .option('-o, --out <path>', 'write deposit_data.json to <path> (else stdout)')\n .option('--json', 'emit result as JSON to stdout (mnemonic + keys with 0x-prefixed hex)')\n .addHelpText(\n 'after',\n `\nExamples:\n sm-keys 2 --json\n sm-keys --count 5 --chain mainnet --json\n sm-keys --json --out deposit_data.json`,\n )\n // `sm-keys 2` == `sm-keys --count 2`; the positional wins when both are given.\n .argument('[count]', 'number of validators (positional alias for --count)')\n // `sm-keys help` mirrors `--help` (matches the sm-recipes CLI).\n .helpCommand(true)\n .addCommand(createCompletionCommand())\n .action(\n (\n countArg: string | undefined,\n opts: {\n chain: string;\n count: string;\n type: string;\n mnemonic?: string;\n wc?: string;\n startIndex: string;\n out?: string;\n json?: boolean;\n },\n ) => {\n run(async () => {\n const result = await deps.makeDepositKeys({\n chain: opts.chain as ChainName,\n count: Number(countArg ?? opts.count),\n type: opts.type as WcType,\n mnemonic: opts.mnemonic,\n withdrawalAddress: opts.wc as `0x${string}` | undefined,\n startIndex: Number(opts.startIndex),\n });\n const { mnemonic, keys } = result;\n\n if (opts.json) {\n // Unlike human mode (mnemonic → stderr), --json deliberately includes the\n // mnemonic in the stdout JSON.\n console.log(JSON.stringify(result, bigintReplacer, 2));\n return;\n }\n\n // Human mode: mnemonic to stderr so stdout / -o stays clean JSON.\n console.error(`mnemonic: ${mnemonic}`);\n if (opts.out) {\n writeDepositDataFile(opts.out, keys);\n console.error(`wrote ${keys.length} key(s) to ${opts.out}`);\n } else {\n console.log(toDepositDataJson(keys));\n }\n });\n },\n )\n );\n}\n","#!/usr/bin/env node\n\nimport { buildProgram } from './program';\n\nbuildProgram()\n .parseAsync()\n .catch((err: unknown) => {\n console.error('Error:', err instanceof Error ? err.message : String(err));\n process.exit(1);\n });\n"],"x_google_ignoreList":[0,1],"mappings":";;;;;;;ACuCA,MAAM,gBAAgB,OAAO;AAC7B,IAAI,YAAY,cAAc,cAAc;CAC3C,YAAY,OAAO,SAAS;EAC3B,IAAI,OAAO,UAAU,YAAY,mBAAmB,OAAO;GAC1D,MAAM,qBAAqB,YAAY,KAAK,KAAK,UAAU,WAAW,QAAQ,QAAQ;GACtF,IAAI,MAAM,4BAA4B,CAAC,oBAAoB,MAAM,IAAI,UAAU,8EAA8E;GAC7J,QAAQ,MAAM,gBAAgB,CAAC;EAChC;EACA,IAAI,QAAQ,SAAS,KAAA,EAAO,cAAc,aAAa,QAAQ,WAAW;EAC1E,MAAM,OAAO,OAAO;CACrB;AACD;AACA,MAAM,0BAA0B,aAAa;CAC5C,MAAM,eAAe,CAAC;CACtB,MAAM,aAAa,SAAS;CAC5B,KAAK,IAAI,IAAI,GAAG,MAAM,WAAW,QAAQ,IAAI,KAAK,KAAK,GAAG;EACzD,MAAM,MAAM,WAAW;EACvB,IAAI,IAAI,WAAW,CAAC,MAAM,IAAI,aAAa,KAAK,CAAC,KAAK,WAAW,IAAI,EAAE,CAAC;CACzE;CACA,OAAO,IAAI,QAAQ,YAAY;AAChC;AACA,MAAM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,61 @@
1
+ //#region src/hex.d.ts
2
+ type Hex = `0x${string}`;
3
+ /** Parse a hex string (with or without 0x) into bytes. */
4
+ declare function hexToBytes(hex: string): Uint8Array;
5
+ /** Serialize bytes to a 0x-prefixed lowercase hex string. */
6
+ declare function bytesToHex(bytes: Uint8Array): Hex;
7
+ //#endregion
8
+ //#region src/constants.d.ts
9
+ type ChainName = 'mainnet' | 'hoodi';
10
+ type WcType = '0x01' | '0x02';
11
+ interface ChainConfig {
12
+ chainId: number;
13
+ forkVersion: Hex;
14
+ networkName: ChainName;
15
+ withdrawalVault: Hex;
16
+ }
17
+ /** SSZ deposit domain type (DOMAIN_DEPOSIT), per the consensus spec. */
18
+ declare const DOMAIN_DEPOSIT: Hex;
19
+ /** The only deposit amount the CSM SDK validator accepts: 32 ETH in gwei. */
20
+ declare const DEPOSIT_AMOUNT_GWEI = 32000000000;
21
+ declare const CHAINS: Record<ChainName, ChainConfig>;
22
+ //#endregion
23
+ //#region src/keys.d.ts
24
+ interface MakeDepositKeysOptions {
25
+ chain?: ChainName;
26
+ count?: number;
27
+ mnemonic?: string;
28
+ type?: WcType;
29
+ withdrawalAddress?: Hex;
30
+ startIndex?: number;
31
+ }
32
+ interface DepositKey {
33
+ pubkey: Hex;
34
+ withdrawal_credentials: Hex;
35
+ amount: number;
36
+ signature: Hex;
37
+ deposit_message_root: Hex;
38
+ deposit_data_root: Hex;
39
+ fork_version: Hex;
40
+ network_name: ChainName;
41
+ deposit_cli_version: string;
42
+ }
43
+ interface MakeDepositKeysResult {
44
+ mnemonic: string;
45
+ keys: DepositKey[];
46
+ }
47
+ /** type_byte ++ 11 zero bytes ++ 20-byte eth1 address = 32-byte 0x01/0x02 credential. */
48
+ declare function withdrawalCredentials(type: WcType, address: Hex): Uint8Array;
49
+ declare function makeDepositKeys(opts?: MakeDepositKeysOptions): Promise<MakeDepositKeysResult>;
50
+ //#endregion
51
+ //#region src/io.d.ts
52
+ /**
53
+ * Serialize keys to the eth-staking-smith / staking-deposit-cli JSON shape: a JSON array
54
+ * with hex fields rendered WITHOUT a 0x prefix. The CSM SDK parser normalizes both forms;
55
+ * matching the binary's exact shape keeps fixtures / diffs clean.
56
+ */
57
+ declare function toDepositDataJson(keys: DepositKey[]): string;
58
+ declare function writeDepositDataFile(path: string, keys: DepositKey[]): void;
59
+ //#endregion
60
+ export { CHAINS, type ChainConfig, type ChainName, DEPOSIT_AMOUNT_GWEI, DOMAIN_DEPOSIT, type DepositKey, type Hex, type MakeDepositKeysOptions, type MakeDepositKeysResult, type WcType, bytesToHex, hexToBytes, makeDepositKeys, toDepositDataJson, withdrawalCredentials, writeDepositDataFile };
61
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/hex.ts","../src/constants.ts","../src/keys.ts","../src/io.ts"],"mappings":";KAAY,GAAA;AAAZ;AAAA,iBAGgB,UAAA,CAAW,GAAA,WAAc,UAAU;;iBAWnC,UAAA,CAAW,KAAA,EAAO,UAAA,GAAa,GAAG;;;KCZtC,SAAA;AAAA,KACA,MAAA;AAAA,UAEK,WAAA;EACf,OAAA;EACA,WAAA,EAAa,GAAA;EACb,WAAA,EAAa,SAAA;EACb,eAAA,EAAiB,GAAA;AAAA;;cAIN,cAAA,EAAgB,GAAkB;ADC/C;AAAA,cCEa,mBAAA;AAAA,cAQA,MAAA,EAAQ,MAAA,CAAO,SAAA,EAAW,WAAA;;;UCTtB,sBAAA;EACf,KAAA,GAAQ,SAAA;EACR,KAAA;EACA,QAAA;EACA,IAAA,GAAO,MAAA;EACP,iBAAA,GAAoB,GAAA;EACpB,UAAA;AAAA;AAAA,UAGe,UAAA;EACf,MAAA,EAAQ,GAAA;EACR,sBAAA,EAAwB,GAAA;EACxB,MAAA;EACA,SAAA,EAAW,GAAA;EACX,oBAAA,EAAsB,GAAA;EACtB,iBAAA,EAAmB,GAAA;EACnB,YAAA,EAAc,GAAA;EACd,YAAA,EAAc,SAAA;EACd,mBAAA;AAAA;AAAA,UAGe,qBAAA;EACf,QAAA;EACA,IAAA,EAAM,UAAU;AAAA;;iBAIF,qBAAA,CAAsB,IAAA,EAAM,MAAA,EAAQ,OAAA,EAAS,GAAA,GAAM,UAAA;AAAA,iBAW7C,eAAA,CACpB,IAAA,GAAM,sBAAA,GACL,OAAA,CAAQ,qBAAA;;;AFvDX;;;;AAAe;AAAf,iBGUgB,iBAAA,CAAkB,IAAkB,EAAZ,UAAU;AAAA,iBAelC,oBAAA,CAAqB,IAAA,UAAc,IAAA,EAAM,UAAU"}
package/dist/index.mjs ADDED
@@ -0,0 +1,2 @@
1
+ import { a as bytesToHex, c as DEPOSIT_AMOUNT_GWEI, i as withdrawalCredentials, l as DOMAIN_DEPOSIT, n as writeDepositDataFile, o as hexToBytes, r as makeDepositKeys, s as CHAINS, t as toDepositDataJson } from "./io-BtF203qz.mjs";
2
+ export { CHAINS, DEPOSIT_AMOUNT_GWEI, DOMAIN_DEPOSIT, bytesToHex, hexToBytes, makeDepositKeys, toDepositDataJson, withdrawalCredentials, writeDepositDataFile };
@@ -0,0 +1,275 @@
1
+ import { SecretKey } from "@chainsafe/bls/herumi";
2
+ import { deriveEth2ValidatorKeys, deriveKeyFromMnemonic } from "@chainsafe/bls-keygen";
3
+ import { generateMnemonic, validateMnemonic } from "@scure/bip39";
4
+ import { wordlist } from "@scure/bip39/wordlists/english.js";
5
+ import { ByteVectorType, ContainerType, UintBigintType } from "@chainsafe/ssz";
6
+ import { writeFileSync } from "node:fs";
7
+ //#region src/constants.ts
8
+ /** SSZ deposit domain type (DOMAIN_DEPOSIT), per the consensus spec. */
9
+ const DOMAIN_DEPOSIT = "0x03000000";
10
+ /** The only deposit amount the CSM SDK validator accepts: 32 ETH in gwei. */
11
+ const DEPOSIT_AMOUNT_GWEI = 32e9;
12
+ /** Cosmetic deposit_data.json field; not validated on-chain or by the widget. */
13
+ const DEPOSIT_CLI_VERSION = "sm-keys/0.1.0";
14
+ const CHAINS = {
15
+ mainnet: {
16
+ chainId: 1,
17
+ forkVersion: "0x00000000",
18
+ networkName: "mainnet",
19
+ withdrawalVault: "0xB9D7934878B5FB9610B3fE8A5e441e8fad7E293f"
20
+ },
21
+ hoodi: {
22
+ chainId: 560048,
23
+ forkVersion: "0x10000910",
24
+ networkName: "hoodi",
25
+ withdrawalVault: "0x4473dCDDbf77679A643BdB654dbd86D67F8d32f2"
26
+ }
27
+ };
28
+ //#endregion
29
+ //#region ../../fixtures/receipts/dist/index.mjs
30
+ /** Default committed address books per (chain, module). cm exists for hoodi only. */
31
+ const addresses = {
32
+ hoodi: {
33
+ csm: {
34
+ CSModule: "0x79CEf36D84743222f37765204Bec41E92a93E59d",
35
+ Accounting: "0xA54b90BA34C5f326BC1485054080994e38FB4C60",
36
+ FeeDistributor: "0xaCd9820b0A2229a82dc1A0770307ce5522FF3582",
37
+ FeeOracle: "0xe7314f561B2e72f9543F1004e741bab6Fc51028B",
38
+ HashConsensus: "0x54f74a10e4397dDeF85C4854d9dfcA129D72C637",
39
+ ParametersRegistry: "0xA4aD5236963f9Fe4229864712269D8d79B65C5Ad",
40
+ ValidatorStrikes: "0x8fBA385C3c334D251eE413e79d4D3890db98693c",
41
+ Verifier: "0x1773b2Ff99A030F6000554Cb8A5Ec93145650cbA",
42
+ Ejector: "0xCAe028378d69D54dc8bF809e6C44CF751F997b80",
43
+ ExitPenalties: "0xD259b31083Be841E5C85b2D481Cfc17C14276800",
44
+ GateSeal: "0x725166f143DdcD9EC1b96dfb70f16E3f44968A65",
45
+ LidoLocator: "0xe2EF9536DAAAEBFf5b1c130957AB3E80056b06D8",
46
+ VettedGate: "0x10a254E724fe2b7f305F76f3F116a3969c53845f",
47
+ PermissionlessGate: "0xd7bD8D2A9888D1414c770B35ACF55890B15de26a",
48
+ IdentifiedDVTClusterGate: "0x887F8512F9998045f4b5993e6eaa6BCfE5F02A94",
49
+ ChainId: 560048,
50
+ "git-ref": "a6be775483e17d76718f8852428b5251a75c6429",
51
+ protocol: {
52
+ "stakingRouter": "0xCc820558B39ee15C7C45B59390B503b83fb499A8",
53
+ "validatorsExitBusOracle": "0x8664d394C2B3278F26A1B44B967aEf99707eeAB2",
54
+ "lido": "0x3508A952176b3c15387C97BE809eaffB1982176a",
55
+ "withdrawalQueue": "0xfe56573178f1bcdf53F01A6E9977670dcBBD9186",
56
+ "burner": "0xb2c99cd38a2636a6281a849C8de938B3eF4A7C3D",
57
+ "withdrawalVault": "0x4473dCDDbf77679A643BdB654dbd86D67F8d32f2"
58
+ }
59
+ },
60
+ cm: {
61
+ CuratedModule: "0x87EB69Ae51317405FD285efD2326a4a11f6173b9",
62
+ Accounting: "0x7f7356D29aCd915F1934220956c3305808ceB235",
63
+ FeeDistributor: "0x0ced6de191E2A15f7BBAf9E32307626C9f6BD0Cd",
64
+ FeeOracle: "0x5D2F27000C80f6f7A03015Fd49dB7FEba3fBfa83",
65
+ HashConsensus: "0x920883908A78c1554f682006a8aB32E62Be09F33",
66
+ ParametersRegistry: "0xefb8e4091A75C4828826bf64595F392f87A07b37",
67
+ ValidatorStrikes: "0x4c427Ec826F403339719C0FABfb3209e80939eA6",
68
+ Verifier: "0x209190Ebc2Be80367a15d05e626784Eb94d6A880",
69
+ Ejector: "0xfDbde2B3554B69C84e0f8d7daB68D390Ff0f4394",
70
+ ExitPenalties: "0xad79e1d3B380cEb1a0e188fBAB91f85A446E9E54",
71
+ MetaRegistry: "0x857289cCBFBc4C134Cc312022a104CD9b38d8AAE",
72
+ CuratedGateFactory: "0x0e26d2cC3f0c2A17D2D784068cAAD34206B6804D",
73
+ LidoLocator: "0xe2EF9536DAAAEBFf5b1c130957AB3E80056b06D8",
74
+ CuratedGates: [
75
+ "0xF1862d120831eBE31f7202378Ff3Ae63A5658ae3",
76
+ "0x410A309dF81B782190188CDB3d215729cc6bC1f3",
77
+ "0xa5A604b172787e017b1b118F02fE54fC1D696519",
78
+ "0xE966874cDB6A4282ED75Cd10439e3799e5531a2D",
79
+ "0x5c063da03e3f21443716D75a2205EE16706e1153",
80
+ "0x1cD655Ac53CfE8269DE0DBfc0140B074623C4A6B",
81
+ "0x28518be9894C20135F280a9539617783b08a04c7"
82
+ ],
83
+ ChainId: 560048,
84
+ "git-ref": "a6be775483e17d76718f8852428b5251a75c6429",
85
+ protocol: {
86
+ "stakingRouter": "0xCc820558B39ee15C7C45B59390B503b83fb499A8",
87
+ "validatorsExitBusOracle": "0x8664d394C2B3278F26A1B44B967aEf99707eeAB2",
88
+ "lido": "0x3508A952176b3c15387C97BE809eaffB1982176a",
89
+ "withdrawalQueue": "0xfe56573178f1bcdf53F01A6E9977670dcBBD9186",
90
+ "burner": "0xb2c99cd38a2636a6281a849C8de938B3eF4A7C3D",
91
+ "withdrawalVault": "0x4473dCDDbf77679A643BdB654dbd86D67F8d32f2"
92
+ }
93
+ }
94
+ },
95
+ mainnet: { csm: {
96
+ CSModule: "0xdA7dE2ECdDfccC6c3AF10108Db212ACBBf9EA83F",
97
+ Accounting: "0x4d72BFF1BeaC69925F8Bd12526a39BAAb069e5Da",
98
+ FeeDistributor: "0xD99CC66fEC647E68294C6477B40fC7E0F6F618D0",
99
+ FeeOracle: "0x4D4074628678Bd302921c20573EEa1ed38DdF7FB",
100
+ HashConsensus: "0x71093efF8D8599b5fA340D665Ad60fA7C80688e4",
101
+ ParametersRegistry: "0x9D28ad303C90DF524BA960d7a2DAC56DcC31e428",
102
+ ValidatorStrikes: "0xaa328816027F2D32B9F56d190BC9Fa4A5C07637f",
103
+ Verifier: "0xdC5FE1782B6943f318E05230d688713a560063DC",
104
+ Ejector: "0xc72b58aa02E0e98cF8A4a0E9Dce75e763800802C",
105
+ ExitPenalties: "0x06cd61045f958A209a0f8D746e103eCc625f4193",
106
+ GateSeal: "0xE1686C2E90eb41a48356c1cC7FaA17629af3ADB3",
107
+ LidoLocator: "0xC1d0b3DE6792Bf6b4b37EccdcC24e45978Cfd2Eb",
108
+ VettedGate: "0xB314D4A76C457c93150d308787939063F4Cc67E0",
109
+ PermissionlessGate: "0xcF33a38111d0B1246A3F38a838fb41D626B454f0",
110
+ ChainId: 1,
111
+ "git-ref": "cc8409a8ac21d7816d572658077dd6cf5f61507f",
112
+ protocol: {
113
+ "stakingRouter": "0xFdDf38947aFB03C621C71b06C9C70bce73f12999",
114
+ "validatorsExitBusOracle": "0x0De4Ea0184c2ad0BacA7183356Aea5B8d5Bf5c6e",
115
+ "lido": "0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84",
116
+ "withdrawalQueue": "0x889edC2eDab5f40e902b864aD4d7AdE8E412F9B1",
117
+ "burner": "0xE76c52750019b80B43E36DF30bf4060EB73F573a",
118
+ "withdrawalVault": "0xB9D7934878B5FB9610B3fE8A5e441e8fad7E293f"
119
+ }
120
+ } }
121
+ };
122
+ //#endregion
123
+ //#region src/receipts.ts
124
+ /** The baked Lido WithdrawalVault for a chainId, or undefined if no receipts book has been enriched. */
125
+ function protocolWithdrawalVault(chainId, books = addresses) {
126
+ return Object.values(books).flatMap((m) => Object.values(m)).find((b) => b.ChainId === chainId)?.protocol?.withdrawalVault;
127
+ }
128
+ //#endregion
129
+ //#region src/hex.ts
130
+ /** Parse a hex string (with or without 0x) into bytes. */
131
+ function hexToBytes(hex) {
132
+ const h = hex.startsWith("0x") ? hex.slice(2) : hex;
133
+ if (h.length % 2 !== 0) throw new Error(`hex string has odd length: ${hex}`);
134
+ const out = new Uint8Array(h.length / 2);
135
+ for (let i = 0; i < out.length; i++) out[i] = Number.parseInt(h.slice(i * 2, i * 2 + 2), 16);
136
+ return out;
137
+ }
138
+ /** Serialize bytes to a 0x-prefixed lowercase hex string. */
139
+ function bytesToHex(bytes) {
140
+ let s = "0x";
141
+ for (const b of bytes) s += b.toString(16).padStart(2, "0");
142
+ return s;
143
+ }
144
+ //#endregion
145
+ //#region src/ssz.ts
146
+ const DepositMessage = new ContainerType({
147
+ pubkey: new ByteVectorType(48),
148
+ withdrawal_credentials: new ByteVectorType(32),
149
+ amount: new UintBigintType(8)
150
+ });
151
+ const DepositData = new ContainerType({
152
+ pubkey: new ByteVectorType(48),
153
+ withdrawal_credentials: new ByteVectorType(32),
154
+ amount: new UintBigintType(8),
155
+ signature: new ByteVectorType(96)
156
+ });
157
+ const ForkData = new ContainerType({
158
+ current_version: new ByteVectorType(4),
159
+ genesis_validators_root: new ByteVectorType(32)
160
+ });
161
+ const SigningData = new ContainerType({
162
+ object_root: new ByteVectorType(32),
163
+ domain: new ByteVectorType(32)
164
+ });
165
+ function computeForkDataRoot(currentVersion, genesisValidatorsRoot) {
166
+ return ForkData.hashTreeRoot({
167
+ current_version: currentVersion,
168
+ genesis_validators_root: genesisValidatorsRoot
169
+ });
170
+ }
171
+ /** compute_domain(DOMAIN_DEPOSIT, forkVersion, genesisValidatorsRoot=zeros). */
172
+ function computeDomain(forkVersion) {
173
+ const forkDataRoot = computeForkDataRoot(forkVersion, /* @__PURE__ */ new Uint8Array(32));
174
+ const domain = /* @__PURE__ */ new Uint8Array(32);
175
+ domain.set(hexToBytes(DOMAIN_DEPOSIT), 0);
176
+ domain.set(forkDataRoot.slice(0, 28), 4);
177
+ return domain;
178
+ }
179
+ function computeSigningRoot(objectRoot, domain) {
180
+ return SigningData.hashTreeRoot({
181
+ object_root: objectRoot,
182
+ domain
183
+ });
184
+ }
185
+ //#endregion
186
+ //#region src/keys.ts
187
+ /** type_byte ++ 11 zero bytes ++ 20-byte eth1 address = 32-byte 0x01/0x02 credential. */
188
+ function withdrawalCredentials(type, address) {
189
+ const addr = hexToBytes(address);
190
+ if (addr.length !== 20) throw new Error(`withdrawal address must be 20 bytes, got ${addr.length}`);
191
+ const wc = /* @__PURE__ */ new Uint8Array(32);
192
+ wc[0] = type === "0x02" ? 2 : 1;
193
+ wc.set(addr, 12);
194
+ return wc;
195
+ }
196
+ async function makeDepositKeys(opts = {}) {
197
+ const chain = opts.chain ?? "hoodi";
198
+ const count = opts.count ?? 1;
199
+ const type = opts.type ?? "0x01";
200
+ const startIndex = opts.startIndex ?? 0;
201
+ const cfg = CHAINS[chain];
202
+ if (!cfg) throw new Error(`unknown chain: ${String(chain)} (expected mainnet | hoodi)`);
203
+ if (!Number.isInteger(count) || count < 1) throw new Error(`count must be a positive integer, got ${count}`);
204
+ if (type !== "0x01" && type !== "0x02") throw new Error(`type must be 0x01 or 0x02, got ${String(type)}`);
205
+ const mnemonic = opts.mnemonic ?? generateMnemonic(wordlist, 128);
206
+ if (!validateMnemonic(mnemonic, wordlist)) throw new Error("invalid BIP-39 mnemonic");
207
+ const baked = protocolWithdrawalVault(cfg.chainId);
208
+ const wc = withdrawalCredentials(type, opts.withdrawalAddress ?? baked ?? cfg.withdrawalVault);
209
+ const amount = BigInt(DEPOSIT_AMOUNT_GWEI);
210
+ const domain = computeDomain(hexToBytes(cfg.forkVersion));
211
+ const master = deriveKeyFromMnemonic(mnemonic);
212
+ const keys = [];
213
+ for (let i = 0; i < count; i++) {
214
+ const { signing } = deriveEth2ValidatorKeys(master, startIndex + i);
215
+ const sk = SecretKey.fromBytes(signing);
216
+ const pubkey = sk.toPublicKey().toBytes();
217
+ const messageRoot = DepositMessage.hashTreeRoot({
218
+ pubkey,
219
+ withdrawal_credentials: wc,
220
+ amount
221
+ });
222
+ const signingRoot = computeSigningRoot(messageRoot, domain);
223
+ const signature = sk.sign(signingRoot).toBytes();
224
+ const dataRoot = DepositData.hashTreeRoot({
225
+ pubkey,
226
+ withdrawal_credentials: wc,
227
+ amount,
228
+ signature
229
+ });
230
+ keys.push({
231
+ pubkey: bytesToHex(pubkey),
232
+ withdrawal_credentials: bytesToHex(wc),
233
+ amount: DEPOSIT_AMOUNT_GWEI,
234
+ signature: bytesToHex(signature),
235
+ deposit_message_root: bytesToHex(messageRoot),
236
+ deposit_data_root: bytesToHex(dataRoot),
237
+ fork_version: cfg.forkVersion,
238
+ network_name: cfg.networkName,
239
+ deposit_cli_version: DEPOSIT_CLI_VERSION
240
+ });
241
+ }
242
+ return {
243
+ mnemonic,
244
+ keys
245
+ };
246
+ }
247
+ //#endregion
248
+ //#region src/io.ts
249
+ const strip = (hex) => hex.startsWith("0x") ? hex.slice(2) : hex;
250
+ /**
251
+ * Serialize keys to the eth-staking-smith / staking-deposit-cli JSON shape: a JSON array
252
+ * with hex fields rendered WITHOUT a 0x prefix. The CSM SDK parser normalizes both forms;
253
+ * matching the binary's exact shape keeps fixtures / diffs clean.
254
+ */
255
+ function toDepositDataJson(keys) {
256
+ const out = keys.map((k) => ({
257
+ pubkey: strip(k.pubkey),
258
+ withdrawal_credentials: strip(k.withdrawal_credentials),
259
+ amount: k.amount,
260
+ signature: strip(k.signature),
261
+ deposit_message_root: strip(k.deposit_message_root),
262
+ deposit_data_root: strip(k.deposit_data_root),
263
+ fork_version: strip(k.fork_version),
264
+ network_name: k.network_name,
265
+ deposit_cli_version: k.deposit_cli_version
266
+ }));
267
+ return JSON.stringify(out, null, 2);
268
+ }
269
+ function writeDepositDataFile(path, keys) {
270
+ writeFileSync(path, toDepositDataJson(keys));
271
+ }
272
+ //#endregion
273
+ export { bytesToHex as a, DEPOSIT_AMOUNT_GWEI as c, withdrawalCredentials as i, DOMAIN_DEPOSIT as l, writeDepositDataFile as n, hexToBytes as o, makeDepositKeys as r, CHAINS as s, toDepositDataJson as t };
274
+
275
+ //# sourceMappingURL=io-BtF203qz.mjs.map